From c758052cdc573c815b77f4341323f18c39767313 Mon Sep 17 00:00:00 2001 From: yuanjm Date: Tue, 28 Jul 2020 17:21:55 +0800 Subject: [PATCH] feat(modbus): Bring freemodbus component and example from IDF Commit ID: d0b9829e --- components/freemodbus/CMakeLists.txt | 59 ++ components/freemodbus/Kconfig | 199 ++++ .../freemodbus/common/esp_modbus_callbacks.h | 29 + .../freemodbus/common/esp_modbus_master.c | 244 +++++ .../common/esp_modbus_master_serial.c | 41 + .../freemodbus/common/esp_modbus_master_tcp.c | 33 + .../freemodbus/common/esp_modbus_slave.c | 231 +++++ .../common/esp_modbus_slave_serial.c | 44 + .../freemodbus/common/esp_modbus_slave_tcp.c | 33 + .../common/include/esp_modbus_common.h | 156 +++ .../common/include/esp_modbus_master.h | 270 +++++ .../common/include/esp_modbus_slave.h | 152 +++ .../freemodbus/common/include/mbcontroller.h | 32 + components/freemodbus/common/mbc_master.h | 106 ++ components/freemodbus/common/mbc_slave.h | 94 ++ components/freemodbus/component.mk | 14 + components/freemodbus/modbus/ascii/mbascii.c | 473 +++++++++ components/freemodbus/modbus/ascii/mbascii.h | 78 ++ .../freemodbus/modbus/ascii/mbascii_m.c | 573 +++++++++++ .../freemodbus/modbus/functions/mbfunccoils.c | 273 +++++ .../modbus/functions/mbfunccoils_m.c | 391 ++++++++ .../freemodbus/modbus/functions/mbfuncdiag.c | 29 + .../freemodbus/modbus/functions/mbfuncdisc.c | 126 +++ .../modbus/functions/mbfuncdisc_m.c | 162 +++ .../modbus/functions/mbfuncholding.c | 311 ++++++ .../modbus/functions/mbfuncholding_m.c | 455 +++++++++ .../freemodbus/modbus/functions/mbfuncinput.c | 126 +++ .../modbus/functions/mbfuncinput_m.c | 147 +++ .../freemodbus/modbus/functions/mbfuncother.c | 92 ++ .../freemodbus/modbus/functions/mbutils.c | 141 +++ components/freemodbus/modbus/include/mb.h | 417 ++++++++ components/freemodbus/modbus/include/mb_m.h | 410 ++++++++ .../freemodbus/modbus/include/mbconfig.h | 170 ++++ .../freemodbus/modbus/include/mbframe.h | 103 ++ components/freemodbus/modbus/include/mbfunc.h | 80 ++ components/freemodbus/modbus/include/mbport.h | 247 +++++ .../freemodbus/modbus/include/mbproto.h | 83 ++ .../freemodbus/modbus/include/mbutils.h | 108 ++ components/freemodbus/modbus/mb.c | 428 ++++++++ components/freemodbus/modbus/mb_m.c | 547 ++++++++++ components/freemodbus/modbus/rtu/mbcrc.c | 103 ++ components/freemodbus/modbus/rtu/mbcrc.h | 36 + components/freemodbus/modbus/rtu/mbrtu.c | 350 +++++++ components/freemodbus/modbus/rtu/mbrtu.h | 69 ++ components/freemodbus/modbus/rtu/mbrtu_m.c | 408 ++++++++ components/freemodbus/modbus/tcp/mbtcp.c | 152 +++ components/freemodbus/modbus/tcp/mbtcp.h | 56 ++ components/freemodbus/modbus/tcp/mbtcp_m.c | 152 +++ components/freemodbus/modbus/tcp/mbtcp_m.h | 57 ++ components/freemodbus/port/port.c | 146 +++ components/freemodbus/port/port.h | 145 +++ components/freemodbus/port/portevent.c | 132 +++ components/freemodbus/port/portevent_m.c | 317 ++++++ components/freemodbus/port/portother.c | 76 ++ components/freemodbus/port/portother_m.c | 71 ++ components/freemodbus/port/portserial.c | 286 ++++++ components/freemodbus/port/portserial_m.c | 279 ++++++ components/freemodbus/port/porttimer.c | 154 +++ components/freemodbus/port/porttimer_m.c | 199 ++++ components/freemodbus/sdkconfig.rename | 18 + .../modbus_controller/mbc_serial_master.c | 705 +++++++++++++ .../modbus_controller/mbc_serial_master.h | 38 + .../serial_master/port/port_serial_master.h | 65 ++ .../modbus_controller/mbc_serial_slave.c | 521 ++++++++++ .../modbus_controller/mbc_serial_slave.h | 40 + .../serial_slave/port/port_serial_slave.h | 67 ++ .../modbus_controller/mbc_tcp_master.c | 716 +++++++++++++ .../modbus_controller/mbc_tcp_master.h | 43 + .../tcp_master/port/port_tcp_master.c | 941 ++++++++++++++++++ .../tcp_master/port/port_tcp_master.h | 133 +++ .../modbus_controller/mbc_tcp_slave.c | 484 +++++++++ .../modbus_controller/mbc_tcp_slave.h | 41 + .../tcp_slave/port/port_tcp_slave.c | 709 +++++++++++++ .../tcp_slave/port/port_tcp_slave.h | 113 +++ .../modbus/mb_example_common/CMakeLists.txt | 6 + .../modbus/mb_example_common/README.md | 10 + .../modbus/mb_example_common/component.mk | 5 + .../mb_example_common/include/modbus_params.h | 62 ++ .../modbus/mb_example_common/modbus_params.c | 17 + examples/protocols/modbus/serial/README.md | 82 ++ .../protocols/modbus/serial/example_test.py | 288 ++++++ .../modbus/serial/mb_master/CMakeLists.txt | 8 + .../modbus/serial/mb_master/Makefile | 11 + .../modbus/serial/mb_master/README.md | 155 +++ .../serial/mb_master/main/CMakeLists.txt | 5 + .../serial/mb_master/main/Kconfig.projbuild | 66 ++ .../modbus/serial/mb_master/main/component.mk | 4 + .../modbus/serial/mb_master/main/master.c | 320 ++++++ .../serial/mb_master/sdkconfig.defaults | 11 + .../modbus/serial/mb_slave/CMakeLists.txt | 9 + .../protocols/modbus/serial/mb_slave/Makefile | 11 + .../modbus/serial/mb_slave/README.md | 96 ++ .../serial/mb_slave/main/CMakeLists.txt | 4 + .../serial/mb_slave/main/Kconfig.projbuild | 75 ++ .../modbus/serial/mb_slave/main/component.mk | 4 + .../modbus/serial/mb_slave/main/slave.c | 202 ++++ .../modbus/serial/mb_slave/sdkconfig.defaults | 10 + examples/protocols/modbus/tcp/README.md | 58 ++ examples/protocols/modbus/tcp/example_test.py | 303 ++++++ .../modbus/tcp/mb_tcp_master/CMakeLists.txt | 11 + .../modbus/tcp/mb_tcp_master/Makefile | 11 + .../modbus/tcp/mb_tcp_master/README.md | 143 +++ .../tcp/mb_tcp_master/main/CMakeLists.txt | 5 + .../tcp/mb_tcp_master/main/Kconfig.projbuild | 16 + .../tcp/mb_tcp_master/main/component.mk | 4 + .../tcp/mb_tcp_master/main/tcp_master.c | 600 +++++++++++ .../tcp/mb_tcp_master/sdkconfig.defaults | 19 + .../modbus/tcp/mb_tcp_slave/CMakeLists.txt | 13 + .../modbus/tcp/mb_tcp_slave/Makefile | 11 + .../modbus/tcp/mb_tcp_slave/README.md | 83 ++ .../tcp/mb_tcp_slave/main/CMakeLists.txt | 4 + .../tcp/mb_tcp_slave/main/Kconfig.projbuild | 18 + .../modbus/tcp/mb_tcp_slave/main/component.mk | 4 + .../modbus/tcp/mb_tcp_slave/main/tcp_slave.c | 289 ++++++ .../tcp/mb_tcp_slave/sdkconfig.defaults | 21 + 115 files changed, 18603 insertions(+) create mode 100644 components/freemodbus/CMakeLists.txt create mode 100644 components/freemodbus/Kconfig create mode 100644 components/freemodbus/common/esp_modbus_callbacks.h create mode 100644 components/freemodbus/common/esp_modbus_master.c create mode 100644 components/freemodbus/common/esp_modbus_master_serial.c create mode 100644 components/freemodbus/common/esp_modbus_master_tcp.c create mode 100644 components/freemodbus/common/esp_modbus_slave.c create mode 100644 components/freemodbus/common/esp_modbus_slave_serial.c create mode 100644 components/freemodbus/common/esp_modbus_slave_tcp.c create mode 100644 components/freemodbus/common/include/esp_modbus_common.h create mode 100644 components/freemodbus/common/include/esp_modbus_master.h create mode 100644 components/freemodbus/common/include/esp_modbus_slave.h create mode 100644 components/freemodbus/common/include/mbcontroller.h create mode 100644 components/freemodbus/common/mbc_master.h create mode 100644 components/freemodbus/common/mbc_slave.h create mode 100644 components/freemodbus/component.mk create mode 100644 components/freemodbus/modbus/ascii/mbascii.c create mode 100644 components/freemodbus/modbus/ascii/mbascii.h create mode 100644 components/freemodbus/modbus/ascii/mbascii_m.c create mode 100644 components/freemodbus/modbus/functions/mbfunccoils.c create mode 100644 components/freemodbus/modbus/functions/mbfunccoils_m.c create mode 100644 components/freemodbus/modbus/functions/mbfuncdiag.c create mode 100644 components/freemodbus/modbus/functions/mbfuncdisc.c create mode 100644 components/freemodbus/modbus/functions/mbfuncdisc_m.c create mode 100644 components/freemodbus/modbus/functions/mbfuncholding.c create mode 100644 components/freemodbus/modbus/functions/mbfuncholding_m.c create mode 100644 components/freemodbus/modbus/functions/mbfuncinput.c create mode 100644 components/freemodbus/modbus/functions/mbfuncinput_m.c create mode 100644 components/freemodbus/modbus/functions/mbfuncother.c create mode 100644 components/freemodbus/modbus/functions/mbutils.c create mode 100644 components/freemodbus/modbus/include/mb.h create mode 100644 components/freemodbus/modbus/include/mb_m.h create mode 100644 components/freemodbus/modbus/include/mbconfig.h create mode 100644 components/freemodbus/modbus/include/mbframe.h create mode 100644 components/freemodbus/modbus/include/mbfunc.h create mode 100644 components/freemodbus/modbus/include/mbport.h create mode 100644 components/freemodbus/modbus/include/mbproto.h create mode 100644 components/freemodbus/modbus/include/mbutils.h create mode 100644 components/freemodbus/modbus/mb.c create mode 100644 components/freemodbus/modbus/mb_m.c create mode 100644 components/freemodbus/modbus/rtu/mbcrc.c create mode 100644 components/freemodbus/modbus/rtu/mbcrc.h create mode 100644 components/freemodbus/modbus/rtu/mbrtu.c create mode 100644 components/freemodbus/modbus/rtu/mbrtu.h create mode 100644 components/freemodbus/modbus/rtu/mbrtu_m.c create mode 100644 components/freemodbus/modbus/tcp/mbtcp.c create mode 100644 components/freemodbus/modbus/tcp/mbtcp.h create mode 100644 components/freemodbus/modbus/tcp/mbtcp_m.c create mode 100644 components/freemodbus/modbus/tcp/mbtcp_m.h create mode 100644 components/freemodbus/port/port.c create mode 100644 components/freemodbus/port/port.h create mode 100644 components/freemodbus/port/portevent.c create mode 100644 components/freemodbus/port/portevent_m.c create mode 100644 components/freemodbus/port/portother.c create mode 100644 components/freemodbus/port/portother_m.c create mode 100644 components/freemodbus/port/portserial.c create mode 100644 components/freemodbus/port/portserial_m.c create mode 100644 components/freemodbus/port/porttimer.c create mode 100644 components/freemodbus/port/porttimer_m.c create mode 100644 components/freemodbus/sdkconfig.rename create mode 100644 components/freemodbus/serial_master/modbus_controller/mbc_serial_master.c create mode 100644 components/freemodbus/serial_master/modbus_controller/mbc_serial_master.h create mode 100644 components/freemodbus/serial_master/port/port_serial_master.h create mode 100644 components/freemodbus/serial_slave/modbus_controller/mbc_serial_slave.c create mode 100644 components/freemodbus/serial_slave/modbus_controller/mbc_serial_slave.h create mode 100644 components/freemodbus/serial_slave/port/port_serial_slave.h create mode 100644 components/freemodbus/tcp_master/modbus_controller/mbc_tcp_master.c create mode 100644 components/freemodbus/tcp_master/modbus_controller/mbc_tcp_master.h create mode 100644 components/freemodbus/tcp_master/port/port_tcp_master.c create mode 100644 components/freemodbus/tcp_master/port/port_tcp_master.h create mode 100644 components/freemodbus/tcp_slave/modbus_controller/mbc_tcp_slave.c create mode 100644 components/freemodbus/tcp_slave/modbus_controller/mbc_tcp_slave.h create mode 100644 components/freemodbus/tcp_slave/port/port_tcp_slave.c create mode 100644 components/freemodbus/tcp_slave/port/port_tcp_slave.h create mode 100644 examples/protocols/modbus/mb_example_common/CMakeLists.txt create mode 100644 examples/protocols/modbus/mb_example_common/README.md create mode 100644 examples/protocols/modbus/mb_example_common/component.mk create mode 100644 examples/protocols/modbus/mb_example_common/include/modbus_params.h create mode 100644 examples/protocols/modbus/mb_example_common/modbus_params.c create mode 100644 examples/protocols/modbus/serial/README.md create mode 100644 examples/protocols/modbus/serial/example_test.py create mode 100644 examples/protocols/modbus/serial/mb_master/CMakeLists.txt create mode 100644 examples/protocols/modbus/serial/mb_master/Makefile create mode 100644 examples/protocols/modbus/serial/mb_master/README.md create mode 100644 examples/protocols/modbus/serial/mb_master/main/CMakeLists.txt create mode 100644 examples/protocols/modbus/serial/mb_master/main/Kconfig.projbuild create mode 100644 examples/protocols/modbus/serial/mb_master/main/component.mk create mode 100644 examples/protocols/modbus/serial/mb_master/main/master.c create mode 100644 examples/protocols/modbus/serial/mb_master/sdkconfig.defaults create mode 100644 examples/protocols/modbus/serial/mb_slave/CMakeLists.txt create mode 100644 examples/protocols/modbus/serial/mb_slave/Makefile create mode 100644 examples/protocols/modbus/serial/mb_slave/README.md create mode 100644 examples/protocols/modbus/serial/mb_slave/main/CMakeLists.txt create mode 100644 examples/protocols/modbus/serial/mb_slave/main/Kconfig.projbuild create mode 100644 examples/protocols/modbus/serial/mb_slave/main/component.mk create mode 100644 examples/protocols/modbus/serial/mb_slave/main/slave.c create mode 100644 examples/protocols/modbus/serial/mb_slave/sdkconfig.defaults create mode 100644 examples/protocols/modbus/tcp/README.md create mode 100644 examples/protocols/modbus/tcp/example_test.py create mode 100644 examples/protocols/modbus/tcp/mb_tcp_master/CMakeLists.txt create mode 100644 examples/protocols/modbus/tcp/mb_tcp_master/Makefile create mode 100644 examples/protocols/modbus/tcp/mb_tcp_master/README.md create mode 100644 examples/protocols/modbus/tcp/mb_tcp_master/main/CMakeLists.txt create mode 100644 examples/protocols/modbus/tcp/mb_tcp_master/main/Kconfig.projbuild create mode 100644 examples/protocols/modbus/tcp/mb_tcp_master/main/component.mk create mode 100644 examples/protocols/modbus/tcp/mb_tcp_master/main/tcp_master.c create mode 100644 examples/protocols/modbus/tcp/mb_tcp_master/sdkconfig.defaults create mode 100644 examples/protocols/modbus/tcp/mb_tcp_slave/CMakeLists.txt create mode 100644 examples/protocols/modbus/tcp/mb_tcp_slave/Makefile create mode 100644 examples/protocols/modbus/tcp/mb_tcp_slave/README.md create mode 100644 examples/protocols/modbus/tcp/mb_tcp_slave/main/CMakeLists.txt create mode 100644 examples/protocols/modbus/tcp/mb_tcp_slave/main/Kconfig.projbuild create mode 100644 examples/protocols/modbus/tcp/mb_tcp_slave/main/component.mk create mode 100644 examples/protocols/modbus/tcp/mb_tcp_slave/main/tcp_slave.c create mode 100644 examples/protocols/modbus/tcp/mb_tcp_slave/sdkconfig.defaults diff --git a/components/freemodbus/CMakeLists.txt b/components/freemodbus/CMakeLists.txt new file mode 100644 index 00000000..43765eab --- /dev/null +++ b/components/freemodbus/CMakeLists.txt @@ -0,0 +1,59 @@ +# The following five lines of boilerplate have to be in your project's +# CMakeLists in this exact order for cmake to work correctly +set(srcs + "common/esp_modbus_master.c" + "common/esp_modbus_slave.c" + "modbus/mb.c" + "modbus/mb_m.c" + "modbus/ascii/mbascii.c" + "modbus/ascii/mbascii_m.c" + "modbus/rtu/mbrtu_m.c" + "modbus/rtu/mbrtu.c" + "modbus/rtu/mbcrc.c" + "modbus/tcp/mbtcp.c" + "modbus/tcp/mbtcp_m.c" + "port/port.c" + "port/portevent.c" + "port/portevent_m.c" + "port/portother.c" + "port/portother_m.c" + "port/portserial.c" + "port/portserial_m.c" + "port/porttimer.c" + "port/porttimer_m.c" + "modbus/functions/mbfunccoils.c" + "modbus/functions/mbfunccoils_m.c" + "modbus/functions/mbfuncdiag.c" + "modbus/functions/mbfuncdisc.c" + "modbus/functions/mbfuncdisc_m.c" + "modbus/functions/mbfuncholding.c" + "modbus/functions/mbfuncholding_m.c" + "modbus/functions/mbfuncinput.c" + "modbus/functions/mbfuncinput_m.c" + "modbus/functions/mbfuncother.c" + "modbus/functions/mbutils.c" + "serial_slave/modbus_controller/mbc_serial_slave.c" + "serial_master/modbus_controller/mbc_serial_master.c" + "tcp_slave/port/port_tcp_slave.c" + "tcp_slave/modbus_controller/mbc_tcp_slave.c" + "tcp_master/modbus_controller/mbc_tcp_master.c" + "tcp_master/port/port_tcp_master.c" + "common/esp_modbus_master_tcp.c" + "common/esp_modbus_slave_tcp.c" + "common/esp_modbus_master_serial.c" + "common/esp_modbus_slave_serial.c") + +set(include_dirs common/include) + +set(priv_include_dirs common port modbus modbus/ascii modbus/functions + modbus/rtu modbus/tcp modbus/include) + +list(APPEND priv_include_dirs serial_slave/port serial_slave/modbus_controller + serial_master/port serial_master/modbus_controller + tcp_slave/port tcp_slave/modbus_controller + tcp_master/port tcp_master/modbus_controller) + +idf_component_register(SRCS "${srcs}" + INCLUDE_DIRS "${include_dirs}" + PRIV_INCLUDE_DIRS "${priv_include_dirs}" + REQUIRES driver) diff --git a/components/freemodbus/Kconfig b/components/freemodbus/Kconfig new file mode 100644 index 00000000..e88f18a0 --- /dev/null +++ b/components/freemodbus/Kconfig @@ -0,0 +1,199 @@ +menu "Modbus configuration" + + config FMB_COMM_MODE_TCP_EN + bool "Enable Modbus stack support for TCP communication mode" + default y + help + Enable Modbus TCP option for stack. + + config FMB_TCP_PORT_DEFAULT + int "Modbus TCP port number" + range 0 65535 + default 502 + depends on FMB_COMM_MODE_TCP_EN + help + Modbus default port number used by Modbus TCP stack + + config FMB_TCP_PORT_MAX_CONN + int "Maximum allowed connections for TCP stack" + range 1 6 + default 5 + depends on FMB_COMM_MODE_TCP_EN + help + Maximum allowed connections number for Modbus TCP stack. + This is used by Modbus master and slave port layer to establish connections. + This parameter may decrease performance of Modbus stack and can cause + increasing of processing time (increase only if absolutely necessary). + + config FMB_TCP_CONNECTION_TOUT_SEC + int "Modbus TCP connection timeout" + range 1 3600 + default 20 + depends on FMB_COMM_MODE_TCP_EN + help + Modbus TCP connection timeout in seconds. + Once expired the current connection with the client will be closed + and Modbus slave will be waiting for new connection to accept. + + config FMB_COMM_MODE_RTU_EN + bool "Enable Modbus stack support for RTU mode" + default y + help + Enable RTU Modbus communication mode option for Modbus serial stack. + + config FMB_COMM_MODE_ASCII_EN + bool "Enable Modbus stack support for ASCII mode" + default y + help + Enable ASCII Modbus communication mode option for Modbus serial stack. + + config FMB_MASTER_TIMEOUT_MS_RESPOND + int "Slave respond timeout (Milliseconds)" + default 150 + range 50 3000 + help + If master sends a frame which is not broadcast, it has to wait sometime for slave response. + if slave is not respond in this time, the master will process timeout error. + + config FMB_MASTER_DELAY_MS_CONVERT + int "Slave conversion delay (Milliseconds)" + default 200 + range 50 400 + help + If master sends a broadcast frame, it has to wait conversion time to delay, + then master can send next frame. + + config FMB_QUEUE_LENGTH + int "Modbus serial task queue length" + range 0 200 + default 20 + help + Modbus serial driver queue length. It is used by event queue task. + See the serial driver API for more information. + + config FMB_PORT_TASK_STACK_SIZE + int "Modbus port task stack size" + range 2048 8192 + default 4096 + help + Modbus port task stack size for rx/tx event processing. + It may be adjusted when debugging is enabled (for example). + + config FMB_SERIAL_BUF_SIZE + int "Modbus serial task RX/TX buffer size" + range 0 2048 + default 256 + help + Modbus serial task RX and TX buffer size for UART driver initialization. + This buffer is used for modbus frame transfer. The Modbus protocol maximum + frame size is 256 bytes. Bigger size can be used for non standard implementations. + + config FMB_SERIAL_ASCII_BITS_PER_SYMB + int "Number of data bits per ASCII character" + default 8 + range 7 8 + depends on FMB_COMM_MODE_ASCII_EN + help + This option defines the number of data bits per ASCII character. + + config FMB_SERIAL_ASCII_TIMEOUT_RESPOND_MS + int "Response timeout for ASCII communication mode (ms)" + default 1000 + range 300 2000 + depends on FMB_COMM_MODE_ASCII_EN + help + This option defines response timeout of slave in milliseconds for ASCII communication mode. + Thus the timeout will expire and allow the master program to handle the error. + + config FMB_PORT_TASK_PRIO + int "Modbus port task priority" + range 3 10 + default 10 + help + Modbus port data processing task priority. + The priority of Modbus controller task is equal to (CONFIG_FMB_PORT_TASK_PRIO - 1). + + config FMB_CONTROLLER_SLAVE_ID_SUPPORT + bool "Modbus controller slave ID support" + default y + help + Modbus slave ID support enable. + When enabled the Modbus command is supported by stack. + + config FMB_CONTROLLER_SLAVE_ID + hex "Modbus controller slave ID" + range 0 4294967295 + default 0x00112233 + depends on FMB_CONTROLLER_SLAVE_ID_SUPPORT + help + Modbus slave ID value to identify modbus device + in the network using command. + Most significant byte of ID is used as short device ID and + other three bytes used as long ID. + + config FMB_CONTROLLER_NOTIFY_TIMEOUT + int "Modbus controller notification timeout (ms)" + range 0 200 + default 20 + help + Modbus controller notification timeout in milliseconds. + This timeout is used to send notification about accessed parameters. + + config FMB_CONTROLLER_NOTIFY_QUEUE_SIZE + int "Modbus controller notification queue size" + range 0 200 + default 20 + help + Modbus controller notification queue size. + The notification queue is used to get information about accessed parameters. + + config FMB_CONTROLLER_STACK_SIZE + int "Modbus controller stack size" + range 0 8192 + default 4096 + help + Modbus controller task stack size. The Stack size may be adjusted when + debug mode is used which requires more stack size (for example). + + config FMB_EVENT_QUEUE_TIMEOUT + int "Modbus stack event queue timeout (ms)" + range 0 500 + default 20 + help + Modbus stack event queue timeout in milliseconds. This may help to optimize + Modbus stack event processing time. + + config FMB_TIMER_PORT_ENABLED + bool "Modbus slave stack use timer for 3.5T symbol time measurement" + default y + help + If this option is set the Modbus stack uses timer for T3.5 time measurement. + Else the internal UART TOUT timeout is used for 3.5T symbol time measurement. + + config FMB_TIMER_GROUP + int "Modbus Timer group number" + range 0 1 + default 0 + help + Modbus Timer group number that is used for timeout measurement. + + config FMB_TIMER_INDEX + int "Modbus Timer index in the group" + range 0 1 + default 0 + help + Modbus Timer Index in the group that is used for timeout measurement. + + config FMB_TIMER_ISR_IN_IRAM + bool "Place timer interrupt handler into IRAM" + default n + select UART_ISR_IN_IRAM + help + This option places Modbus timer IRQ handler into IRAM. + This allows to avoid delays related to processing of non-IRAM-safe interrupts + during a flash write operation (NVS updating a value, or some other + flash API which has to perform an read/write operation and disable CPU cache). + This option has dependency with the UART_ISR_IN_IRAM option which places UART interrupt + handler into IRAM to prevent delays related to processing of UART events. + +endmenu diff --git a/components/freemodbus/common/esp_modbus_callbacks.h b/components/freemodbus/common/esp_modbus_callbacks.h new file mode 100644 index 00000000..d9875a62 --- /dev/null +++ b/components/freemodbus/common/esp_modbus_callbacks.h @@ -0,0 +1,29 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +// Stack callback functions prototypes + +#ifndef _ESP_MODBUS_CALLBACKS_H_ +#define _ESP_MODBUS_CALLBACKS_H_ + +#include "mb.h" +#include "mb_m.h" + +typedef eMBErrorCode (*reg_input_cb)(UCHAR*, USHORT, USHORT); +typedef eMBErrorCode (*reg_holding_cb)(UCHAR*, USHORT, USHORT, eMBRegisterMode); +typedef eMBErrorCode (*reg_coils_cb)(UCHAR*, USHORT, USHORT, eMBRegisterMode); +typedef eMBErrorCode (*reg_discrete_cb)(UCHAR*, USHORT, USHORT); + +#endif /* _ESP_MODBUS_CALLBACKS_H_ */ diff --git a/components/freemodbus/common/esp_modbus_master.c b/components/freemodbus/common/esp_modbus_master.c new file mode 100644 index 00000000..eee36082 --- /dev/null +++ b/components/freemodbus/common/esp_modbus_master.c @@ -0,0 +1,244 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "esp_err.h" // for esp_err_t +#include "mbc_master.h" // for master interface define +#include "esp_modbus_master.h" // for public interface defines +#include "esp_modbus_callbacks.h" // for callback functions + +// This file implements public API for Modbus master controller. +// These functions are wrappers for interface functions of the controller +static mb_master_interface_t* master_interface_ptr = NULL; + +void mbc_master_init_iface(void* handler) +{ + master_interface_ptr = (mb_master_interface_t*) handler; +} + +/** + * Modbus controller destroy function + */ +esp_err_t mbc_master_destroy(void) +{ + esp_err_t error = ESP_OK; + MB_MASTER_CHECK((master_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + MB_MASTER_CHECK((master_interface_ptr->destroy != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + error = master_interface_ptr->destroy(); + MB_MASTER_CHECK((error == ESP_OK), + error, + "Master destroy failure, error=(0x%x).", + error); + return error; +} + +esp_err_t mbc_master_get_cid_info(uint16_t cid, const mb_parameter_descriptor_t** param_info) +{ + esp_err_t error = ESP_OK; + MB_MASTER_CHECK((master_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + MB_MASTER_CHECK((master_interface_ptr->get_cid_info != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + error = master_interface_ptr->get_cid_info(cid, param_info); + MB_MASTER_CHECK((error == ESP_OK), + error, + "Master get cid info failure, error=(0x%x).", + error); + return error; +} + +/** + * Get parameter data for corresponding characteristic + */ +esp_err_t mbc_master_get_parameter(uint16_t cid, char* name, uint8_t* value, uint8_t* type) +{ + esp_err_t error = ESP_OK; + MB_MASTER_CHECK((master_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + MB_MASTER_CHECK((master_interface_ptr->get_parameter != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + error = master_interface_ptr->get_parameter(cid, name, value, type); + MB_MASTER_CHECK((error == ESP_OK), + error, + "Master get parameter failure, error=(0x%x) (%s).", + error, esp_err_to_name(error)); + return error; +} + +/** + * Send custom Modbus request defined as mb_param_request_t structure + */ +esp_err_t mbc_master_send_request(mb_param_request_t* request, void* data_ptr) +{ + esp_err_t error = ESP_OK; + MB_MASTER_CHECK((master_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + MB_MASTER_CHECK((master_interface_ptr->send_request != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + error = master_interface_ptr->send_request(request, data_ptr); + MB_MASTER_CHECK((error == ESP_OK), + error, + "Master send request failure error=(0x%x) (%s).", + error, esp_err_to_name(error)); + return ESP_OK; +} + +/** + * Set Modbus parameter description table + */ +esp_err_t mbc_master_set_descriptor(const mb_parameter_descriptor_t* descriptor, + const uint16_t num_elements) +{ + esp_err_t error = ESP_OK; + MB_MASTER_CHECK((master_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + MB_MASTER_CHECK((master_interface_ptr->set_descriptor != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + error = master_interface_ptr->set_descriptor(descriptor, num_elements); + MB_MASTER_CHECK((error == ESP_OK), + error, + "Master set descriptor failure, error=(0x%x) (%s).", + error, esp_err_to_name(error)); + return ESP_OK; +} + +/** + * Set parameter value for characteristic selected by name and cid + */ +esp_err_t mbc_master_set_parameter(uint16_t cid, char* name, uint8_t* value, uint8_t* type) +{ + esp_err_t error = ESP_OK; + MB_MASTER_CHECK((master_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + MB_MASTER_CHECK((master_interface_ptr->set_parameter != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + error = master_interface_ptr->set_parameter(cid, name, value, type); + MB_MASTER_CHECK((error == ESP_OK), + error, + "Master set parameter failure, error=(0x%x) (%s).", + error, esp_err_to_name(error)); + return ESP_OK; +} + +/** + * Setup Modbus controller parameters + */ +esp_err_t mbc_master_setup(void* comm_info) +{ + esp_err_t error = ESP_OK; + MB_MASTER_CHECK((master_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + MB_MASTER_CHECK((master_interface_ptr->setup != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + error = master_interface_ptr->setup(comm_info); + MB_MASTER_CHECK((error == ESP_OK), + error, + "Master setup failure, error=(0x%x) (%s).", + error, esp_err_to_name(error)); + return ESP_OK; +} + +/** + * Modbus controller stack start function + */ +esp_err_t mbc_master_start(void) +{ + esp_err_t error = ESP_OK; + MB_MASTER_CHECK((master_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + MB_MASTER_CHECK((master_interface_ptr->start != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + error = master_interface_ptr->start(); + MB_MASTER_CHECK((error == ESP_OK), + error, + "Master start failure, error=(0x%x) (%s).", + error, esp_err_to_name(error)); + return ESP_OK; +} + +eMBErrorCode eMBMasterRegDiscreteCB(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNDiscrete) +{ + eMBErrorCode error = MB_ENOERR; + MB_MASTER_CHECK((master_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + MB_MASTER_CHECK((master_interface_ptr->master_reg_cb_discrete != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + error = master_interface_ptr->master_reg_cb_discrete(pucRegBuffer, usAddress, usNDiscrete); + return error; +} + +eMBErrorCode eMBMasterRegCoilsCB(UCHAR* pucRegBuffer, USHORT usAddress, + USHORT usNCoils, eMBRegisterMode eMode) +{ + eMBErrorCode error = MB_ENOERR; + MB_MASTER_CHECK((master_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + MB_MASTER_CHECK((master_interface_ptr->master_reg_cb_coils != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + error = master_interface_ptr->master_reg_cb_coils(pucRegBuffer, usAddress, + usNCoils, eMode); + return error; +} + +eMBErrorCode eMBMasterRegHoldingCB(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs, eMBRegisterMode eMode) +{ + eMBErrorCode error = MB_ENOERR; + MB_MASTER_CHECK((master_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + MB_MASTER_CHECK((master_interface_ptr->master_reg_cb_holding != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + error = master_interface_ptr->master_reg_cb_holding(pucRegBuffer, usAddress, + usNRegs, eMode); + return error; +} + +eMBErrorCode eMBMasterRegInputCB(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs) +{ + eMBErrorCode error = MB_ENOERR; + MB_MASTER_CHECK((master_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + MB_MASTER_CHECK((master_interface_ptr->master_reg_cb_input != NULL), + ESP_ERR_INVALID_STATE, + "Master interface is not correctly initialized."); + error = master_interface_ptr->master_reg_cb_input(pucRegBuffer, usAddress, usNRegs); + return error; +} diff --git a/components/freemodbus/common/esp_modbus_master_serial.c b/components/freemodbus/common/esp_modbus_master_serial.c new file mode 100644 index 00000000..26179746 --- /dev/null +++ b/components/freemodbus/common/esp_modbus_master_serial.c @@ -0,0 +1,41 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "esp_err.h" // for esp_err_t +#include "mbc_master.h" // for master interface define +#include "esp_modbus_master.h" // for public slave defines +#include "mbc_serial_master.h" // for public interface defines + +/** + * Initialization of Modbus master serial + */ +esp_err_t mbc_master_init(mb_port_type_t port_type, void** handler) +{ + void* port_handler = NULL; + esp_err_t error = ESP_ERR_NOT_SUPPORTED; + switch(port_type) + { + case MB_PORT_SERIAL_MASTER: + error = mbc_serial_master_create(&port_handler); + break; + default: + return ESP_ERR_NOT_SUPPORTED; + } + if ((port_handler != NULL) && (error == ESP_OK)) { + mbc_master_init_iface(port_handler); + *handler = port_handler; + } + return error; +} diff --git a/components/freemodbus/common/esp_modbus_master_tcp.c b/components/freemodbus/common/esp_modbus_master_tcp.c new file mode 100644 index 00000000..4bedfe84 --- /dev/null +++ b/components/freemodbus/common/esp_modbus_master_tcp.c @@ -0,0 +1,33 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "esp_err.h" // for esp_err_t +#include "esp_modbus_master.h" // for public interface defines +#include "mbc_tcp_master.h" // for public interface defines + +/** + * Initialization of Modbus TCP Master controller interface + */ +esp_err_t mbc_master_init_tcp(void** handler) +{ + void* port_handler = NULL; + esp_err_t error = mbc_tcp_master_create(&port_handler); + + if ((port_handler != NULL) && (error == ESP_OK)) { + mbc_master_init_iface(port_handler); + *handler = port_handler; + } + return error; +} diff --git a/components/freemodbus/common/esp_modbus_slave.c b/components/freemodbus/common/esp_modbus_slave.c new file mode 100644 index 00000000..57a54efe --- /dev/null +++ b/components/freemodbus/common/esp_modbus_slave.c @@ -0,0 +1,231 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "esp_err.h" // for esp_err_t +#include "sdkconfig.h" // for KConfig defines +#include "mbc_slave.h" // for slave private type definitions +#include "esp_modbus_common.h" // for common defines +#include "esp_modbus_slave.h" // for public slave defines +#include "esp_modbus_callbacks.h" // for modbus callbacks function pointers declaration + +#ifdef CONFIG_FMB_CONTROLLER_SLAVE_ID_SUPPORT + +#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_CONTROLLER_SLAVE_ID (CONFIG_FMB_CONTROLLER_SLAVE_ID) +#define MB_SLAVE_ID_SHORT (MB_ID_BYTE3(MB_CONTROLLER_SLAVE_ID)) + +// Slave ID constant +static uint8_t mb_slave_id[] = { MB_ID_BYTE0(MB_CONTROLLER_SLAVE_ID), + MB_ID_BYTE1(MB_CONTROLLER_SLAVE_ID), + MB_ID_BYTE2(MB_CONTROLLER_SLAVE_ID) }; + +#endif + +// Common interface pointer for slave port +static mb_slave_interface_t* slave_interface_ptr = NULL; + +void mbc_slave_init_iface(void* handler) +{ + slave_interface_ptr = (mb_slave_interface_t*) handler; +} + +/** + * Modbus controller destroy function + */ +esp_err_t mbc_slave_destroy(void) +{ + esp_err_t error = ESP_OK; + // Is initialization done? + MB_SLAVE_CHECK((slave_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + // Check if interface has been initialized + MB_SLAVE_CHECK((slave_interface_ptr->destroy != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + // Call the slave port destroy function + error = slave_interface_ptr->destroy(); + MB_SLAVE_CHECK((error == ESP_OK), + ESP_ERR_INVALID_STATE, + "Slave destroy failure error=(0x%x).", + error); + return error; +} + +/** + * Setup Modbus controller parameters + */ +esp_err_t mbc_slave_setup(void* comm_info) +{ + esp_err_t error = ESP_OK; + MB_SLAVE_CHECK((slave_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + MB_SLAVE_CHECK((slave_interface_ptr->setup != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + error = slave_interface_ptr->setup(comm_info); + MB_SLAVE_CHECK((error == ESP_OK), + ESP_ERR_INVALID_STATE, + "Slave setup failure error=(0x%x).", + error); + return error; +} + +/** + * Start Modbus controller start function + */ +esp_err_t mbc_slave_start(void) +{ + esp_err_t error = ESP_OK; + MB_SLAVE_CHECK((slave_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + MB_SLAVE_CHECK((slave_interface_ptr->start != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); +#ifdef CONFIG_FMB_CONTROLLER_SLAVE_ID_SUPPORT + // Set the slave ID if the KConfig option is selected + eMBErrorCode status = eMBSetSlaveID(MB_SLAVE_ID_SHORT, TRUE, (UCHAR*)mb_slave_id, sizeof(mb_slave_id)); + MB_SLAVE_CHECK((status == MB_ENOERR), ESP_ERR_INVALID_STATE, "mb stack set slave ID failure."); +#endif + error = slave_interface_ptr->start(); + MB_SLAVE_CHECK((error == ESP_OK), + ESP_ERR_INVALID_STATE, + "Slave start failure error=(0x%x).", + error); + return error; +} + +/** + * Blocking function to get event on parameter group change for application task + */ +mb_event_group_t mbc_slave_check_event(mb_event_group_t group) +{ + MB_SLAVE_CHECK((slave_interface_ptr != NULL), + MB_EVENT_NO_EVENTS, + "Slave interface is not correctly initialized."); + MB_SLAVE_CHECK((slave_interface_ptr->check_event != NULL), + MB_EVENT_NO_EVENTS, + "Slave interface is not correctly initialized."); + mb_event_group_t event = slave_interface_ptr->check_event(group); + return event; +} + +/** + * Function to get notification about parameter change from application task + */ +esp_err_t mbc_slave_get_param_info(mb_param_info_t* reg_info, uint32_t timeout) +{ + esp_err_t error = ESP_OK; + MB_SLAVE_CHECK((slave_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + MB_SLAVE_CHECK((slave_interface_ptr->get_param_info != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + error = slave_interface_ptr->get_param_info(reg_info, timeout); + MB_SLAVE_CHECK((error == ESP_OK), + ESP_ERR_INVALID_STATE, + "Slave get parameter info failure error=(0x%x).", + error); + return error; +} + +/** + * Function to set area descriptors for modbus parameters + */ +esp_err_t mbc_slave_set_descriptor(mb_register_area_descriptor_t descr_data) +{ + esp_err_t error = ESP_OK; + MB_SLAVE_CHECK((slave_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + MB_SLAVE_CHECK((slave_interface_ptr->set_descriptor != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + error = slave_interface_ptr->set_descriptor(descr_data); + MB_SLAVE_CHECK((error == ESP_OK), + ESP_ERR_INVALID_STATE, + "Slave set descriptor failure error=(0x%x).", + (uint16_t)error); + return error; +} + +/** + * Below are stack callback functions to read/write registers + */ +eMBErrorCode eMBRegDiscreteCB(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNDiscrete) +{ + eMBErrorCode error = MB_ENOERR; + MB_SLAVE_CHECK((slave_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + MB_SLAVE_CHECK((slave_interface_ptr->slave_reg_cb_discrete != NULL), + error, + "Slave interface is not correctly initialized."); + error = slave_interface_ptr->slave_reg_cb_discrete(pucRegBuffer, usAddress, usNDiscrete); + + return error; +} + +eMBErrorCode eMBRegCoilsCB(UCHAR* pucRegBuffer, USHORT usAddress, + USHORT usNCoils, eMBRegisterMode eMode) +{ + eMBErrorCode error = MB_ENOERR; + MB_SLAVE_CHECK((slave_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + MB_SLAVE_CHECK((slave_interface_ptr->slave_reg_cb_coils != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + error = slave_interface_ptr->slave_reg_cb_coils(pucRegBuffer, usAddress, + usNCoils, eMode); + return error; +} + +eMBErrorCode eMBRegHoldingCB(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs, eMBRegisterMode eMode) +{ + eMBErrorCode error = MB_ENOERR; + MB_SLAVE_CHECK((slave_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + MB_SLAVE_CHECK((slave_interface_ptr->slave_reg_cb_holding != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + error = slave_interface_ptr->slave_reg_cb_holding(pucRegBuffer, usAddress, + usNRegs, eMode); + return error; +} + +eMBErrorCode eMBRegInputCB(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs) +{ + eMBErrorCode error = MB_ENOERR; + MB_SLAVE_CHECK((slave_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + MB_SLAVE_CHECK((slave_interface_ptr->slave_reg_cb_input != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + error = slave_interface_ptr->slave_reg_cb_input(pucRegBuffer, usAddress, usNRegs); + return error; +} diff --git a/components/freemodbus/common/esp_modbus_slave_serial.c b/components/freemodbus/common/esp_modbus_slave_serial.c new file mode 100644 index 00000000..662b03e9 --- /dev/null +++ b/components/freemodbus/common/esp_modbus_slave_serial.c @@ -0,0 +1,44 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "esp_err.h" // for esp_err_t +#include "sdkconfig.h" // for KConfig defines +#include "mbc_slave.h" // for slave interface define +#include "esp_modbus_slave.h" // for public slave defines +#include "mbc_serial_slave.h" // for public interface defines + +/** + * Initialization of Modbus Serial slave controller + */ +esp_err_t mbc_slave_init(mb_port_type_t port_type, void** handler) +{ + void* port_handler = NULL; + esp_err_t error = ESP_ERR_NOT_SUPPORTED; + switch(port_type) + { + case MB_PORT_SERIAL_SLAVE: + // Call constructor function of actual port implementation + error = mbc_serial_slave_create(&port_handler); + break; + default: + return ESP_ERR_NOT_SUPPORTED; + } + if ((port_handler != NULL) && (error == ESP_OK)) { + mbc_slave_init_iface(port_handler); + *handler = port_handler; + } + return error; +} + diff --git a/components/freemodbus/common/esp_modbus_slave_tcp.c b/components/freemodbus/common/esp_modbus_slave_tcp.c new file mode 100644 index 00000000..23846904 --- /dev/null +++ b/components/freemodbus/common/esp_modbus_slave_tcp.c @@ -0,0 +1,33 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "esp_err.h" // for esp_err_t +#include "esp_modbus_slave.h" // for public slave defines +#include "mbc_tcp_slave.h" // for public interface defines + +/** + * Initialization of Modbus TCP Slave controller + */ +esp_err_t mbc_slave_init_tcp(void** handler) +{ + void* port_handler = NULL; + esp_err_t error = mbc_tcp_slave_create(&port_handler); + + if ((port_handler != NULL) && (error == ESP_OK)) { + mbc_slave_init_iface(port_handler); + *handler = port_handler; + } + return error; +} diff --git a/components/freemodbus/common/include/esp_modbus_common.h b/components/freemodbus/common/include/esp_modbus_common.h new file mode 100644 index 00000000..b6836ba7 --- /dev/null +++ b/components/freemodbus/common/include/esp_modbus_common.h @@ -0,0 +1,156 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _MB_IFACE_COMMON_H +#define _MB_IFACE_COMMON_H + +#include "driver/uart.h" // for UART types + +#ifdef __cplusplus +extern "C" { +#endif + +#define MB_CONTROLLER_STACK_SIZE (CONFIG_FMB_CONTROLLER_STACK_SIZE) // Stack size for Modbus controller +#define MB_CONTROLLER_PRIORITY (CONFIG_FMB_PORT_TASK_PRIO - 1) // priority of MB controller task + +// Default port defines +#define MB_DEVICE_ADDRESS (1) // Default slave device address in Modbus +#define MB_DEVICE_SPEED (115200) // Default Modbus speed for now hard defined +#define MB_UART_PORT (UART_NUM_MAX - 1) // Default UART port number +#define MB_PAR_INFO_TOUT (10) // Timeout for get parameter info +#define MB_PARITY_NONE (UART_PARITY_DISABLE) + +// The Macros below handle the endianness while transfer N byte data into buffer +#define _XFER_4_RD(dst, src) { \ + *(uint8_t *)(dst)++ = *(uint8_t*)(src + 1); \ + *(uint8_t *)(dst)++ = *(uint8_t*)(src + 0); \ + *(uint8_t *)(dst)++ = *(uint8_t*)(src + 3); \ + *(uint8_t *)(dst)++ = *(uint8_t*)(src + 2); \ + (src) += 4; \ +} + +#define _XFER_2_RD(dst, src) { \ + *(uint8_t *)(dst)++ = *(uint8_t *)(src + 1); \ + *(uint8_t *)(dst)++ = *(uint8_t *)(src + 0); \ + (src) += 2; \ +} + +#define _XFER_4_WR(dst, src) { \ + *(uint8_t *)(dst + 1) = *(uint8_t *)(src)++; \ + *(uint8_t *)(dst + 0) = *(uint8_t *)(src)++; \ + *(uint8_t *)(dst + 3) = *(uint8_t *)(src)++; \ + *(uint8_t *)(dst + 2) = *(uint8_t *)(src)++ ; \ +} + +#define _XFER_2_WR(dst, src) { \ + *(uint8_t *)(dst + 1) = *(uint8_t *)(src)++; \ + *(uint8_t *)(dst + 0) = *(uint8_t *)(src)++; \ +} + +/** + * @brief Types of actual Modbus implementation + */ +typedef enum +{ + MB_PORT_SERIAL_MASTER = 0x00, /*!< Modbus port type serial master. */ + MB_PORT_SERIAL_SLAVE, /*!< Modbus port type serial slave. */ + MB_PORT_TCP_MASTER, /*!< Modbus port type TCP master. */ + MB_PORT_TCP_SLAVE, /*!< Modbus port type TCP slave. */ + MB_PORT_COUNT, /*!< Modbus port count. */ + MB_PORT_INACTIVE = 0xFF +} mb_port_type_t; + +/** + * @brief Event group for parameters notification + */ +typedef enum +{ + MB_EVENT_NO_EVENTS = 0x00, + MB_EVENT_HOLDING_REG_WR = BIT0, /*!< Modbus Event Write Holding registers. */ + MB_EVENT_HOLDING_REG_RD = BIT1, /*!< Modbus Event Read Holding registers. */ + MB_EVENT_INPUT_REG_RD = BIT3, /*!< Modbus Event Read Input registers. */ + MB_EVENT_COILS_WR = BIT4, /*!< Modbus Event Write Coils. */ + MB_EVENT_COILS_RD = BIT5, /*!< Modbus Event Read Coils. */ + MB_EVENT_DISCRETE_RD = BIT6, /*!< Modbus Event Read Discrete bits. */ + MB_EVENT_STACK_STARTED = BIT7 /*!< Modbus Event Stack started */ +} mb_event_group_t; + +/** + * @brief Type of Modbus parameter + */ +typedef enum { + MB_PARAM_HOLDING = 0x00, /*!< Modbus Holding register. */ + MB_PARAM_INPUT, /*!< Modbus Input register. */ + MB_PARAM_COIL, /*!< Modbus Coils. */ + MB_PARAM_DISCRETE, /*!< Modbus Discrete bits. */ + MB_PARAM_COUNT, + MB_PARAM_UNKNOWN = 0xFF +} mb_param_type_t; + +/*! + * \brief Modbus serial transmission modes (RTU/ASCII). + */ +typedef enum { + MB_MODE_RTU, /*!< RTU transmission mode. */ + MB_MODE_ASCII, /*!< ASCII transmission mode. */ + MB_MODE_TCP, /*!< TCP communication mode. */ + MB_MODE_UDP /*!< UDP communication mode. */ +} mb_mode_type_t; + +/*! + * \brief Modbus TCP type of address. + */ +typedef enum { + MB_IPV4 = 0, /*!< TCP IPV4 addressing */ + MB_IPV6 = 1 /*!< TCP IPV6 addressing */ +} mb_tcp_addr_type_t; + +/** + * @brief Device communication structure to setup Modbus controller + */ +typedef union { + // Serial communication structure + struct { + mb_mode_type_t mode; /*!< Modbus communication mode */ + uint8_t slave_addr; /*!< Modbus slave address field (dummy for master) */ + uart_port_t port; /*!< Modbus communication port (UART) number */ + uint32_t baudrate; /*!< Modbus baudrate */ + uart_parity_t parity; /*!< Modbus UART parity settings */ + uint16_t dummy_port; /*!< Dummy field, unused */ + }; + // TCP/UDP communication structure + struct { + mb_mode_type_t ip_mode; /*!< Modbus communication mode */ + uint16_t ip_port; /*!< Modbus port */ + mb_tcp_addr_type_t ip_addr_type; /*!< Modbus address type */ + void* ip_addr; /*!< Modbus address table for connection */ + void* ip_netif_ptr; /*!< Modbus network interface */ + }; +} mb_communication_info_t; + +/** + * common interface method types + */ +typedef esp_err_t (*iface_init)(void**); /*!< Interface method init */ +typedef esp_err_t (*iface_destroy)(void); /*!< Interface method destroy */ +typedef esp_err_t (*iface_setup)(void*); /*!< Interface method setup */ +typedef esp_err_t (*iface_start)(void); /*!< Interface method start */ + +#ifdef __cplusplus +} +#endif + +#endif // _MB_IFACE_COMMON_H + diff --git a/components/freemodbus/common/include/esp_modbus_master.h b/components/freemodbus/common/include/esp_modbus_master.h new file mode 100644 index 00000000..bb7dc7a0 --- /dev/null +++ b/components/freemodbus/common/include/esp_modbus_master.h @@ -0,0 +1,270 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _ESP_MB_MASTER_INTERFACE_H +#define _ESP_MB_MASTER_INTERFACE_H + +#include // for standard int types definition +#include // for NULL and std defines +#include "soc/soc.h" // for BITN definitions +#include "esp_modbus_common.h" // for common types + +#ifdef __cplusplus +extern "C" { +#endif + +/*! + * \brief Modbus descriptor table parameter type defines. + */ +typedef enum { + PARAM_TYPE_U8 = 0x00, /*!< Unsigned 8 */ + PARAM_TYPE_U16 = 0x01, /*!< Unsigned 16 */ + PARAM_TYPE_U32 = 0x02, /*!< Unsigned 32 */ + PARAM_TYPE_FLOAT = 0x03, /*!< Float type */ + PARAM_TYPE_ASCII = 0x04 /*!< ASCII type */ +} mb_descr_type_t; + +/*! + * \brief Modbus descriptor table parameter size in bytes. + */ +typedef enum { + PARAM_SIZE_U8 = 0x01, /*!< Unsigned 8 */ + PARAM_SIZE_U16 = 0x02, /*!< Unsigned 16 */ + PARAM_SIZE_U32 = 0x04, /*!< Unsigned 32 */ + PARAM_SIZE_FLOAT = 0x04, /*!< Float size */ + PARAM_SIZE_ASCII = 0x08, /*!< ASCII size */ + PARAM_SIZE_ASCII24 = 0x18, /*!< ASCII24 size */ + PARAM_MAX_SIZE +} mb_descr_size_t; + +/*! + * \brief Modbus parameter options for description table + */ +typedef union { + struct { + int opt1; /*!< Parameter option1 */ + int opt2; /*!< Parameter option2 */ + int opt3; /*!< Parameter option3 */ + }; + struct { + int min; /*!< Parameter minimum value */ + int max; /*!< Parameter maximum value */ + int step; /*!< Step of parameter change tracking */ + }; +} mb_parameter_opt_t; + +/** + * @brief Permissions for the characteristics + */ +typedef enum { + PAR_PERMS_READ = 1 << BIT0, /**< the characteristic of the device are readable */ + PAR_PERMS_WRITE = 1 << BIT1, /**< the characteristic of the device are writable*/ + PAR_PERMS_TRIGGER = 1 << BIT2, /**< the characteristic of the device are triggerable */ + PAR_PERMS_READ_WRITE = PAR_PERMS_READ | PAR_PERMS_WRITE, /**< the characteristic of the device are readable & writable */ + PAR_PERMS_READ_TRIGGER = PAR_PERMS_READ | PAR_PERMS_TRIGGER, /**< the characteristic of the device are readable & triggerable */ + PAR_PERMS_WRITE_TRIGGER = PAR_PERMS_WRITE | PAR_PERMS_TRIGGER, /**< the characteristic of the device are writable & triggerable */ + PAR_PERMS_READ_WRITE_TRIGGER = PAR_PERMS_READ_WRITE | PAR_PERMS_TRIGGER, /**< the characteristic of the device are readable & writable & triggerable */ +} mb_param_perms_t; + +/** + * @brief Characteristics descriptor type is used to describe characteristic and + * link it with Modbus parameters that reflect its data. + */ +typedef struct { + uint16_t cid; /*!< Characteristic cid */ + const char* param_key; /*!< The key (name) of the parameter */ + const char* param_units; /*!< The physical units of the parameter */ + uint8_t mb_slave_addr; /*!< Slave address of device in the Modbus segment */ + mb_param_type_t mb_param_type; /*!< Type of modbus parameter */ + uint16_t mb_reg_start; /*!< This is the Modbus register address. This is the 0 based value. */ + uint16_t mb_size; /*!< Size of mb parameter in registers */ + uint16_t param_offset; /*!< Parameter name (OFFSET in the parameter structure) */ + mb_descr_type_t param_type; /*!< Float, U8, U16, U32, ASCII, etc. */ + mb_descr_size_t param_size; /*!< Number of bytes in the parameter. */ + mb_parameter_opt_t param_opts; /*!< Parameter options used to check limits and etc. */ + mb_param_perms_t access; /*!< Access permissions based on mode */ +} mb_parameter_descriptor_t; + +/** + * @brief Modbus register request type structure + */ +typedef struct { + uint8_t slave_addr; /*!< Modbus slave address */ + uint8_t command; /*!< Modbus command to send */ + uint16_t reg_start; /*!< Modbus start register */ + uint16_t reg_size; /*!< Modbus number of registers */ +} mb_param_request_t; + +/** + * @brief Initialize Modbus controller and stack for TCP port + * + * @param[out] handler handler(pointer) to master data structure + * @return + * - ESP_OK Success + * - ESP_ERR_NO_MEM Parameter error + * - ESP_ERR_NOT_SUPPORTED Port type not supported + * - ESP_ERR_INVALID_STATE Initialization failure + */ +esp_err_t mbc_master_init_tcp(void** handler); + +/** + * @brief Initialize Modbus Master controller and stack for Serial port + * + * @param[out] handler handler(pointer) to master data structure + * @param[in] port_type type of stack + * @return + * - ESP_OK Success + * - ESP_ERR_NO_MEM Parameter error + * - ESP_ERR_NOT_SUPPORTED Port type not supported + * - ESP_ERR_INVALID_STATE Initialization failure + */ +esp_err_t mbc_master_init(mb_port_type_t port_type, void** handler); + +/** + * @brief Initialize Modbus Master controller interface handle + * + * @param[in] handler - pointer to master data structure + * @return None + */ +void mbc_master_init_iface(void* handler); + +/** + * @brief Destroy Modbus controller and stack + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE Parameter error + */ +esp_err_t mbc_master_destroy(void); + +/** + * @brief Start Modbus communication stack + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Modbus stack start error + */ +esp_err_t mbc_master_start(void); + +/** + * @brief Set Modbus communication parameters for the controller + * + * @param comm_info Communication parameters structure. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Incorrect parameter data + */ +esp_err_t mbc_master_setup(void* comm_info); + +/***************************** Specific interface functions ******************************************** + * Interface functions below provide basic methods to read/write access to slave devices in Modbus + * segment as well as API to read specific supported characteristics linked to Modbus parameters + * of devices in Modbus network. +*******************************************************************************************************/ + +/** + * @brief Assign parameter description table for Modbus controller interface. + * + * @param[in] descriptor pointer to parameter description table + * @param num_elements number of elements in the table + * + * @return + * - esp_err_t ESP_OK - set descriptor successfully + * - esp_err_t ESP_ERR_INVALID_ARG - invalid argument in function call + */ +esp_err_t mbc_master_set_descriptor(const mb_parameter_descriptor_t* descriptor, const uint16_t num_elements); + +/** + * @brief Send data request as defined in parameter request, waits response + * from slave and returns status of command execution. This function provides standard way + * for read/write access to Modbus devices in the network. + * + * @param[in] request pointer to request structure of type mb_param_request_t + * @param[in] data_ptr pointer to data buffer to send or received data (dependent of command field in request) + * + * @return + * - esp_err_t ESP_OK - request was successful + * - esp_err_t ESP_ERR_INVALID_ARG - invalid argument of function + * - esp_err_t ESP_ERR_INVALID_RESPONSE - an invalid response from slave + * - esp_err_t ESP_ERR_TIMEOUT - operation timeout or no response from slave + * - esp_err_t ESP_ERR_NOT_SUPPORTED - the request command is not supported by slave + * - esp_err_t ESP_FAIL - slave returned an exception or other failure + */ +esp_err_t mbc_master_send_request(mb_param_request_t* request, void* data_ptr); + +/** + * @brief Get information about supported characteristic defined as cid. Uses parameter description table to get + * this information. The function will check if characteristic defined as a cid parameter is supported + * and returns its description in param_info. Returns ESP_ERR_NOT_FOUND if characteristic is not supported. + * + * @param[in] cid characteristic id + * @param param_info pointer to pointer of characteristic data. + * + * @return + * - esp_err_t ESP_OK - request was successful and buffer contains the supported characteristic name + * - esp_err_t ESP_ERR_INVALID_ARG - invalid argument of function + * - esp_err_t ESP_ERR_NOT_FOUND - the characteristic (cid) not found + * - esp_err_t ESP_FAIL - unknown error during lookup table processing +*/ +esp_err_t mbc_master_get_cid_info(uint16_t cid, const mb_parameter_descriptor_t** param_info); + +/** + * @brief Read parameter from modbus slave device whose name is defined by name and has cid. + * The additional data for request is taken from parameter description (lookup) table. + * + * @param[in] cid id of the characteristic for parameter + * @param[in] name pointer into string name (key) of parameter (null terminated) + * @param[out] value pointer to data buffer of parameter + * @param[out] type parameter type associated with the name returned from parameter description table. + * + * @return + * - esp_err_t ESP_OK - request was successful and value buffer contains + * representation of actual parameter data from slave + * - esp_err_t ESP_ERR_INVALID_ARG - invalid argument of function + * - esp_err_t ESP_ERR_INVALID_RESPONSE - an invalid response from slave + * - esp_err_t ESP_ERR_INVALID_STATE - invalid state during data processing or allocation failure + * - esp_err_t ESP_ERR_TIMEOUT - operation timed out and no response from slave + * - esp_err_t ESP_ERR_NOT_SUPPORTED - the request command is not supported by slave + * - esp_err_t ESP_ERR_NOT_FOUND - the parameter is not found in the parameter description table + * - esp_err_t ESP_FAIL - slave returned an exception or other failure +*/ +esp_err_t mbc_master_get_parameter(uint16_t cid, char* name, uint8_t* value, uint8_t *type); + +/** + * @brief Set characteristic's value defined as a name and cid parameter. + * The additional data for cid parameter request is taken from master parameter lookup table. + * + * @param[in] cid id of the characteristic for parameter + * @param[in] name pointer into string name (key) of parameter (null terminated) + * @param[out] value pointer to data buffer of parameter (actual representation of json value field in binary form) + * @param[out] type pointer to parameter type associated with the name returned from parameter lookup table. + * + * @return + * - esp_err_t ESP_OK - request was successful and value was saved in the slave device registers + * - esp_err_t ESP_ERR_INVALID_ARG - invalid argument of function + * - esp_err_t ESP_ERR_INVALID_RESPONSE - an invalid response from slave during processing of parameter + * - esp_err_t ESP_ERR_INVALID_STATE - invalid state during data processing or allocation failure + * - esp_err_t ESP_ERR_TIMEOUT - operation timed out and no response from slave + * - esp_err_t ESP_ERR_NOT_SUPPORTED - the request command is not supported by slave + * - esp_err_t ESP_FAIL - slave returned an exception or other failure +*/ +esp_err_t mbc_master_set_parameter(uint16_t cid, char* name, uint8_t* value, uint8_t *type); + +#ifdef __cplusplus +} +#endif + +#endif // _ESP_MB_MASTER_INTERFACE_H diff --git a/components/freemodbus/common/include/esp_modbus_slave.h b/components/freemodbus/common/include/esp_modbus_slave.h new file mode 100644 index 00000000..ed6a12ed --- /dev/null +++ b/components/freemodbus/common/include/esp_modbus_slave.h @@ -0,0 +1,152 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _ESP_MB_SLAVE_INTERFACE_H +#define _ESP_MB_SLAVE_INTERFACE_H + +// Public interface header for slave +#include // for standard int types definition +#include // for NULL and std defines +#include "soc/soc.h" // for BITN definitions +#include "freertos/FreeRTOS.h" // for task creation and queues access +#include "freertos/event_groups.h" // for event groups +#include "esp_modbus_common.h" // for common types + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Parameter access event information type + */ +typedef struct { + uint32_t time_stamp; /*!< Timestamp of Modbus Event (uS)*/ + uint16_t mb_offset; /*!< Modbus register offset */ + mb_event_group_t type; /*!< Modbus event type */ + uint8_t* address; /*!< Modbus data storage address */ + size_t size; /*!< Modbus event register size (number of registers)*/ +} mb_param_info_t; + +/** + * @brief Parameter storage area descriptor + */ +typedef struct { + uint16_t start_offset; /*!< Modbus start address for area descriptor */ + mb_param_type_t type; /*!< Type of storage area descriptor */ + void* address; /*!< Instance address for storage area descriptor */ + size_t size; /*!< Instance size for area descriptor (bytes) */ +} mb_register_area_descriptor_t; + +/** + * @brief Initialize Modbus Slave controller and stack for TCP port + * + * @param[out] handler handler(pointer) to master data structure + * @return + * - ESP_OK Success + * - ESP_ERR_NO_MEM Parameter error + * - ESP_ERR_NOT_SUPPORTED Port type not supported + * - ESP_ERR_INVALID_STATE Initialization failure + */ +esp_err_t mbc_slave_init_tcp(void** handler); + +/** + * @brief Initialize Modbus Slave controller and stack for Serial port + * + * @param[out] handler handler(pointer) to master data structure + * @param[in] port_type the type of port + * @return + * - ESP_OK Success + * - ESP_ERR_NO_MEM Parameter error + * - ESP_ERR_NOT_SUPPORTED Port type not supported + * - ESP_ERR_INVALID_STATE Initialization failure + */ +esp_err_t mbc_slave_init(mb_port_type_t port_type, void** handler); + +/** + * @brief Initialize Modbus Slave controller interface handle + * + * @param[in] handler - pointer to slave interface data structure + * @return None + */ +void mbc_slave_init_iface(void* handler); + +/** + * @brief Destroy Modbus controller and stack + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_STATE Parameter error + */ +esp_err_t mbc_slave_destroy(void); + +/** + * @brief Start Modbus communication stack + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Modbus stack start error + */ +esp_err_t mbc_slave_start(void); + +/** + * @brief Set Modbus communication parameters for the controller + * + * @param comm_info Communication parameters structure. + * + * @return + * - ESP_OK Success + * - ESP_ERR_INVALID_ARG Incorrect parameter data + */ +esp_err_t mbc_slave_setup(void* comm_info); + +/** + * @brief Wait for specific event on parameter change. + * + * @param group Group event bit mask to wait for change + * + * @return + * - mb_event_group_t event bits triggered + */ +mb_event_group_t mbc_slave_check_event(mb_event_group_t group); + +/** + * @brief Get parameter information + * + * @param[out] reg_info parameter info structure + * @param timeout Timeout in milliseconds to read information from + * parameter queue + * @return + * - ESP_OK Success + * - ESP_ERR_TIMEOUT Can not get data from parameter queue + * or queue overflow + */ +esp_err_t mbc_slave_get_param_info(mb_param_info_t* reg_info, uint32_t timeout); + +/** + * @brief Set Modbus area descriptor + * + * @param descr_data Modbus registers area descriptor structure + * + * @return + * - ESP_OK: The appropriate descriptor is set + * - ESP_ERR_INVALID_ARG: The argument is incorrect + */ +esp_err_t mbc_slave_set_descriptor(mb_register_area_descriptor_t descr_data); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/components/freemodbus/common/include/mbcontroller.h b/components/freemodbus/common/include/mbcontroller.h new file mode 100644 index 00000000..08b3c183 --- /dev/null +++ b/components/freemodbus/common/include/mbcontroller.h @@ -0,0 +1,32 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ +// mbcontroller.h +// mbcontroller - common Modbus controller header file + +#ifndef _MODBUS_CONTROLLER_COMMON +#define _MODBUS_CONTROLLER_COMMON + +#include // for standard int types definition +#include // for NULL and std defines +#include "string.h" // for strerror() +#include "errno.h" // for errno +#include "esp_err.h" // for error handling +#include "driver/uart.h" // for uart port number defines +#include "sdkconfig.h" // for KConfig options + +#include "esp_modbus_master.h" +#include "esp_modbus_slave.h" + +#endif diff --git a/components/freemodbus/common/mbc_master.h b/components/freemodbus/common/mbc_master.h new file mode 100644 index 00000000..67e5f556 --- /dev/null +++ b/components/freemodbus/common/mbc_master.h @@ -0,0 +1,106 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef _MB_CONTROLLER_MASTER_H +#define _MB_CONTROLLER_MASTER_H + +#include "freertos/FreeRTOS.h" // for task creation and queue access +#include "freertos/task.h" // for task api access +#include "freertos/event_groups.h" // for event groups +#include "driver/uart.h" // for UART types +#include "errno.h" // for errno +#include "esp_log.h" // for log write +#include "string.h" // for strerror() +#include "esp_modbus_common.h" // for common types +#include "esp_modbus_master.h" // for public master types +#include "esp_modbus_callbacks.h" + +/* ----------------------- Defines ------------------------------------------*/ + +#define MB_MASTER_TAG "MB_CONTROLLER_MASTER" + +#define MB_MASTER_CHECK(a, ret_val, str, ...) \ + if (!(a)) { \ + ESP_LOGE(MB_MASTER_TAG, "%s(%u): " str, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ + return (ret_val); \ + } + +#define MB_MASTER_ASSERT(con) do { \ + if (!(con)) { ESP_LOGE(MB_MASTER_TAG, "assert errno:%d, errno_str: !(%s)", errno, strerror(errno)); assert(0 && #con); } \ + } while (0) + +/** + * @brief Request mode for parameter to use in data dictionary + */ +typedef enum { + MB_PARAM_READ, /*!< Read parameter values. */ + MB_PARAM_WRITE /*!< Write parameter values. */ +} mb_param_mode_t; + +/** + * @brief Device communication parameters for master + */ +typedef struct { + mb_mode_type_t mode; /*!< Modbus communication mode */ + uint8_t dummy; /*!< Dummy field */ + uart_port_t port; /*!< Modbus communication port (UART) number */ + uint32_t baudrate; /*!< Modbus baudrate */ + uart_parity_t parity; /*!< Modbus UART parity settings */ +} mb_master_comm_info_t; + +/** + * @brief Modbus controller handler structure + */ +typedef struct { + mb_port_type_t port_type; /*!< Modbus port type */ + mb_communication_info_t mbm_comm; /*!< Modbus communication info */ + uint8_t* mbm_reg_buffer_ptr; /*!< Modbus data buffer pointer */ + uint16_t mbm_reg_buffer_size; /*!< Modbus data buffer size */ + TaskHandle_t mbm_task_handle; /*!< Modbus task handle */ + EventGroupHandle_t mbm_event_group; /*!< Modbus controller event group */ + const mb_parameter_descriptor_t* mbm_param_descriptor_table; /*!< Modbus controller parameter description table */ + size_t mbm_param_descriptor_size; /*!< Modbus controller parameter description table size*/ +} mb_master_options_t; + +typedef esp_err_t (*iface_get_cid_info)(uint16_t, const mb_parameter_descriptor_t**); /*!< Interface get_cid_info method */ +typedef esp_err_t (*iface_get_parameter)(uint16_t, char*, uint8_t*, uint8_t*); /*!< Interface get_parameter method */ +typedef esp_err_t (*iface_send_request)(mb_param_request_t*, void*); /*!< Interface send_request method */ +typedef esp_err_t (*iface_set_descriptor)(const mb_parameter_descriptor_t*, const uint16_t); /*!< Interface set_descriptor method */ +typedef esp_err_t (*iface_set_parameter)(uint16_t, char*, uint8_t*, uint8_t*); /*!< Interface set_parameter method */ + +/** + * @brief Modbus controller interface structure + */ +typedef struct { + // Master object interface options + mb_master_options_t opts; + + // Public interface methods + iface_init init; /*!< Interface method init */ + iface_destroy destroy; /*!< Interface method destroy */ + iface_setup setup; /*!< Interface method setup */ + iface_start start; /*!< Interface method start */ + iface_get_cid_info get_cid_info; /*!< Interface get_cid_info method */ + iface_get_parameter get_parameter; /*!< Interface get_parameter method */ + iface_send_request send_request; /*!< Interface send_request method */ + iface_set_descriptor set_descriptor; /*!< Interface set_descriptor method */ + iface_set_parameter set_parameter; /*!< Interface set_parameter method */ + // Modbus register calback function pointers + reg_discrete_cb master_reg_cb_discrete; /*!< Stack callback discrete rw method */ + reg_input_cb master_reg_cb_input; /*!< Stack callback input rw method */ + reg_holding_cb master_reg_cb_holding; /*!< Stack callback holding rw method */ + reg_coils_cb master_reg_cb_coils; /*!< Stack callback coils rw method */ +} mb_master_interface_t; + +#endif //_MB_CONTROLLER_MASTER_H diff --git a/components/freemodbus/common/mbc_slave.h b/components/freemodbus/common/mbc_slave.h new file mode 100644 index 00000000..1565da1a --- /dev/null +++ b/components/freemodbus/common/mbc_slave.h @@ -0,0 +1,94 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef _MB_CONTROLLER_SLAVE_H +#define _MB_CONTROLLER_SLAVE_H + +#include "driver/uart.h" // for uart defines +#include "errno.h" // for errno +#include "esp_log.h" // for log write +#include "string.h" // for strerror() +#include "esp_modbus_slave.h" // for public type defines +#include "esp_modbus_callbacks.h" // for callback functions + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_INST_MIN_SIZE (2) // The minimal size of Modbus registers area in bytes +#define MB_INST_MAX_SIZE (65535 * 2) // The maximum size of Modbus area in bytes + +#define MB_CONTROLLER_NOTIFY_QUEUE_SIZE (CONFIG_FMB_CONTROLLER_NOTIFY_QUEUE_SIZE) // Number of messages in parameter notification queue +#define MB_CONTROLLER_NOTIFY_TIMEOUT (pdMS_TO_TICKS(CONFIG_FMB_CONTROLLER_NOTIFY_TIMEOUT)) // notification timeout + +#define MB_SLAVE_TAG "MB_CONTROLLER_SLAVE" + +#define MB_SLAVE_CHECK(a, ret_val, str, ...) \ + if (!(a)) { \ + ESP_LOGE(MB_SLAVE_TAG, "%s(%u): " str, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ + return (ret_val); \ + } + +#define MB_SLAVE_ASSERT(con) do { \ + if (!(con)) { ESP_LOGE(MB_SLAVE_TAG, "assert errno:%d, errno_str: !(%s)", errno, strerror(errno)); assert(0 && #con); } \ + } while (0) + +/** + * @brief Device communication parameters for master + */ +typedef struct { + mb_mode_type_t mode; /*!< Modbus communication mode */ + uint8_t slave_addr; /*!< Slave address field */ + uart_port_t port; /*!< Modbus communication port (UART) number */ + uint32_t baudrate; /*!< Modbus baudrate */ + uart_parity_t parity; /*!< Modbus UART parity settings */ +} mb_slave_comm_info_t; + +/** + * @brief Modbus controller handler structure + */ +typedef struct { + mb_port_type_t port_type; /*!< port type */ + mb_communication_info_t mbs_comm; /*!< communication info */ + TaskHandle_t mbs_task_handle; /*!< task handle */ + EventGroupHandle_t mbs_event_group; /*!< controller event group */ + QueueHandle_t mbs_notification_queue_handle; /*!< controller notification queue */ + mb_register_area_descriptor_t mbs_area_descriptors[MB_PARAM_COUNT]; /*!< register area descriptors */ +} mb_slave_options_t; + +typedef mb_event_group_t (*iface_check_event)(mb_event_group_t); /*!< Interface method check_event */ +typedef esp_err_t (*iface_get_param_info)(mb_param_info_t*, uint32_t); /*!< Interface method get_param_info */ +typedef esp_err_t (*iface_set_descriptor)(mb_register_area_descriptor_t); /*!< Interface method set_descriptor */ + +/** + * @brief Request mode for parameter to use in data dictionary + */ +typedef struct +{ + mb_slave_options_t opts; /*!< Modbus slave options */ + + // Functional pointers to internal static functions of the implementation (public interface methods) + iface_init init; /*!< Interface method init */ + iface_destroy destroy; /*!< Interface method destroy */ + iface_setup setup; /*!< Interface method setup */ + iface_start start; /*!< Interface method start */ + iface_check_event check_event; /*!< Interface method check_event */ + iface_get_param_info get_param_info; /*!< Interface method get_param_info */ + iface_set_descriptor set_descriptor; /*!< Interface method set_descriptor */ + + // Modbus register calback function pointers + reg_discrete_cb slave_reg_cb_discrete; /*!< Stack callback discrete rw method */ + reg_input_cb slave_reg_cb_input; /*!< Stack callback input rw method */ + reg_holding_cb slave_reg_cb_holding; /*!< Stack callback holding rw method */ + reg_coils_cb slave_reg_cb_coils; /*!< Stack callback coils rw method */ +} mb_slave_interface_t; + +#endif diff --git a/components/freemodbus/component.mk b/components/freemodbus/component.mk new file mode 100644 index 00000000..e19a2428 --- /dev/null +++ b/components/freemodbus/component.mk @@ -0,0 +1,14 @@ +COMPONENT_ADD_INCLUDEDIRS := common/include +COMPONENT_PRIV_INCLUDEDIRS := common port modbus modbus/ascii modbus/functions +COMPONENT_PRIV_INCLUDEDIRS += modbus/rtu modbus/tcp modbus/include +COMPONENT_PRIV_INCLUDEDIRS += serial_slave/port serial_slave/modbus_controller +COMPONENT_PRIV_INCLUDEDIRS += serial_master/port serial_master/modbus_controller +COMPONENT_PRIV_INCLUDEDIRS += tcp_slave/port tcp_slave/modbus_controller +COMPONENT_PRIV_INCLUDEDIRS += tcp_master/port tcp_master/modbus_controller +COMPONENT_SRCDIRS := common +COMPONENT_SRCDIRS += modbus modbus/ascii modbus/functions modbus/rtu modbus/tcp +COMPONENT_SRCDIRS += serial_slave/port serial_slave/modbus_controller +COMPONENT_SRCDIRS += serial_master/port serial_master/modbus_controller +COMPONENT_SRCDIRS += tcp_slave/port tcp_slave/modbus_controller +COMPONENT_SRCDIRS += tcp_master/port tcp_master/modbus_controller +COMPONENT_SRCDIRS += port diff --git a/components/freemodbus/modbus/ascii/mbascii.c b/components/freemodbus/modbus/ascii/mbascii.c new file mode 100644 index 00000000..bbe1994b --- /dev/null +++ b/components/freemodbus/modbus/ascii/mbascii.c @@ -0,0 +1,473 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbascii.c,v 1.17 2010/06/06 13:47:07 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbconfig.h" +#include "mbascii.h" +#include "mbframe.h" + +#include "mbcrc.h" +#include "mbport.h" + +#if MB_SLAVE_ASCII_ENABLED > 0 + +/* ----------------------- Type definitions ---------------------------------*/ +typedef enum +{ + STATE_RX_IDLE, /*!< Receiver is in idle state. */ + STATE_RX_RCV, /*!< Frame is beeing received. */ + STATE_RX_WAIT_EOF /*!< Wait for End of Frame. */ +} eMBRcvState; + +typedef enum +{ + STATE_TX_IDLE, /*!< Transmitter is in idle state. */ + STATE_TX_START, /*!< Starting transmission (':' sent). */ + STATE_TX_DATA, /*!< Sending of data (Address, Data, LRC). */ + STATE_TX_END, /*!< End of transmission. */ + STATE_TX_NOTIFY /*!< Notify sender that the frame has been sent. */ +} eMBSndState; + +typedef enum +{ + BYTE_HIGH_NIBBLE, /*!< Character for high nibble of byte. */ + BYTE_LOW_NIBBLE /*!< Character for low nibble of byte. */ +} eMBBytePos; + +/* ----------------------- Shared variables ---------------------------------*/ +/* We reuse the Modbus RTU buffer because only one driver is active */ +extern volatile UCHAR ucMbSlaveBuf[]; + +/* ----------------------- Static functions ---------------------------------*/ +static UCHAR prvucMBCHAR2BIN( UCHAR ucCharacter ); + +static UCHAR prvucMBBIN2CHAR( UCHAR ucByte ); + +static UCHAR prvucMBLRC( UCHAR * pucFrame, USHORT usLen ); + +/* ----------------------- Static variables ---------------------------------*/ +static volatile eMBSndState eSndState; +static volatile eMBRcvState eRcvState; + +static volatile UCHAR *ucASCIIBuf = ucMbSlaveBuf; + +static volatile USHORT usRcvBufferPos; +static volatile eMBBytePos eBytePos; + +static volatile UCHAR *pucSndBufferCur; +static volatile USHORT usSndBufferCount; + +static volatile UCHAR ucLRC; +static volatile UCHAR ucMBLFCharacter; + +/* ----------------------- Start implementation -----------------------------*/ +eMBErrorCode +eMBASCIIInit( UCHAR ucSlaveAddress, UCHAR ucPort, ULONG ulBaudRate, eMBParity eParity ) +{ + eMBErrorCode eStatus = MB_ENOERR; + ( void )ucSlaveAddress; + + ENTER_CRITICAL_SECTION( ); + ucMBLFCharacter = MB_ASCII_DEFAULT_LF; + + if( xMBPortSerialInit( ucPort, ulBaudRate, MB_ASCII_BITS_PER_SYMB, eParity ) != TRUE ) + { + eStatus = MB_EPORTERR; + } + else if( xMBPortTimersInit( MB_ASCII_TIMEOUT_MS * 20UL ) != TRUE ) + { + eStatus = MB_EPORTERR; + } + + EXIT_CRITICAL_SECTION( ); + + return eStatus; +} + +void +eMBASCIIStart( void ) +{ + ENTER_CRITICAL_SECTION( ); + vMBPortSerialEnable( TRUE, FALSE ); + eRcvState = STATE_RX_IDLE; + EXIT_CRITICAL_SECTION( ); + + /* No special startup required for ASCII. */ + ( void )xMBPortEventPost( EV_READY ); +} + +void +eMBASCIIStop( void ) +{ + ENTER_CRITICAL_SECTION( ); + vMBPortSerialEnable( FALSE, FALSE ); + vMBPortTimersDisable( ); + EXIT_CRITICAL_SECTION( ); +} + +eMBErrorCode +eMBASCIIReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, USHORT * pusLength ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + ENTER_CRITICAL_SECTION( ); + assert( usRcvBufferPos < MB_SER_PDU_SIZE_MAX ); + + /* Length and CRC check */ + if( ( usRcvBufferPos >= MB_ASCII_SER_PDU_SIZE_MIN ) + && ( prvucMBLRC( ( UCHAR * ) ucASCIIBuf, usRcvBufferPos ) == 0 ) ) + { + /* Save the address field. All frames are passed to the upper layed + * and the decision if a frame is used is done there. + */ + *pucRcvAddress = ucASCIIBuf[MB_SER_PDU_ADDR_OFF]; + + /* Total length of Modbus-PDU is Modbus-Serial-Line-PDU minus + * size of address field and CRC checksum. + */ + *pusLength = ( USHORT )( usRcvBufferPos - MB_SER_PDU_PDU_OFF - MB_SER_PDU_SIZE_LRC ); + + /* Return the start of the Modbus PDU to the caller. */ + *pucFrame = ( UCHAR * ) & ucASCIIBuf[MB_SER_PDU_PDU_OFF]; + } + else + { + eStatus = MB_EIO; + } + EXIT_CRITICAL_SECTION( ); + return eStatus; +} + +eMBErrorCode +eMBASCIISend( UCHAR ucSlaveAddress, const UCHAR * pucFrame, USHORT usLength ) +{ + eMBErrorCode eStatus = MB_ENOERR; + UCHAR usLRC; + + ENTER_CRITICAL_SECTION( ); + /* Check if the receiver is still in idle state. If not we where too + * slow with processing the received frame and the master sent another + * frame on the network. We have to abort sending the frame. + */ + if( eRcvState == STATE_RX_IDLE ) + { + /* First byte before the Modbus-PDU is the slave address. */ + pucSndBufferCur = ( UCHAR * ) pucFrame - 1; + usSndBufferCount = 1; + + /* Now copy the Modbus-PDU into the Modbus-Serial-Line-PDU. */ + pucSndBufferCur[MB_SER_PDU_ADDR_OFF] = ucSlaveAddress; + usSndBufferCount += usLength; + + /* Calculate LRC checksum for Modbus-Serial-Line-PDU. */ + usLRC = prvucMBLRC( ( UCHAR * ) pucSndBufferCur, usSndBufferCount ); + ucASCIIBuf[usSndBufferCount++] = usLRC; + + /* Activate the transmitter. */ + eSndState = STATE_TX_START; + vMBPortSerialEnable( FALSE, TRUE ); + } + else + { + eStatus = MB_EIO; + } + EXIT_CRITICAL_SECTION( ); + return eStatus; +} + +BOOL +xMBASCIIReceiveFSM( void ) +{ + BOOL xNeedPoll = FALSE; + UCHAR ucByte; + UCHAR ucResult; + + assert( eSndState == STATE_TX_IDLE ); + + xNeedPoll = xMBPortSerialGetByte( ( CHAR * ) & ucByte ); + switch ( eRcvState ) + { + /* A new character is received. If the character is a ':' the input + * buffer is cleared. A CR-character signals the end of the data + * block. Other characters are part of the data block and their + * ASCII value is converted back to a binary representation. + */ + case STATE_RX_RCV: + /* Enable timer for character timeout. */ + vMBPortTimersEnable( ); + if( ucByte == ':' ) + { + /* Empty receive buffer. */ + eBytePos = BYTE_HIGH_NIBBLE; + usRcvBufferPos = 0; + } + else if( ucByte == MB_ASCII_DEFAULT_CR ) + { + eRcvState = STATE_RX_WAIT_EOF; + } + else + { + ucResult = prvucMBCHAR2BIN( ucByte ); + switch ( eBytePos ) + { + /* High nibble of the byte comes first. We check for + * a buffer overflow here. */ + case BYTE_HIGH_NIBBLE: + if( usRcvBufferPos < MB_SER_PDU_SIZE_MAX ) + { + ucASCIIBuf[usRcvBufferPos] = ( UCHAR )( ucResult << 4 ); + eBytePos = BYTE_LOW_NIBBLE; + break; + } + else + { + /* not handled in Modbus specification but seems + * a resonable implementation. */ + eRcvState = STATE_RX_IDLE; + /* Disable previously activated timer because of error state. */ + vMBPortTimersDisable( ); + } + break; + + case BYTE_LOW_NIBBLE: + ucASCIIBuf[usRcvBufferPos] |= ucResult; + usRcvBufferPos++; + eBytePos = BYTE_HIGH_NIBBLE; + break; + } + } + break; + + case STATE_RX_WAIT_EOF: + if( ucByte == ucMBLFCharacter ) + { + /* Disable character timeout timer because all characters are + * received. */ + vMBPortTimersDisable( ); + /* Receiver is again in idle state. */ + eRcvState = STATE_RX_IDLE; + + /* Notify the caller of eMBASCIIReceive that a new frame + * was received. */ + (void)xMBPortEventPost( EV_FRAME_RECEIVED ); + } + else if( ucByte == ':' ) + { + /* Empty receive buffer and back to receive state. */ + eBytePos = BYTE_HIGH_NIBBLE; + usRcvBufferPos = 0; + eRcvState = STATE_RX_RCV; + + /* Enable timer for character timeout. */ + vMBPortTimersEnable( ); + } + else + { + /* Frame is not okay. Delete entire frame. */ + eRcvState = STATE_RX_IDLE; + } + break; + + case STATE_RX_IDLE: + if( ucByte == ':' ) + { + /* Enable timer for character timeout. */ + vMBPortTimersEnable( ); + /* Reset the input buffers to store the frame. */ + usRcvBufferPos = 0; + eBytePos = BYTE_HIGH_NIBBLE; + eRcvState = STATE_RX_RCV; + } + break; + } + + return xNeedPoll; +} + +BOOL +xMBASCIITransmitFSM( void ) +{ + BOOL xNeedPoll = TRUE; + UCHAR ucByte; + + assert( eRcvState == STATE_RX_IDLE ); + switch ( eSndState ) + { + /* Start of transmission. The start of a frame is defined by sending + * the character ':'. */ + case STATE_TX_START: + ucByte = ':'; + xMBPortSerialPutByte( ( CHAR )ucByte ); + eSndState = STATE_TX_DATA; + eBytePos = BYTE_HIGH_NIBBLE; + break; + + /* Send the data block. Each data byte is encoded as a character hex + * stream with the high nibble sent first and the low nibble sent + * last. If all data bytes are exhausted we send a '\r' character + * to end the transmission. */ + case STATE_TX_DATA: + if( usSndBufferCount > 0 ) + { + switch ( eBytePos ) + { + case BYTE_HIGH_NIBBLE: + ucByte = prvucMBBIN2CHAR( ( UCHAR )( *pucSndBufferCur >> 4 ) ); + xMBPortSerialPutByte( ( CHAR ) ucByte ); + eBytePos = BYTE_LOW_NIBBLE; + break; + + case BYTE_LOW_NIBBLE: + ucByte = prvucMBBIN2CHAR( ( UCHAR )( *pucSndBufferCur & 0x0F ) ); + xMBPortSerialPutByte( ( CHAR )ucByte ); + pucSndBufferCur++; + eBytePos = BYTE_HIGH_NIBBLE; + usSndBufferCount--; + break; + } + } + else + { + xMBPortSerialPutByte( MB_ASCII_DEFAULT_CR ); + eSndState = STATE_TX_END; + } + break; + + /* Finish the frame by sending a LF character. */ + case STATE_TX_END: + xMBPortSerialPutByte( ( CHAR )ucMBLFCharacter ); + /* We need another state to make sure that the CR character has + * been sent. */ + eSndState = STATE_TX_NOTIFY; + break; + + /* Notify the task which called eMBASCIISend that the frame has + * been sent. */ + case STATE_TX_NOTIFY: + eSndState = STATE_TX_IDLE; + xMBPortEventPost( EV_FRAME_TRANSMIT ); + xNeedPoll = FALSE; + break; + + /* We should not get a transmitter event if the transmitter is in + * idle state. */ + case STATE_TX_IDLE: + break; + } + + return xNeedPoll; +} + +BOOL MB_PORT_ISR_ATTR +xMBASCIITimerT1SExpired( void ) +{ + switch ( eRcvState ) + { + /* If we have a timeout we go back to the idle state and wait for + * the next frame. + */ + case STATE_RX_RCV: + case STATE_RX_WAIT_EOF: + eRcvState = STATE_RX_IDLE; + break; + + default: + assert( ( eRcvState == STATE_RX_RCV ) || ( eRcvState == STATE_RX_WAIT_EOF ) + || (eRcvState == STATE_RX_IDLE )); + break; + } + vMBPortTimersDisable( ); + + /* no context switch required. */ + return FALSE; +} + + +static UCHAR +prvucMBCHAR2BIN( UCHAR ucCharacter ) +{ + if( ( ucCharacter >= '0' ) && ( ucCharacter <= '9' ) ) + { + return ( UCHAR )( ucCharacter - '0' ); + } + else if( ( ucCharacter >= 'A' ) && ( ucCharacter <= 'F' ) ) + { + return ( UCHAR )( ucCharacter - 'A' + 0x0A ); + } + else + { + return 0xFF; + } +} + +static UCHAR +prvucMBBIN2CHAR( UCHAR ucByte ) +{ + if( ucByte <= 0x09 ) + { + return ( UCHAR )( '0' + ucByte ); + } + else if( ( ucByte >= 0x0A ) && ( ucByte <= 0x0F ) ) + { + return ( UCHAR )( ucByte - 0x0A + 'A' ); + } + else + { + /* Programming error. */ + assert( 0 ); + } + return '0'; +} + + +static UCHAR +prvucMBLRC( UCHAR * pucFrame, USHORT usLen ) +{ + UCHAR ucLRC = 0; /* LRC char initialized */ + + while( usLen-- ) + { + ucLRC += *pucFrame++; /* Add buffer byte without carry */ + } + + /* Return twos complement */ + ucLRC = ( UCHAR ) ( -( ( CHAR ) ucLRC ) ); + return ucLRC; +} + +#endif diff --git a/components/freemodbus/modbus/ascii/mbascii.h b/components/freemodbus/modbus/ascii/mbascii.h new file mode 100644 index 00000000..535701b6 --- /dev/null +++ b/components/freemodbus/modbus/ascii/mbascii.h @@ -0,0 +1,78 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbascii.h,v 1.8 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_ASCII_H +#define _MB_ASCII_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_ASCII_DEFAULT_CR '\r' /*!< Default CR character for Modbus ASCII. */ +#define MB_ASCII_DEFAULT_LF '\n' /*!< Default LF character for Modbus ASCII. */ +#define MB_ASCII_SER_PDU_SIZE_MIN 3 /*!< Minimum size of a Modbus ASCII frame. */ + +/* ----------------------- Function declaration -----------------------------*/ + +#if MB_SLAVE_ASCII_ENABLED > 0 +eMBErrorCode eMBASCIIInit( UCHAR slaveAddress, UCHAR ucPort, + ULONG ulBaudRate, eMBParity eParity ); +void eMBASCIIStart( void ); +void eMBASCIIStop( void ); + +eMBErrorCode eMBASCIIReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, + USHORT * pusLength ); +eMBErrorCode eMBASCIISend( UCHAR slaveAddress, const UCHAR * pucFrame, + USHORT usLength ); +BOOL xMBASCIIReceiveFSM( void ); +BOOL xMBASCIITransmitFSM( void ); +BOOL xMBASCIITimerT1SExpired( void ); +#endif + +#if MB_MASTER_ASCII_ENABLED > 0 +eMBErrorCode eMBMasterASCIIInit( UCHAR ucPort, + ULONG ulBaudRate, eMBParity eParity ); +void eMBMasterASCIIStart( void ); +void eMBMasterASCIIStop( void ); + +eMBErrorCode eMBMasterASCIIReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, + USHORT * pusLength ); +eMBErrorCode eMBMasterASCIISend( UCHAR slaveAddress, const UCHAR * pucFrame, + USHORT usLength ); +BOOL xMBMasterASCIIReceiveFSM( void ); +BOOL xMBMasterASCIITransmitFSM( void ); +BOOL xMBMasterASCIITimerT1SExpired( void ); +#endif + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/ascii/mbascii_m.c b/components/freemodbus/modbus/ascii/mbascii_m.c new file mode 100644 index 00000000..b6327c2a --- /dev/null +++ b/components/freemodbus/modbus/ascii/mbascii_m.c @@ -0,0 +1,573 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbascii.c,v 1.17 2010/06/06 13:47:07 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb_m.h" +#include "mbconfig.h" +#include "mbascii.h" +#include "mbframe.h" + +#include "mbcrc.h" +#include "mbport.h" + +#if MB_MASTER_ASCII_ENABLED > 0 + +/* ----------------------- Defines ------------------------------------------*/ + +/* ----------------------- Type definitions ---------------------------------*/ +typedef enum +{ + STATE_M_RX_INIT, /*!< Receiver is in initial state. */ + STATE_M_RX_IDLE, /*!< Receiver is in idle state. */ + STATE_M_RX_RCV, /*!< Frame is beeing received. */ + STATE_M_RX_WAIT_EOF, /*!< Wait for End of Frame. */ + STATE_M_RX_ERROR, /*!< If the frame is invalid. */ +} eMBMasterAsciiRcvState; + +typedef enum +{ + STATE_M_TX_IDLE, /*!< Transmitter is in idle state. */ + STATE_M_TX_START, /*!< Starting transmission (':' sent). */ + STATE_M_TX_DATA, /*!< Sending of data (Address, Data, LRC). */ + STATE_M_TX_END, /*!< End of transmission. */ + STATE_M_TX_NOTIFY, /*!< Notify sender that the frame has been sent. */ + STATE_M_TX_XFWR, /*!< Transmitter is in transfer finish and wait receive state. */ +} eMBMasterAsciiSndState; + +typedef enum +{ + BYTE_HIGH_NIBBLE, /*!< Character for high nibble of byte. */ + BYTE_LOW_NIBBLE /*!< Character for low nibble of byte. */ +} eMBBytePos; + +/* ----------------------- Shared values -----------------------------------*/ +/* These Modbus values are shared in ASCII mode*/ +extern volatile UCHAR ucMasterRcvBuf[]; +extern volatile UCHAR ucMasterSndBuf[]; +extern volatile eMBMasterTimerMode eMasterCurTimerMode; + +/* ----------------------- Static functions ---------------------------------*/ +static UCHAR prvucMBCHAR2BIN( UCHAR ucCharacter ); + +static UCHAR prvucMBBIN2CHAR( UCHAR ucByte ); + +static UCHAR prvucMBLRC( UCHAR * pucFrame, USHORT usLen ); + +/* ----------------------- Static variables ---------------------------------*/ +static volatile eMBMasterAsciiSndState eSndState; +static volatile eMBMasterAsciiRcvState eRcvState; + +static volatile UCHAR *ucMasterASCIIRcvBuf = ucMasterRcvBuf; +static volatile UCHAR *ucMasterASCIISndBuf = ucMasterSndBuf; + +static volatile USHORT usMasterRcvBufferPos; +static volatile eMBBytePos eBytePos; + +static volatile UCHAR *pucMasterSndBufferCur; +static volatile USHORT usMasterSndBufferCount; + +static volatile UCHAR ucLRC; +static volatile UCHAR ucMBLFCharacter; + +/* ----------------------- Start implementation -----------------------------*/ +eMBErrorCode +eMBMasterASCIIInit( UCHAR ucPort, ULONG ulBaudRate, eMBParity eParity ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + ENTER_CRITICAL_SECTION( ); + ucMBLFCharacter = MB_ASCII_DEFAULT_LF; + + if( xMBMasterPortSerialInit( ucPort, ulBaudRate, MB_ASCII_BITS_PER_SYMB, eParity ) != TRUE ) + { + eStatus = MB_EPORTERR; + } + else if( xMBMasterPortTimersInit( MB_ASCII_TIMEOUT_MS * MB_TIMER_TICS_PER_MS ) != TRUE ) + { + eStatus = MB_EPORTERR; + } + + EXIT_CRITICAL_SECTION( ); + + return eStatus; +} + +void +eMBMasterASCIIStart( void ) +{ + ENTER_CRITICAL_SECTION( ); + eRcvState = STATE_M_RX_IDLE; + vMBMasterPortSerialEnable( TRUE, FALSE ); + vMBMasterPortTimersT35Enable( ); + EXIT_CRITICAL_SECTION( ); +} + +void +eMBMasterASCIIStop( void ) +{ + ENTER_CRITICAL_SECTION( ); + vMBMasterPortSerialEnable( FALSE, FALSE ); + vMBMasterPortTimersDisable( ); + EXIT_CRITICAL_SECTION( ); +} + +eMBErrorCode +eMBMasterASCIIReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, USHORT * pusLength ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + ENTER_CRITICAL_SECTION( ); + assert( usMasterRcvBufferPos < MB_SER_PDU_SIZE_MAX ); + + /* Length and CRC check */ + if( ( usMasterRcvBufferPos >= MB_ASCII_SER_PDU_SIZE_MIN ) + && ( prvucMBLRC( ( UCHAR * ) ucMasterASCIIRcvBuf, usMasterRcvBufferPos ) == 0 ) ) + { + /* Save the address field. All frames are passed to the upper layed + * and the decision if a frame is used is done there. + */ + *pucRcvAddress = ucMasterASCIIRcvBuf[MB_SER_PDU_ADDR_OFF]; + + /* Total length of Modbus-PDU is Modbus-Serial-Line-PDU minus + * size of address field and CRC checksum. + */ + *pusLength = ( USHORT )( usMasterRcvBufferPos - MB_SER_PDU_PDU_OFF - MB_SER_PDU_SIZE_LRC ); + + /* Return the start of the Modbus PDU to the caller. */ + *pucFrame = ( UCHAR * ) & ucMasterASCIIRcvBuf[MB_SER_PDU_PDU_OFF]; + } + else + { + eStatus = MB_EIO; + } + EXIT_CRITICAL_SECTION( ); + return eStatus; +} + +eMBErrorCode +eMBMasterASCIISend( UCHAR ucSlaveAddress, const UCHAR * pucFrame, USHORT usLength ) +{ + eMBErrorCode eStatus = MB_ENOERR; + UCHAR usLRC; + + if ( ucSlaveAddress > MB_MASTER_TOTAL_SLAVE_NUM ) return MB_EINVAL; + + ENTER_CRITICAL_SECTION( ); + /* Check if the receiver is still in idle state. If not we where too + * slow with processing the received frame and the master sent another + * frame on the network. We have to abort sending the frame. + */ + if(eRcvState == STATE_M_RX_IDLE) + { + /* First byte before the Modbus-PDU is the slave address. */ + pucMasterSndBufferCur = ( UCHAR * ) pucFrame - 1; + usMasterSndBufferCount = 1; + + /* Now copy the Modbus-PDU into the Modbus-Serial-Line-PDU. */ + pucMasterSndBufferCur[MB_SER_PDU_ADDR_OFF] = ucSlaveAddress; + usMasterSndBufferCount += usLength; + + /* Calculate LRC checksum for Modbus-Serial-Line-PDU. */ + usLRC = prvucMBLRC( ( UCHAR * ) pucMasterSndBufferCur, usMasterSndBufferCount ); + ucMasterASCIISndBuf[usMasterSndBufferCount++] = usLRC; + + /* Activate the transmitter. */ + eSndState = STATE_M_TX_START; + vMBMasterPortSerialEnable( FALSE, TRUE ); + } + else + { + eStatus = MB_EIO; + } + EXIT_CRITICAL_SECTION( ); + return eStatus; +} + +BOOL +xMBMasterASCIIReceiveFSM( void ) +{ + BOOL xNeedPoll = FALSE; + UCHAR ucByte; + UCHAR ucResult; + + assert(( eSndState == STATE_M_TX_IDLE ) || ( eSndState == STATE_M_TX_XFWR )); + + /* Always read the character. */ + xNeedPoll = xMBMasterPortSerialGetByte( ( CHAR * ) & ucByte ); + + switch ( eRcvState ) + { + /* If we have received a character in the init state we have to + * wait until the frame is finished. + */ + case STATE_M_RX_INIT: + vMBMasterPortTimersT35Enable( ); + break; + + /* In the error state we wait until all characters in the + * damaged frame are transmitted. + */ + case STATE_M_RX_ERROR: + vMBMasterPortTimersRespondTimeoutEnable( ); + break; + + /* In the idle state we wait for a new character. If a character + * is received the t1.5 and t3.5 timers are started and the + * receiver is in the state STATE_RX_RECEIVE and disable early + * the timer of respond timeout . + */ + case STATE_M_RX_IDLE: + /* Waiting for the start of frame character during respond timeout */ + vMBMasterPortTimersRespondTimeoutEnable( ); + if( ucByte == ':' ) + { + /* Reset the input buffers to store the frame in receive state. */ + usMasterRcvBufferPos = 0; + eBytePos = BYTE_HIGH_NIBBLE; + eRcvState = STATE_M_RX_RCV; + } + eSndState = STATE_M_TX_IDLE; + break; + + /* A new character is received. If the character is a ':' the input + * buffer is cleared. A CR-character signals the end of the data + * block. Other characters are part of the data block and their + * ASCII value is converted back to a binary representation. + */ + case STATE_M_RX_RCV: + /* Enable timer timeout. */ + vMBMasterPortTimersT35Enable( ); + if( ucByte == ':' ) + { + /* Empty receive buffer. */ + eBytePos = BYTE_HIGH_NIBBLE; + usMasterRcvBufferPos = 0; + } + else if( ucByte == MB_ASCII_DEFAULT_CR ) + { + eRcvState = STATE_M_RX_WAIT_EOF; + } + else + { + ucResult = prvucMBCHAR2BIN( ucByte ); + switch ( eBytePos ) + { + /* High nibble of the byte comes first. We check for + * a buffer overflow here. */ + case BYTE_HIGH_NIBBLE: + if( usMasterRcvBufferPos < MB_SER_PDU_SIZE_MAX ) + { + ucMasterASCIIRcvBuf[usMasterRcvBufferPos] = ( UCHAR )( ucResult << 4 ); + eBytePos = BYTE_LOW_NIBBLE; + break; + } + else + { + /* not handled in Modbus specification but seems + * a resonable implementation. */ + eRcvState = STATE_M_RX_ERROR; + /* Disable previously activated timer because of error state. */ + vMBPortTimersDisable( ); + } + break; + + case BYTE_LOW_NIBBLE: + ucMasterASCIIRcvBuf[usMasterRcvBufferPos] |= ucResult; + usMasterRcvBufferPos++; + eBytePos = BYTE_HIGH_NIBBLE; + break; + } + } + break; + + case STATE_M_RX_WAIT_EOF: + if( ucByte == ucMBLFCharacter ) + { + /* Disable character timeout timer because all characters are + * received. */ + vMBMasterPortTimersDisable( ); + /* Receiver is again in idle state. */ + eRcvState = STATE_M_RX_IDLE; + + /* Notify the caller of eMBMasterASCIIReceive that a new frame + * was received. */ + (void)xMBMasterPortEventPost( EV_MASTER_FRAME_RECEIVED ); + xNeedPoll = FALSE; + } + else if( ucByte == ':' ) + { + /* Start of frame character received but last message is not completed. + * Empty receive buffer and back to receive state. */ + eBytePos = BYTE_HIGH_NIBBLE; + usMasterRcvBufferPos = 0; + eRcvState = STATE_M_RX_IDLE; + + /* Enable timer for respond timeout and wait for next frame. */ + vMBMasterPortTimersRespondTimeoutEnable( ); + } + else + { + /* Frame is not okay. Delete entire frame. */ + eRcvState = STATE_M_RX_IDLE; + } + break; + } + + return xNeedPoll; +} + +BOOL +xMBMasterASCIITransmitFSM( void ) +{ + BOOL xNeedPoll = TRUE; + UCHAR ucByte; + BOOL xFrameIsBroadcast = FALSE; + + assert( eRcvState == STATE_M_RX_IDLE ); + + switch ( eSndState ) + { + /* We should not get a transmitter event if the transmitter is in + * idle state. */ + case STATE_M_TX_XFWR: + break; + + /* We should not get a transmitter event if the transmitter is in + * idle state. */ + case STATE_M_TX_IDLE: + break; + + /* Start of transmission. The start of a frame is defined by sending + * the character ':'. */ + case STATE_M_TX_START: + ucByte = ':'; + xMBMasterPortSerialPutByte( ( CHAR )ucByte ); + eSndState = STATE_M_TX_DATA; + eBytePos = BYTE_HIGH_NIBBLE; + break; + + /* Send the data block. Each data byte is encoded as a character hex + * stream with the high nibble sent first and the low nibble sent + * last. If all data bytes are exhausted we send a '\r' character + * to end the transmission. */ + case STATE_M_TX_DATA: + if( usMasterSndBufferCount > 0 ) + { + switch ( eBytePos ) + { + case BYTE_HIGH_NIBBLE: + ucByte = prvucMBBIN2CHAR( ( UCHAR )( *pucMasterSndBufferCur >> 4 ) ); + xMBMasterPortSerialPutByte( ( CHAR ) ucByte ); + eBytePos = BYTE_LOW_NIBBLE; + break; + + case BYTE_LOW_NIBBLE: + ucByte = prvucMBBIN2CHAR( ( UCHAR )( *pucMasterSndBufferCur & 0x0F ) ); + xMBMasterPortSerialPutByte( ( CHAR )ucByte ); + pucMasterSndBufferCur++; + eBytePos = BYTE_HIGH_NIBBLE; + usMasterSndBufferCount--; + break; + } + } + else + { + xMBMasterPortSerialPutByte( MB_ASCII_DEFAULT_CR ); + eSndState = STATE_M_TX_END; + } + break; + + /* Finish the frame by sending a LF character. */ + case STATE_M_TX_END: + xMBMasterPortSerialPutByte( ( CHAR )ucMBLFCharacter ); + /* We need another state to make sure that the CR character has + * been sent. */ + eSndState = STATE_M_TX_NOTIFY; + break; + + /* Notify the task which called eMBMasterASCIISend that the frame has + * been sent. */ + case STATE_M_TX_NOTIFY: + xFrameIsBroadcast = ( ucMasterASCIISndBuf[MB_SER_PDU_ADDR_OFF] == MB_ADDRESS_BROADCAST ) ? TRUE : FALSE; + vMBMasterRequestSetType( xFrameIsBroadcast ); + eSndState = STATE_M_TX_XFWR; + /* If the frame is broadcast ,master will enable timer of convert delay, + * else master will enable timer of respond timeout. */ + if ( xFrameIsBroadcast == TRUE ) + { + vMBMasterPortTimersConvertDelayEnable( ); + } + else + { + vMBMasterPortTimersRespondTimeoutEnable( ); + } + xNeedPoll = FALSE; + break; + } + + return xNeedPoll; +} + +BOOL +xMBMasterASCIITimerT1SExpired( void ) +{ + BOOL xNeedPoll = FALSE; + + switch ( eRcvState ) + { + /* Timer t35 expired. Startup phase is finished. */ + case STATE_M_RX_INIT: + xNeedPoll = xMBMasterPortEventPost(EV_MASTER_READY); + ESP_EARLY_LOGI("xMBMasterASCIITimerT1SExpired", "RX_INIT_EXPIRED"); + break; + + /* Start of message is not received during respond timeout. + * Process error. */ + case STATE_M_RX_IDLE: + eRcvState = STATE_M_RX_ERROR; + break; + + /* A recieve timeout expired and no any new character received. + * Wait for respond time and go to error state to inform listener about error */ + case STATE_M_RX_RCV: + eRcvState = STATE_M_RX_ERROR; + break; + + /* An error occured while receiving the frame. */ + case STATE_M_RX_ERROR: + vMBMasterSetErrorType(EV_ERROR_RECEIVE_DATA); + xNeedPoll = xMBMasterPortEventPost( EV_MASTER_ERROR_PROCESS ); + break; + + /* If we have a timeout we go back to the idle state and wait for + * the next frame. + */ + case STATE_M_RX_WAIT_EOF: + eRcvState = STATE_M_RX_IDLE; + break; + + default: + assert( 0 ); + break; + } + eRcvState = STATE_M_RX_IDLE; + + switch (eSndState) + { + /* A frame was send finish and convert delay or respond timeout expired. + * If the frame is broadcast,The master will idle,and if the frame is not + * broadcast.*/ + case STATE_M_TX_XFWR: + if ( xMBMasterRequestIsBroadcast( ) == FALSE ) { + vMBMasterSetErrorType(EV_ERROR_RESPOND_TIMEOUT); + xNeedPoll = xMBMasterPortEventPost(EV_MASTER_ERROR_PROCESS); + } + break; + + /* Function called in an illegal state. */ + default: + assert( ( eSndState == STATE_M_TX_START ) || ( eSndState == STATE_M_TX_IDLE ) + || ( eSndState == STATE_M_TX_DATA ) || ( eSndState == STATE_M_TX_END ) + || ( eSndState == STATE_M_TX_NOTIFY ) ); + break; + } + eSndState = STATE_M_TX_IDLE; + + vMBMasterPortTimersDisable( ); + /* If timer mode is convert delay, the master event then turns EV_MASTER_EXECUTE status. */ + if (xMBMasterGetCurTimerMode() == MB_TMODE_CONVERT_DELAY) { + xNeedPoll = xMBMasterPortEventPost( EV_MASTER_EXECUTE ); + } + + vMBMasterPortTimersDisable( ); + + /* no context switch required. */ + return xNeedPoll; +} + +static UCHAR +prvucMBCHAR2BIN( UCHAR ucCharacter ) +{ + if( ( ucCharacter >= '0' ) && ( ucCharacter <= '9' ) ) + { + return ( UCHAR )( ucCharacter - '0' ); + } + else if( ( ucCharacter >= 'A' ) && ( ucCharacter <= 'F' ) ) + { + return ( UCHAR )( ucCharacter - 'A' + 0x0A ); + } + else + { + return 0xFF; + } +} + +static UCHAR +prvucMBBIN2CHAR( UCHAR ucByte ) +{ + if( ucByte <= 0x09 ) + { + return ( UCHAR )( '0' + ucByte ); + } + else if( ( ucByte >= 0x0A ) && ( ucByte <= 0x0F ) ) + { + return ( UCHAR )( ucByte - 0x0A + 'A' ); + } + else + { + /* Programming error. */ + assert( 0 ); + } + return '0'; +} + +static UCHAR +prvucMBLRC( UCHAR * pucFrame, USHORT usLen ) +{ + UCHAR ucLRC = 0; /* LRC char initialized */ + + while( usLen-- ) + { + ucLRC += *pucFrame++; /* Add buffer byte without carry */ + } + + /* Return twos complement */ + ucLRC = ( UCHAR ) ( -( ( CHAR ) ucLRC ) ); + return ucLRC; +} + +#endif diff --git a/components/freemodbus/modbus/functions/mbfunccoils.c b/components/freemodbus/modbus/functions/mbfunccoils.c new file mode 100644 index 00000000..458ff5ca --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfunccoils.c @@ -0,0 +1,273 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfunccoils.c,v 1.8 2007/02/18 23:47:16 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbconfig.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_PDU_FUNC_READ_ADDR_OFF ( MB_PDU_DATA_OFF ) +#define MB_PDU_FUNC_READ_COILCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_READ_SIZE ( 4 ) +#define MB_PDU_FUNC_READ_COILCNT_MAX ( 0x07D0 ) + +#define MB_PDU_FUNC_WRITE_ADDR_OFF ( MB_PDU_DATA_OFF ) +#define MB_PDU_FUNC_WRITE_VALUE_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_WRITE_SIZE ( 4 ) + +#define MB_PDU_FUNC_WRITE_MUL_ADDR_OFF ( MB_PDU_DATA_OFF ) +#define MB_PDU_FUNC_WRITE_MUL_COILCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF ( MB_PDU_DATA_OFF + 4 ) +#define MB_PDU_FUNC_WRITE_MUL_VALUES_OFF ( MB_PDU_DATA_OFF + 5 ) +#define MB_PDU_FUNC_WRITE_MUL_SIZE_MIN ( 5 ) +#define MB_PDU_FUNC_WRITE_MUL_COILCNT_MAX ( 0x07B0 ) + +/* ----------------------- Static functions ---------------------------------*/ +eMBException prveMBError2Exception( eMBErrorCode eErrorCode ); + +/* ----------------------- Start implementation -----------------------------*/ +#if MB_SLAVE_RTU_ENABLED || MB_SLAVE_ASCII_ENABLED || MB_TCP_ENABLED + +#if MB_FUNC_READ_COILS_ENABLED + +eMBException +eMBFuncReadCoils( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + USHORT usCoilCount; + UCHAR ucNBytes; + UCHAR *pucFrameCur; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen == ( MB_PDU_FUNC_READ_SIZE + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF + 1] ); + usRegAddress++; + + usCoilCount = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_COILCNT_OFF] << 8 ); + usCoilCount |= ( USHORT )( pucFrame[MB_PDU_FUNC_READ_COILCNT_OFF + 1] ); + + /* Check if the number of registers to read is valid. If not + * return Modbus illegal data value exception. + */ + if( ( usCoilCount >= 1 ) && + ( usCoilCount < MB_PDU_FUNC_READ_COILCNT_MAX ) ) + { + /* Set the current PDU data pointer to the beginning. */ + pucFrameCur = &pucFrame[MB_PDU_FUNC_OFF]; + *usLen = MB_PDU_FUNC_OFF; + + /* First byte contains the function code. */ + *pucFrameCur++ = MB_FUNC_READ_COILS; + *usLen += 1; + + /* Test if the quantity of coils is a multiple of 8. If not last + * byte is only partially field with unused coils set to zero. */ + if( ( usCoilCount & 0x0007 ) != 0 ) + { + ucNBytes = ( UCHAR )( usCoilCount / 8 + 1 ); + } + else + { + ucNBytes = ( UCHAR )( usCoilCount / 8 ); + } + *pucFrameCur++ = ucNBytes; + *usLen += 1; + + eRegStatus = + eMBRegCoilsCB( pucFrameCur, usRegAddress, usCoilCount, + MB_REG_READ ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + else + { + /* The response contains the function code, the starting address + * and the quantity of registers. We reuse the old values in the + * buffer because they are still valid. */ + *usLen += ucNBytes;; + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid read coil register request because the length + * is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#if MB_FUNC_WRITE_COIL_ENABLED > 0 +eMBException +eMBFuncWriteCoil( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + UCHAR ucBuf[2]; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen == ( MB_PDU_FUNC_WRITE_SIZE + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF + 1] ); + usRegAddress++; + + if( ( pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF + 1] == 0x00 ) && + ( ( pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF] == 0xFF ) || + ( pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF] == 0x00 ) ) ) + { + ucBuf[1] = 0; + if( pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF] == 0xFF ) + { + ucBuf[0] = 1; + } + else + { + ucBuf[0] = 0; + } + eRegStatus = + eMBRegCoilsCB( &ucBuf[0], usRegAddress, 1, MB_REG_WRITE ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid write coil register request because the length + * is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#endif + +#if MB_FUNC_WRITE_MULTIPLE_COILS_ENABLED > 0 +eMBException +eMBFuncWriteMultipleCoils( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + USHORT usCoilCnt; + UCHAR ucByteCount; + UCHAR ucByteCountVerify; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen > ( MB_PDU_FUNC_WRITE_SIZE + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF + 1] ); + usRegAddress++; + + usCoilCnt = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_COILCNT_OFF] << 8 ); + usCoilCnt |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_COILCNT_OFF + 1] ); + + ucByteCount = pucFrame[MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF]; + + /* Compute the number of expected bytes in the request. */ + if( ( usCoilCnt & 0x0007 ) != 0 ) + { + ucByteCountVerify = ( UCHAR )( usCoilCnt / 8 + 1 ); + } + else + { + ucByteCountVerify = ( UCHAR )( usCoilCnt / 8 ); + } + + if( ( usCoilCnt >= 1 ) && + ( usCoilCnt <= MB_PDU_FUNC_WRITE_MUL_COILCNT_MAX ) && + ( ucByteCountVerify == ucByteCount ) ) + { + eRegStatus = + eMBRegCoilsCB( &pucFrame[MB_PDU_FUNC_WRITE_MUL_VALUES_OFF], + usRegAddress, usCoilCnt, MB_REG_WRITE ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + else + { + /* The response contains the function code, the starting address + * and the quantity of registers. We reuse the old values in the + * buffer because they are still valid. */ + *usLen = MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF; + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid write coil register request because the length + * is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#endif + +#endif + +#endif diff --git a/components/freemodbus/modbus/functions/mbfunccoils_m.c b/components/freemodbus/modbus/functions/mbfunccoils_m.c new file mode 100644 index 00000000..036808c7 --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfunccoils_m.c @@ -0,0 +1,391 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (C) 2013 Armink + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfunccoils_m.c,v 1.60 2013/10/12 15:10:12 Armink Add Master Functions + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb_m.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbconfig.h" +#include "mbutils.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_PDU_REQ_READ_ADDR_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_REQ_READ_COILCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_REQ_READ_SIZE ( 4 ) +#define MB_PDU_FUNC_READ_COILCNT_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_FUNC_READ_VALUES_OFF ( MB_PDU_DATA_OFF + 1 ) +#define MB_PDU_FUNC_READ_SIZE_MIN ( 1 ) + +#define MB_PDU_REQ_WRITE_ADDR_OFF ( MB_PDU_DATA_OFF ) +#define MB_PDU_REQ_WRITE_VALUE_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_REQ_WRITE_SIZE ( 4 ) +#define MB_PDU_FUNC_WRITE_ADDR_OFF ( MB_PDU_DATA_OFF ) +#define MB_PDU_FUNC_WRITE_VALUE_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_WRITE_SIZE ( 4 ) + +#define MB_PDU_REQ_WRITE_MUL_ADDR_OFF ( MB_PDU_DATA_OFF ) +#define MB_PDU_REQ_WRITE_MUL_COILCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_REQ_WRITE_MUL_BYTECNT_OFF ( MB_PDU_DATA_OFF + 4 ) +#define MB_PDU_REQ_WRITE_MUL_VALUES_OFF ( MB_PDU_DATA_OFF + 5 ) +#define MB_PDU_REQ_WRITE_MUL_SIZE_MIN ( 5 ) +#define MB_PDU_REQ_WRITE_MUL_COILCNT_MAX ( 0x07B0 ) +#define MB_PDU_FUNC_WRITE_MUL_ADDR_OFF ( MB_PDU_DATA_OFF ) +#define MB_PDU_FUNC_WRITE_MUL_COILCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_WRITE_MUL_SIZE ( 5 ) + +/* ----------------------- Static functions ---------------------------------*/ +eMBException prveMBError2Exception( eMBErrorCode eErrorCode ); + +/* ----------------------- Start implementation -----------------------------*/ +#if MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED + +#if MB_FUNC_READ_COILS_ENABLED + +/** + * This function will request read coil. + * + * @param ucSndAddr salve address + * @param usCoilAddr coil start address + * @param usNCoils coil total number + * @param lTimeOut timeout (-1 will waiting forever) + * + * @return error code + */ +eMBMasterReqErrCode +eMBMasterReqReadCoils( UCHAR ucSndAddr, USHORT usCoilAddr, USHORT usNCoils, LONG lTimeOut ) +{ + UCHAR *ucMBFrame; + eMBMasterReqErrCode eErrStatus = MB_MRE_NO_ERR; + + if ( ucSndAddr > MB_MASTER_TOTAL_SLAVE_NUM ) eErrStatus = MB_MRE_ILL_ARG; + else if ( xMBMasterRunResTake( lTimeOut ) == FALSE ) eErrStatus = MB_MRE_MASTER_BUSY; + else + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + vMBMasterSetDestAddress(ucSndAddr); + ucMBFrame[MB_PDU_FUNC_OFF] = MB_FUNC_READ_COILS; + ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF] = usCoilAddr >> 8; + ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF + 1] = usCoilAddr; + ucMBFrame[MB_PDU_REQ_READ_COILCNT_OFF ] = usNCoils >> 8; + ucMBFrame[MB_PDU_REQ_READ_COILCNT_OFF + 1] = usNCoils; + vMBMasterSetPDUSndLength( MB_PDU_SIZE_MIN + MB_PDU_REQ_READ_SIZE ); + ( void ) xMBMasterPortEventPost( EV_MASTER_FRAME_TRANSMIT ); + eErrStatus = eMBMasterWaitRequestFinish( ); + + } + return eErrStatus; +} + +eMBException +eMBMasterFuncReadCoils( UCHAR * pucFrame, USHORT * usLen ) +{ + UCHAR *ucMBFrame; + USHORT usRegAddress; + USHORT usCoilCount; + UCHAR ucByteCount; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + /* If this request is broadcast, and it's read mode. This request don't need execute. */ + if ( xMBMasterRequestIsBroadcast() ) + { + eStatus = MB_EX_NONE; + } + else if ( *usLen >= MB_PDU_SIZE_MIN + MB_PDU_FUNC_READ_SIZE_MIN ) + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + usRegAddress = ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF + 1] ); + usRegAddress++; + + usCoilCount = ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_COILCNT_OFF] << 8 ); + usCoilCount |= ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_COILCNT_OFF + 1] ); + + /* Test if the quantity of coils is a multiple of 8. If not last + * byte is only partially field with unused coils set to zero. */ + if( ( usCoilCount & 0x0007 ) != 0 ) + { + ucByteCount = ( UCHAR )( usCoilCount / 8 + 1 ); + } + else + { + ucByteCount = ( UCHAR )( usCoilCount / 8 ); + } + + /* Check if the number of registers to read is valid. If not + * return Modbus illegal data value exception. + */ + if( ( usCoilCount >= 1 ) && + ( ucByteCount == pucFrame[MB_PDU_FUNC_READ_COILCNT_OFF] ) ) + { + /* Make callback to fill the buffer. */ + eRegStatus = eMBMasterRegCoilsCB( &pucFrame[MB_PDU_FUNC_READ_VALUES_OFF], usRegAddress, usCoilCount, MB_REG_READ ); + + /* If an error occurred convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid read coil register request because the length + * is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} +#endif + +#if MB_FUNC_WRITE_COIL_ENABLED > 0 + +/** + * This function will request write one coil. + * + * @param ucSndAddr salve address + * @param usCoilAddr coil start address + * @param usCoilData data to be written + * @param lTimeOut timeout (-1 will waiting forever) + * + * @return error code + * + * @see eMBMasterReqWriteMultipleCoils + */ +eMBMasterReqErrCode +eMBMasterReqWriteCoil( UCHAR ucSndAddr, USHORT usCoilAddr, USHORT usCoilData, LONG lTimeOut ) +{ + UCHAR *ucMBFrame; + eMBMasterReqErrCode eErrStatus = MB_MRE_NO_ERR; + + if ( ucSndAddr > MB_MASTER_TOTAL_SLAVE_NUM ) eErrStatus = MB_MRE_ILL_ARG; + else if ( ( usCoilData != 0xFF00 ) && ( usCoilData != 0x0000 ) ) eErrStatus = MB_MRE_ILL_ARG; + else if ( xMBMasterRunResTake( lTimeOut ) == FALSE ) eErrStatus = MB_MRE_MASTER_BUSY; + else + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + vMBMasterSetDestAddress(ucSndAddr); + ucMBFrame[MB_PDU_FUNC_OFF] = MB_FUNC_WRITE_SINGLE_COIL; + ucMBFrame[MB_PDU_REQ_WRITE_ADDR_OFF] = usCoilAddr >> 8; + ucMBFrame[MB_PDU_REQ_WRITE_ADDR_OFF + 1] = usCoilAddr; + ucMBFrame[MB_PDU_REQ_WRITE_VALUE_OFF ] = usCoilData >> 8; + ucMBFrame[MB_PDU_REQ_WRITE_VALUE_OFF + 1] = usCoilData; + vMBMasterSetPDUSndLength( MB_PDU_SIZE_MIN + MB_PDU_REQ_WRITE_SIZE ); + ( void ) xMBMasterPortEventPost( EV_MASTER_FRAME_TRANSMIT ); + eErrStatus = eMBMasterWaitRequestFinish( ); + } + return eErrStatus; +} + +eMBException +eMBMasterFuncWriteCoil( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + UCHAR ucBuf[2]; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen == ( MB_PDU_FUNC_WRITE_SIZE + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF + 1] ); + usRegAddress++; + + if( ( pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF + 1] == 0x00 ) && + ( ( pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF] == 0xFF ) || + ( pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF] == 0x00 ) ) ) + { + ucBuf[1] = 0; + if( pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF] == 0xFF ) + { + ucBuf[0] = 1; + } + else + { + ucBuf[0] = 0; + } + eRegStatus = + eMBMasterRegCoilsCB( &ucBuf[0], usRegAddress, 1, MB_REG_WRITE ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid write coil register request because the length + * is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#endif // #if MB_FUNC_WRITE_COIL_ENABLED > 0 + +#if MB_FUNC_WRITE_MULTIPLE_COILS_ENABLED > 0 + +/** + * This function will request write multiple coils. + * + * @param ucSndAddr salve address + * @param usCoilAddr coil start address + * @param usNCoils coil total number + * @param usCoilData data to be written + * @param lTimeOut timeout (-1 will waiting forever) + * + * @return error code + * + * @see eMBMasterReqWriteCoil + */ +eMBMasterReqErrCode +eMBMasterReqWriteMultipleCoils( UCHAR ucSndAddr, + USHORT usCoilAddr, USHORT usNCoils, UCHAR * pucDataBuffer, LONG lTimeOut) +{ + UCHAR *ucMBFrame; + USHORT usRegIndex = 0; + UCHAR ucByteCount; + eMBMasterReqErrCode eErrStatus = MB_MRE_NO_ERR; + + if ( ucSndAddr > MB_MASTER_TOTAL_SLAVE_NUM ) eErrStatus = MB_MRE_ILL_ARG; + else if ( usNCoils > MB_PDU_REQ_WRITE_MUL_COILCNT_MAX ) eErrStatus = MB_MRE_ILL_ARG; + else if ( xMBMasterRunResTake( lTimeOut ) == FALSE ) eErrStatus = MB_MRE_MASTER_BUSY; + else + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + vMBMasterSetDestAddress(ucSndAddr); + ucMBFrame[MB_PDU_FUNC_OFF] = MB_FUNC_WRITE_MULTIPLE_COILS; + ucMBFrame[MB_PDU_REQ_WRITE_MUL_ADDR_OFF] = usCoilAddr >> 8; + ucMBFrame[MB_PDU_REQ_WRITE_MUL_ADDR_OFF + 1] = usCoilAddr; + ucMBFrame[MB_PDU_REQ_WRITE_MUL_COILCNT_OFF] = usNCoils >> 8; + ucMBFrame[MB_PDU_REQ_WRITE_MUL_COILCNT_OFF + 1] = usNCoils ; + if( ( usNCoils & 0x0007 ) != 0 ) + { + ucByteCount = ( UCHAR )( usNCoils / 8 + 1 ); + } + else + { + ucByteCount = ( UCHAR )( usNCoils / 8 ); + } + ucMBFrame[MB_PDU_REQ_WRITE_MUL_BYTECNT_OFF] = ucByteCount; + ucMBFrame += MB_PDU_REQ_WRITE_MUL_VALUES_OFF; + while( ucByteCount > usRegIndex) + { + *ucMBFrame++ = pucDataBuffer[usRegIndex++]; + } + vMBMasterSetPDUSndLength( MB_PDU_SIZE_MIN + MB_PDU_REQ_WRITE_MUL_SIZE_MIN + ucByteCount ); + ( void ) xMBMasterPortEventPost( EV_MASTER_FRAME_TRANSMIT ); + eErrStatus = eMBMasterWaitRequestFinish( ); + } + return eErrStatus; +} + +eMBException +eMBMasterFuncWriteMultipleCoils( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + USHORT usCoilCnt; + UCHAR ucByteCount; + UCHAR ucByteCountVerify; + UCHAR *ucMBFrame; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + /* If this request is broadcast, the *usLen is not need check. */ + if( ( *usLen == MB_PDU_FUNC_WRITE_MUL_SIZE ) || xMBMasterRequestIsBroadcast() ) + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF + 1] ); + usRegAddress++; + + usCoilCnt = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_COILCNT_OFF] << 8 ); + usCoilCnt |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_COILCNT_OFF + 1] ); + + ucByteCount = ucMBFrame[MB_PDU_REQ_WRITE_MUL_BYTECNT_OFF]; + + /* Compute the number of expected bytes in the request. */ + if( ( usCoilCnt & 0x0007 ) != 0 ) + { + ucByteCountVerify = ( UCHAR )( usCoilCnt / 8 + 1 ); + } + else + { + ucByteCountVerify = ( UCHAR )( usCoilCnt / 8 ); + } + + if( ( usCoilCnt >= 1 ) && ( ucByteCountVerify == ucByteCount ) ) + { + eRegStatus = + eMBMasterRegCoilsCB( &ucMBFrame[MB_PDU_REQ_WRITE_MUL_VALUES_OFF], + usRegAddress, usCoilCnt, MB_REG_WRITE ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid write coil register request because the length + * is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#endif // #if MB_FUNC_WRITE_MULTIPLE_COILS_ENABLED > 0 +#endif // #if MB_MASTER_RTU_ENABLED > 0 || MB_MASTER_ASCII_ENABLED > 0 diff --git a/components/freemodbus/modbus/functions/mbfuncdiag.c b/components/freemodbus/modbus/functions/mbfuncdiag.c new file mode 100644 index 00000000..d75ffc0f --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfuncdiag.c @@ -0,0 +1,29 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfuncdiag.c,v 1.3 2006/12/07 22:10:34 wolti Exp $ + */ diff --git a/components/freemodbus/modbus/functions/mbfuncdisc.c b/components/freemodbus/modbus/functions/mbfuncdisc.c new file mode 100644 index 00000000..87667ac2 --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfuncdisc.c @@ -0,0 +1,126 @@ + /* + * FreeRTOS Modbus Libary: A Modbus serial implementation for FreeRTOS + * Copyright (C) 2006 Christian Walter + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbconfig.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_PDU_FUNC_READ_ADDR_OFF ( MB_PDU_DATA_OFF ) +#define MB_PDU_FUNC_READ_DISCCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_READ_SIZE ( 4 ) +#define MB_PDU_FUNC_READ_DISCCNT_MAX ( 0x07D0 ) + +/* ----------------------- Static functions ---------------------------------*/ +eMBException prveMBError2Exception( eMBErrorCode eErrorCode ); + +/* ----------------------- Start implementation -----------------------------*/ +#if MB_SLAVE_RTU_ENABLED || MB_SLAVE_ASCII_ENABLED || MB_TCP_ENABLED + +#if MB_FUNC_READ_COILS_ENABLED + +eMBException +eMBFuncReadDiscreteInputs( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + USHORT usDiscreteCnt; + UCHAR ucNBytes; + UCHAR *pucFrameCur; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen == ( MB_PDU_FUNC_READ_SIZE + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF + 1] ); + usRegAddress++; + + usDiscreteCnt = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_DISCCNT_OFF] << 8 ); + usDiscreteCnt |= ( USHORT )( pucFrame[MB_PDU_FUNC_READ_DISCCNT_OFF + 1] ); + + /* Check if the number of registers to read is valid. If not + * return Modbus illegal data value exception. + */ + if( ( usDiscreteCnt >= 1 ) && + ( usDiscreteCnt < MB_PDU_FUNC_READ_DISCCNT_MAX ) ) + { + /* Set the current PDU data pointer to the beginning. */ + pucFrameCur = &pucFrame[MB_PDU_FUNC_OFF]; + *usLen = MB_PDU_FUNC_OFF; + + /* First byte contains the function code. */ + *pucFrameCur++ = MB_FUNC_READ_DISCRETE_INPUTS; + *usLen += 1; + + /* Test if the quantity of coils is a multiple of 8. If not last + * byte is only partially field with unused coils set to zero. */ + if( ( usDiscreteCnt & 0x0007 ) != 0 ) + { + ucNBytes = ( UCHAR ) ( usDiscreteCnt / 8 + 1 ); + } + else + { + ucNBytes = ( UCHAR ) ( usDiscreteCnt / 8 ); + } + *pucFrameCur++ = ucNBytes; + *usLen += 1; + + eRegStatus = + eMBRegDiscreteCB( pucFrameCur, usRegAddress, usDiscreteCnt ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + else + { + /* The response contains the function code, the starting address + * and the quantity of registers. We reuse the old values in the + * buffer because they are still valid. */ + *usLen += ucNBytes;; + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid read coil register request because the length + * is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#endif + +#endif diff --git a/components/freemodbus/modbus/functions/mbfuncdisc_m.c b/components/freemodbus/modbus/functions/mbfuncdisc_m.c new file mode 100644 index 00000000..1a69647d --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfuncdisc_m.c @@ -0,0 +1,162 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (C) 2013 Armink + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfuncdisc_m.c,v 1.60 2013/10/15 8:48:20 Armink Add Master Functions Exp $ + */ + + + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb_m.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbconfig.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_PDU_REQ_READ_ADDR_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_REQ_READ_DISCCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_REQ_READ_SIZE ( 4 ) +#define MB_PDU_FUNC_READ_DISCCNT_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_FUNC_READ_VALUES_OFF ( MB_PDU_DATA_OFF + 1 ) +#define MB_PDU_FUNC_READ_SIZE_MIN ( 1 ) + +/* ----------------------- Static functions ---------------------------------*/ +eMBException prveMBError2Exception( eMBErrorCode eErrorCode ); + +/* ----------------------- Start implementation -----------------------------*/ +#if MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED + +#if MB_FUNC_READ_DISCRETE_INPUTS_ENABLED + +/** + * This function will request read discrete inputs. + * + * @param ucSndAddr salve address + * @param usDiscreteAddr discrete start address + * @param usNDiscreteIn discrete total number + * @param lTimeOut timeout (-1 will waiting forever) + * + * @return error code + */ +eMBMasterReqErrCode +eMBMasterReqReadDiscreteInputs( UCHAR ucSndAddr, USHORT usDiscreteAddr, USHORT usNDiscreteIn, LONG lTimeOut ) +{ + UCHAR *ucMBFrame; + eMBMasterReqErrCode eErrStatus = MB_MRE_NO_ERR; + + if ( ucSndAddr > MB_MASTER_TOTAL_SLAVE_NUM ) eErrStatus = MB_MRE_ILL_ARG; + else if ( xMBMasterRunResTake( lTimeOut ) == FALSE ) eErrStatus = MB_MRE_MASTER_BUSY; + else + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + vMBMasterSetDestAddress(ucSndAddr); + ucMBFrame[MB_PDU_FUNC_OFF] = MB_FUNC_READ_DISCRETE_INPUTS; + ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF] = usDiscreteAddr >> 8; + ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF + 1] = usDiscreteAddr; + ucMBFrame[MB_PDU_REQ_READ_DISCCNT_OFF ] = usNDiscreteIn >> 8; + ucMBFrame[MB_PDU_REQ_READ_DISCCNT_OFF + 1] = usNDiscreteIn; + vMBMasterSetPDUSndLength( MB_PDU_SIZE_MIN + MB_PDU_REQ_READ_SIZE ); + ( void ) xMBMasterPortEventPost( EV_MASTER_FRAME_TRANSMIT ); + eErrStatus = eMBMasterWaitRequestFinish( ); + } + return eErrStatus; +} + +eMBException +eMBMasterFuncReadDiscreteInputs( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + USHORT usDiscreteCnt; + UCHAR ucNBytes; + UCHAR *ucMBFrame; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + /* If this request is broadcast, and it's read mode. This request don't need execute. */ + if ( xMBMasterRequestIsBroadcast() ) + { + eStatus = MB_EX_NONE; + } + else if( *usLen >= MB_PDU_SIZE_MIN + MB_PDU_FUNC_READ_SIZE_MIN ) + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + usRegAddress = ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF + 1] ); + usRegAddress++; + + usDiscreteCnt = ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_DISCCNT_OFF] << 8 ); + usDiscreteCnt |= ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_DISCCNT_OFF + 1] ); + + /* Test if the quantity of coils is a multiple of 8. If not last + * byte is only partially field with unused coils set to zero. */ + if( ( usDiscreteCnt & 0x0007 ) != 0 ) + { + ucNBytes = ( UCHAR )( usDiscreteCnt / 8 + 1 ); + } + else + { + ucNBytes = ( UCHAR )( usDiscreteCnt / 8 ); + } + + /* Check if the number of registers to read is valid. If not + * return Modbus illegal data value exception. + */ + if ((usDiscreteCnt >= 1) && ucNBytes == pucFrame[MB_PDU_FUNC_READ_DISCCNT_OFF]) + { + /* Make callback to fill the buffer. */ + eRegStatus = eMBMasterRegDiscreteCB( &pucFrame[MB_PDU_FUNC_READ_VALUES_OFF], usRegAddress, usDiscreteCnt ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid read coil register request because the length + * is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#endif +#endif // #if MB_SERIAL_MASTER_RTU_ENABLED || MB_SERIAL_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED diff --git a/components/freemodbus/modbus/functions/mbfuncholding.c b/components/freemodbus/modbus/functions/mbfuncholding.c new file mode 100644 index 00000000..1a37866c --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfuncholding.c @@ -0,0 +1,311 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfuncholding.c,v 1.12 2007/02/18 23:48:22 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbconfig.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_PDU_FUNC_READ_ADDR_OFF ( MB_PDU_DATA_OFF + 0) +#define MB_PDU_FUNC_READ_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_READ_SIZE ( 4 ) +#define MB_PDU_FUNC_READ_REGCNT_MAX ( 0x007D ) + +#define MB_PDU_FUNC_WRITE_ADDR_OFF ( MB_PDU_DATA_OFF + 0) +#define MB_PDU_FUNC_WRITE_VALUE_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_WRITE_SIZE ( 4 ) + +#define MB_PDU_FUNC_WRITE_MUL_ADDR_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_FUNC_WRITE_MUL_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF ( MB_PDU_DATA_OFF + 4 ) +#define MB_PDU_FUNC_WRITE_MUL_VALUES_OFF ( MB_PDU_DATA_OFF + 5 ) +#define MB_PDU_FUNC_WRITE_MUL_SIZE_MIN ( 5 ) +#define MB_PDU_FUNC_WRITE_MUL_REGCNT_MAX ( 0x0078 ) + +#define MB_PDU_FUNC_READWRITE_READ_ADDR_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_FUNC_READWRITE_READ_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_READWRITE_WRITE_ADDR_OFF ( MB_PDU_DATA_OFF + 4 ) +#define MB_PDU_FUNC_READWRITE_WRITE_REGCNT_OFF ( MB_PDU_DATA_OFF + 6 ) +#define MB_PDU_FUNC_READWRITE_BYTECNT_OFF ( MB_PDU_DATA_OFF + 8 ) +#define MB_PDU_FUNC_READWRITE_WRITE_VALUES_OFF ( MB_PDU_DATA_OFF + 9 ) +#define MB_PDU_FUNC_READWRITE_SIZE_MIN ( 9 ) + +/* ----------------------- Static functions ---------------------------------*/ +eMBException prveMBError2Exception( eMBErrorCode eErrorCode ); + +/* ----------------------- Start implementation -----------------------------*/ +#if MB_SLAVE_RTU_ENABLED || MB_SLAVE_ASCII_ENABLED || MB_TCP_ENABLED + +#if MB_FUNC_WRITE_HOLDING_ENABLED + +eMBException +eMBFuncWriteHoldingRegister( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen == ( MB_PDU_FUNC_WRITE_SIZE + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF + 1] ); + usRegAddress++; + + /* Make callback to update the value. */ + eRegStatus = eMBRegHoldingCB( &pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF], + usRegAddress, 1, MB_REG_WRITE ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + } + else + { + /* Can't be a valid request because the length is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} +#endif + +#if MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED > 0 +eMBException +eMBFuncWriteMultipleHoldingRegister( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + USHORT usRegCount; + UCHAR ucRegByteCount; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen >= ( MB_PDU_FUNC_WRITE_MUL_SIZE_MIN + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_ADDR_OFF + 1] ); + usRegAddress++; + + usRegCount = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_REGCNT_OFF] << 8 ); + usRegCount |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_MUL_REGCNT_OFF + 1] ); + + ucRegByteCount = pucFrame[MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF]; + + if( ( usRegCount >= 1 ) && + ( usRegCount <= MB_PDU_FUNC_WRITE_MUL_REGCNT_MAX ) && + ( ucRegByteCount == ( UCHAR ) ( 2 * usRegCount ) ) ) + { + /* Make callback to update the register values. */ + eRegStatus = + eMBRegHoldingCB( &pucFrame[MB_PDU_FUNC_WRITE_MUL_VALUES_OFF], + usRegAddress, usRegCount, MB_REG_WRITE ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + else + { + /* The response contains the function code, the starting + * address and the quantity of registers. We reuse the + * old values in the buffer because they are still valid. + */ + *usLen = MB_PDU_FUNC_WRITE_MUL_BYTECNT_OFF; + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid request because the length is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} +#endif + +#if MB_FUNC_READ_HOLDING_ENABLED > 0 + +eMBException +eMBFuncReadHoldingRegister( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + USHORT usRegCount; + UCHAR *pucFrameCur; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen == ( MB_PDU_FUNC_READ_SIZE + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF + 1] ); + usRegAddress++; + + usRegCount = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_REGCNT_OFF] << 8 ); + usRegCount = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_REGCNT_OFF + 1] ); + + /* Check if the number of registers to read is valid. If not + * return Modbus illegal data value exception. + */ + if( ( usRegCount >= 1 ) && ( usRegCount <= MB_PDU_FUNC_READ_REGCNT_MAX ) ) + { + /* Set the current PDU data pointer to the beginning. */ + pucFrameCur = &pucFrame[MB_PDU_FUNC_OFF]; + *usLen = MB_PDU_FUNC_OFF; + + /* First byte contains the function code. */ + *pucFrameCur++ = MB_FUNC_READ_HOLDING_REGISTER; + *usLen += 1; + + /* Second byte in the response contain the number of bytes. */ + *pucFrameCur++ = ( UCHAR ) ( usRegCount * 2 ); + *usLen += 1; + + /* Make callback to fill the buffer. */ + eRegStatus = eMBRegHoldingCB( pucFrameCur, usRegAddress, usRegCount, MB_REG_READ ); + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + else + { + *usLen += usRegCount * 2; + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid request because the length is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#endif + +#if MB_FUNC_READWRITE_HOLDING_ENABLED > 0 + +eMBException +eMBFuncReadWriteMultipleHoldingRegister( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegReadAddress; + USHORT usRegReadCount; + USHORT usRegWriteAddress; + USHORT usRegWriteCount; + UCHAR ucRegWriteByteCount; + UCHAR *pucFrameCur; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen >= ( MB_PDU_FUNC_READWRITE_SIZE_MIN + MB_PDU_SIZE_MIN ) ) + { + usRegReadAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_READ_ADDR_OFF] << 8U ); + usRegReadAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_READ_ADDR_OFF + 1] ); + usRegReadAddress++; + + usRegReadCount = ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_READ_REGCNT_OFF] << 8U ); + usRegReadCount |= ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_READ_REGCNT_OFF + 1] ); + + usRegWriteAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_WRITE_ADDR_OFF] << 8U ); + usRegWriteAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_WRITE_ADDR_OFF + 1] ); + usRegWriteAddress++; + + usRegWriteCount = ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_WRITE_REGCNT_OFF] << 8U ); + usRegWriteCount |= ( USHORT )( pucFrame[MB_PDU_FUNC_READWRITE_WRITE_REGCNT_OFF + 1] ); + + ucRegWriteByteCount = pucFrame[MB_PDU_FUNC_READWRITE_BYTECNT_OFF]; + + if( ( usRegReadCount >= 1 ) && ( usRegReadCount <= 0x7D ) && + ( usRegWriteCount >= 1 ) && ( usRegWriteCount <= 0x79 ) && + ( ( 2 * usRegWriteCount ) == ucRegWriteByteCount ) ) + { + /* Make callback to update the register values. */ + eRegStatus = eMBRegHoldingCB( &pucFrame[MB_PDU_FUNC_READWRITE_WRITE_VALUES_OFF], + usRegWriteAddress, usRegWriteCount, MB_REG_WRITE ); + + if( eRegStatus == MB_ENOERR ) + { + /* Set the current PDU data pointer to the beginning. */ + pucFrameCur = &pucFrame[MB_PDU_FUNC_OFF]; + *usLen = MB_PDU_FUNC_OFF; + + /* First byte contains the function code. */ + *pucFrameCur++ = MB_FUNC_READWRITE_MULTIPLE_REGISTERS; + *usLen += 1; + + /* Second byte in the response contain the number of bytes. */ + *pucFrameCur++ = ( UCHAR ) ( usRegReadCount * 2 ); + *usLen += 1; + + /* Make the read callback. */ + eRegStatus = + eMBRegHoldingCB( pucFrameCur, usRegReadAddress, usRegReadCount, MB_REG_READ ); + if( eRegStatus == MB_ENOERR ) + { + *usLen += 2 * usRegReadCount; + } + } + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + return eStatus; +} + +#endif + +#endif diff --git a/components/freemodbus/modbus/functions/mbfuncholding_m.c b/components/freemodbus/modbus/functions/mbfuncholding_m.c new file mode 100644 index 00000000..9b4c0771 --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfuncholding_m.c @@ -0,0 +1,455 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (C) 2013 Armink + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfuncholding_m.c,v 1.60 2013/09/02 14:13:40 Armink Add Master Functions Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +//#include "mb.h" +#include "mb_m.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbconfig.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_PDU_REQ_READ_ADDR_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_REQ_READ_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_REQ_READ_SIZE ( 4 ) +#define MB_PDU_FUNC_READ_REGCNT_MAX ( 0x007D ) +#define MB_PDU_FUNC_READ_BYTECNT_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_FUNC_READ_VALUES_OFF ( MB_PDU_DATA_OFF + 1 ) +#define MB_PDU_FUNC_READ_SIZE_MIN ( 1 ) + +#define MB_PDU_REQ_WRITE_ADDR_OFF ( MB_PDU_DATA_OFF + 0) +#define MB_PDU_REQ_WRITE_VALUE_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_REQ_WRITE_SIZE ( 4 ) +#define MB_PDU_FUNC_WRITE_ADDR_OFF ( MB_PDU_DATA_OFF + 0) +#define MB_PDU_FUNC_WRITE_VALUE_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_WRITE_SIZE ( 4 ) + +#define MB_PDU_REQ_WRITE_MUL_ADDR_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_REQ_WRITE_MUL_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_REQ_WRITE_MUL_BYTECNT_OFF ( MB_PDU_DATA_OFF + 4 ) +#define MB_PDU_REQ_WRITE_MUL_VALUES_OFF ( MB_PDU_DATA_OFF + 5 ) +#define MB_PDU_REQ_WRITE_MUL_SIZE_MIN ( 5 ) +#define MB_PDU_REQ_WRITE_MUL_REGCNT_MAX ( 0x0078 ) +#define MB_PDU_FUNC_WRITE_MUL_ADDR_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_FUNC_WRITE_MUL_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_WRITE_MUL_SIZE ( 4 ) + +#define MB_PDU_REQ_READWRITE_READ_ADDR_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_REQ_READWRITE_READ_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_REQ_READWRITE_WRITE_ADDR_OFF ( MB_PDU_DATA_OFF + 4 ) +#define MB_PDU_REQ_READWRITE_WRITE_REGCNT_OFF ( MB_PDU_DATA_OFF + 6 ) +#define MB_PDU_REQ_READWRITE_WRITE_BYTECNT_OFF ( MB_PDU_DATA_OFF + 8 ) +#define MB_PDU_REQ_READWRITE_WRITE_VALUES_OFF ( MB_PDU_DATA_OFF + 9 ) +#define MB_PDU_REQ_READWRITE_SIZE_MIN ( 9 ) +#define MB_PDU_FUNC_READWRITE_READ_BYTECNT_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_FUNC_READWRITE_READ_VALUES_OFF ( MB_PDU_DATA_OFF + 1 ) +#define MB_PDU_FUNC_READWRITE_SIZE_MIN ( 1 ) + +/* ----------------------- Static functions ---------------------------------*/ +eMBException prveMBError2Exception( eMBErrorCode eErrorCode ); + +/* ----------------------- Start implementation -----------------------------*/ +#if MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED + +#if MB_FUNC_WRITE_HOLDING_ENABLED + +/** + * This function will request write holding register. + * + * @param ucSndAddr salve address + * @param usRegAddr register start address + * @param usRegData register data to be written + * @param lTimeOut timeout (-1 will waiting forever) + * + * @return error code + */ +eMBMasterReqErrCode +eMBMasterReqWriteHoldingRegister( UCHAR ucSndAddr, USHORT usRegAddr, USHORT usRegData, LONG lTimeOut ) +{ + UCHAR *ucMBFrame; + eMBMasterReqErrCode eErrStatus = MB_MRE_NO_ERR; + + if ( ucSndAddr > MB_MASTER_TOTAL_SLAVE_NUM ) eErrStatus = MB_MRE_ILL_ARG; + else if ( xMBMasterRunResTake( lTimeOut ) == FALSE ) eErrStatus = MB_MRE_MASTER_BUSY; + else + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + vMBMasterSetDestAddress(ucSndAddr); + ucMBFrame[MB_PDU_FUNC_OFF] = MB_FUNC_WRITE_REGISTER; + ucMBFrame[MB_PDU_REQ_WRITE_ADDR_OFF] = usRegAddr >> 8; + ucMBFrame[MB_PDU_REQ_WRITE_ADDR_OFF + 1] = usRegAddr; + ucMBFrame[MB_PDU_REQ_WRITE_VALUE_OFF] = usRegData >> 8; + ucMBFrame[MB_PDU_REQ_WRITE_VALUE_OFF + 1] = usRegData ; + vMBMasterSetPDUSndLength( MB_PDU_SIZE_MIN + MB_PDU_REQ_WRITE_SIZE ); + ( void ) xMBMasterPortEventPost( EV_MASTER_FRAME_TRANSMIT ); + eErrStatus = eMBMasterWaitRequestFinish( ); + } + return eErrStatus; +} + +eMBException +eMBMasterFuncWriteHoldingRegister( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen == ( MB_PDU_SIZE_MIN + MB_PDU_FUNC_WRITE_SIZE ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_WRITE_ADDR_OFF + 1] ); + usRegAddress++; + + /* Make callback to update the value. */ + eRegStatus = eMBMasterRegHoldingCB( &pucFrame[MB_PDU_FUNC_WRITE_VALUE_OFF], + usRegAddress, 1, MB_REG_WRITE ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + } + else + { + /* Can't be a valid request because the length is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} +#endif + +#if MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED > 0 + +/** + * This function will request write multiple holding register. + * + * @param ucSndAddr salve address + * @param usRegAddr register start address + * @param usNRegs register total number + * @param pusDataBuffer data to be written + * @param lTimeOut timeout (-1 will waiting forever) + * + * @return error code + */ +eMBMasterReqErrCode +eMBMasterReqWriteMultipleHoldingRegister( UCHAR ucSndAddr, + USHORT usRegAddr, USHORT usNRegs, USHORT * pusDataBuffer, LONG lTimeOut ) +{ + UCHAR *ucMBFrame; + USHORT usRegIndex = 0; + eMBMasterReqErrCode eErrStatus = MB_MRE_NO_ERR; + + if ( ucSndAddr > MB_MASTER_TOTAL_SLAVE_NUM ) eErrStatus = MB_MRE_ILL_ARG; + else if ( xMBMasterRunResTake( lTimeOut ) == FALSE ) eErrStatus = MB_MRE_MASTER_BUSY; + else + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + vMBMasterSetDestAddress(ucSndAddr); + ucMBFrame[MB_PDU_FUNC_OFF] = MB_FUNC_WRITE_MULTIPLE_REGISTERS; + ucMBFrame[MB_PDU_REQ_WRITE_MUL_ADDR_OFF] = usRegAddr >> 8; + ucMBFrame[MB_PDU_REQ_WRITE_MUL_ADDR_OFF + 1] = usRegAddr; + ucMBFrame[MB_PDU_REQ_WRITE_MUL_REGCNT_OFF] = usNRegs >> 8; + ucMBFrame[MB_PDU_REQ_WRITE_MUL_REGCNT_OFF + 1] = usNRegs ; + ucMBFrame[MB_PDU_REQ_WRITE_MUL_BYTECNT_OFF] = usNRegs * 2; + ucMBFrame += MB_PDU_REQ_WRITE_MUL_VALUES_OFF; + while( usNRegs > usRegIndex) + { + *ucMBFrame++ = pusDataBuffer[usRegIndex] >> 8; + *ucMBFrame++ = pusDataBuffer[usRegIndex++] ; + } + vMBMasterSetPDUSndLength( MB_PDU_SIZE_MIN + MB_PDU_REQ_WRITE_MUL_SIZE_MIN + 2*usNRegs ); + ( void ) xMBMasterPortEventPost( EV_MASTER_FRAME_TRANSMIT ); + eErrStatus = eMBMasterWaitRequestFinish( ); + } + return eErrStatus; +} + +eMBException +eMBMasterFuncWriteMultipleHoldingRegister( UCHAR * pucFrame, USHORT * usLen ) +{ + UCHAR *ucMBFrame; + USHORT usRegAddress; + USHORT usRegCount; + UCHAR ucRegByteCount; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + /* If this request is broadcast, the *usLen is not need check. */ + if( ( *usLen == MB_PDU_SIZE_MIN + MB_PDU_FUNC_WRITE_MUL_SIZE ) || xMBMasterRequestIsBroadcast() ) + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + usRegAddress = ( USHORT )( ucMBFrame[MB_PDU_REQ_WRITE_MUL_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( ucMBFrame[MB_PDU_REQ_WRITE_MUL_ADDR_OFF + 1] ); + usRegAddress++; + + usRegCount = ( USHORT )( ucMBFrame[MB_PDU_REQ_WRITE_MUL_REGCNT_OFF] << 8 ); + usRegCount |= ( USHORT )( ucMBFrame[MB_PDU_REQ_WRITE_MUL_REGCNT_OFF + 1] ); + + ucRegByteCount = ucMBFrame[MB_PDU_REQ_WRITE_MUL_BYTECNT_OFF]; + + if( ucRegByteCount == 2 * usRegCount ) + { + /* Make callback to update the register values. */ + eRegStatus = eMBMasterRegHoldingCB( &ucMBFrame[MB_PDU_REQ_WRITE_MUL_VALUES_OFF], + usRegAddress, usRegCount, MB_REG_WRITE ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid request because the length is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} +#endif + +#if MB_FUNC_READ_HOLDING_ENABLED > 0 + +/** + * This function will request read holding register. + * + * @param ucSndAddr salve address + * @param usRegAddr register start address + * @param usNRegs register total number + * @param lTimeOut timeout (-1 will waiting forever) + * + * @return error code + */ +eMBMasterReqErrCode +eMBMasterReqReadHoldingRegister( UCHAR ucSndAddr, USHORT usRegAddr, USHORT usNRegs, LONG lTimeOut ) +{ + UCHAR *ucMBFrame; + eMBMasterReqErrCode eErrStatus = MB_MRE_NO_ERR; + + if ( ucSndAddr > MB_MASTER_TOTAL_SLAVE_NUM ) eErrStatus = MB_MRE_ILL_ARG; + else if ( xMBMasterRunResTake( lTimeOut ) == FALSE ) eErrStatus = MB_MRE_MASTER_BUSY; + else + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + vMBMasterSetDestAddress(ucSndAddr); + ucMBFrame[MB_PDU_FUNC_OFF] = MB_FUNC_READ_HOLDING_REGISTER; + ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF] = usRegAddr >> 8; + ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF + 1] = usRegAddr; + ucMBFrame[MB_PDU_REQ_READ_REGCNT_OFF] = usNRegs >> 8; + ucMBFrame[MB_PDU_REQ_READ_REGCNT_OFF + 1] = usNRegs; + vMBMasterSetPDUSndLength( MB_PDU_SIZE_MIN + MB_PDU_REQ_READ_SIZE ); + ( void ) xMBMasterPortEventPost( EV_MASTER_FRAME_TRANSMIT ); + eErrStatus = eMBMasterWaitRequestFinish( ); + } + return eErrStatus; +} + +eMBException +eMBMasterFuncReadHoldingRegister( UCHAR * pucFrame, USHORT * usLen ) +{ + UCHAR *ucMBFrame; + USHORT usRegAddress; + USHORT usRegCount; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + /* If this request is broadcast, and it's read mode. This request don't need execute. */ + if ( xMBMasterRequestIsBroadcast() ) + { + eStatus = MB_EX_NONE; + } + else if( *usLen >= MB_PDU_SIZE_MIN + MB_PDU_FUNC_READ_SIZE_MIN ) + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + usRegAddress = ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF + 1] ); + usRegAddress++; + + usRegCount = ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_REGCNT_OFF] << 8 ); + usRegCount |= ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_REGCNT_OFF + 1] ); + + /* Check if the number of registers to read is valid. If not + * return Modbus illegal data value exception. + */ + if( ( usRegCount >= 1 ) && ( 2 * usRegCount == pucFrame[MB_PDU_FUNC_READ_BYTECNT_OFF] ) ) + { + /* Make callback to fill the buffer. */ + eRegStatus = eMBMasterRegHoldingCB( &pucFrame[MB_PDU_FUNC_READ_VALUES_OFF], usRegAddress, usRegCount, MB_REG_READ ); + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid request because the length is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#endif + +#if MB_FUNC_READWRITE_HOLDING_ENABLED > 0 + +/** + * This function will request read and write holding register. + * + * @param ucSndAddr salve address + * @param usReadRegAddr read register start address + * @param usNReadRegs read register total number + * @param pusDataBuffer data to be written + * @param usWriteRegAddr write register start address + * @param usNWriteRegs write register total number + * @param lTimeOut timeout (-1 will waiting forever) + * + * @return error code + */ +eMBMasterReqErrCode +eMBMasterReqReadWriteMultipleHoldingRegister( UCHAR ucSndAddr, + USHORT usReadRegAddr, USHORT usNReadRegs, USHORT * pusDataBuffer, + USHORT usWriteRegAddr, USHORT usNWriteRegs, LONG lTimeOut ) +{ + UCHAR *ucMBFrame; + USHORT usRegIndex = 0; + eMBMasterReqErrCode eErrStatus = MB_MRE_NO_ERR; + + if ( ucSndAddr > MB_MASTER_TOTAL_SLAVE_NUM ) eErrStatus = MB_MRE_ILL_ARG; + else if ( xMBMasterRunResTake( lTimeOut ) == FALSE ) eErrStatus = MB_MRE_MASTER_BUSY; + else + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + vMBMasterSetDestAddress(ucSndAddr); + ucMBFrame[MB_PDU_FUNC_OFF] = MB_FUNC_READWRITE_MULTIPLE_REGISTERS; + ucMBFrame[MB_PDU_REQ_READWRITE_READ_ADDR_OFF] = usReadRegAddr >> 8; + ucMBFrame[MB_PDU_REQ_READWRITE_READ_ADDR_OFF + 1] = usReadRegAddr; + ucMBFrame[MB_PDU_REQ_READWRITE_READ_REGCNT_OFF] = usNReadRegs >> 8; + ucMBFrame[MB_PDU_REQ_READWRITE_READ_REGCNT_OFF + 1] = usNReadRegs ; + ucMBFrame[MB_PDU_REQ_READWRITE_WRITE_ADDR_OFF] = usWriteRegAddr >> 8; + ucMBFrame[MB_PDU_REQ_READWRITE_WRITE_ADDR_OFF + 1] = usWriteRegAddr; + ucMBFrame[MB_PDU_REQ_READWRITE_WRITE_REGCNT_OFF] = usNWriteRegs >> 8; + ucMBFrame[MB_PDU_REQ_READWRITE_WRITE_REGCNT_OFF + 1] = usNWriteRegs ; + ucMBFrame[MB_PDU_REQ_READWRITE_WRITE_BYTECNT_OFF] = usNWriteRegs * 2; + ucMBFrame += MB_PDU_REQ_READWRITE_WRITE_VALUES_OFF; + while( usNWriteRegs > usRegIndex) + { + *ucMBFrame++ = pusDataBuffer[usRegIndex] >> 8; + *ucMBFrame++ = pusDataBuffer[usRegIndex++] ; + } + vMBMasterSetPDUSndLength( MB_PDU_SIZE_MIN + MB_PDU_REQ_READWRITE_SIZE_MIN + 2*usNWriteRegs ); + ( void ) xMBMasterPortEventPost( EV_MASTER_FRAME_TRANSMIT ); + eErrStatus = eMBMasterWaitRequestFinish( ); + } + return eErrStatus; +} + +eMBException +eMBMasterFuncReadWriteMultipleHoldingRegister( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegReadAddress; + USHORT usRegReadCount; + USHORT usRegWriteAddress; + USHORT usRegWriteCount; + UCHAR *ucMBFrame; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + /* If this request is broadcast, and it's read mode. This request don't need execute. */ + if ( xMBMasterRequestIsBroadcast() ) + { + eStatus = MB_EX_NONE; + } + else if( *usLen >= MB_PDU_SIZE_MIN + MB_PDU_FUNC_READWRITE_SIZE_MIN ) + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + usRegReadAddress = ( USHORT )( ucMBFrame[MB_PDU_REQ_READWRITE_READ_ADDR_OFF] << 8U ); + usRegReadAddress |= ( USHORT )( ucMBFrame[MB_PDU_REQ_READWRITE_READ_ADDR_OFF + 1] ); + usRegReadAddress++; + + usRegReadCount = ( USHORT )( ucMBFrame[MB_PDU_REQ_READWRITE_READ_REGCNT_OFF] << 8U ); + usRegReadCount |= ( USHORT )( ucMBFrame[MB_PDU_REQ_READWRITE_READ_REGCNT_OFF + 1] ); + + usRegWriteAddress = ( USHORT )( ucMBFrame[MB_PDU_REQ_READWRITE_WRITE_ADDR_OFF] << 8U ); + usRegWriteAddress |= ( USHORT )( ucMBFrame[MB_PDU_REQ_READWRITE_WRITE_ADDR_OFF + 1] ); + usRegWriteAddress++; + + usRegWriteCount = ( USHORT )( ucMBFrame[MB_PDU_REQ_READWRITE_WRITE_REGCNT_OFF] << 8U ); + usRegWriteCount |= ( USHORT )( ucMBFrame[MB_PDU_REQ_READWRITE_WRITE_REGCNT_OFF + 1] ); + + if( ( 2 * usRegReadCount ) == pucFrame[MB_PDU_FUNC_READWRITE_READ_BYTECNT_OFF] ) + { + /* Make callback to update the register values. */ + eRegStatus = eMBMasterRegHoldingCB( &ucMBFrame[MB_PDU_REQ_READWRITE_WRITE_VALUES_OFF], + usRegWriteAddress, usRegWriteCount, MB_REG_WRITE ); + + if( eRegStatus == MB_ENOERR ) + { + /* Make the read callback. */ + eRegStatus = eMBMasterRegHoldingCB(&pucFrame[MB_PDU_FUNC_READWRITE_READ_VALUES_OFF], + usRegReadAddress, usRegReadCount, MB_REG_READ); + } + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + return eStatus; +} + +#endif +#endif // #if MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED + diff --git a/components/freemodbus/modbus/functions/mbfuncinput.c b/components/freemodbus/modbus/functions/mbfuncinput.c new file mode 100644 index 00000000..97aeac4d --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfuncinput.c @@ -0,0 +1,126 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfuncinput.c,v 1.10 2007/09/12 10:15:56 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbconfig.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_PDU_FUNC_READ_ADDR_OFF ( MB_PDU_DATA_OFF ) +#define MB_PDU_FUNC_READ_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_FUNC_READ_SIZE ( 4 ) +#define MB_PDU_FUNC_READ_REGCNT_MAX ( 0x007D ) + +#define MB_PDU_FUNC_READ_RSP_BYTECNT_OFF ( MB_PDU_DATA_OFF ) + +/* ----------------------- Static functions ---------------------------------*/ +eMBException prveMBError2Exception( eMBErrorCode eErrorCode ); + +/* ----------------------- Start implementation -----------------------------*/ +#if MB_SLAVE_RTU_ENABLED || MB_SLAVE_ASCII_ENABLED || MB_TCP_ENABLED + +#if MB_FUNC_READ_INPUT_ENABLED + +eMBException +eMBFuncReadInputRegister( UCHAR * pucFrame, USHORT * usLen ) +{ + USHORT usRegAddress; + USHORT usRegCount; + UCHAR *pucFrameCur; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + if( *usLen == ( MB_PDU_FUNC_READ_SIZE + MB_PDU_SIZE_MIN ) ) + { + usRegAddress = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( pucFrame[MB_PDU_FUNC_READ_ADDR_OFF + 1] ); + usRegAddress++; + + usRegCount = ( USHORT )( pucFrame[MB_PDU_FUNC_READ_REGCNT_OFF] << 8 ); + usRegCount |= ( USHORT )( pucFrame[MB_PDU_FUNC_READ_REGCNT_OFF + 1] ); + + /* Check if the number of registers to read is valid. If not + * return Modbus illegal data value exception. + */ + if( ( usRegCount >= 1 ) + && ( usRegCount < MB_PDU_FUNC_READ_REGCNT_MAX ) ) + { + /* Set the current PDU data pointer to the beginning. */ + pucFrameCur = &pucFrame[MB_PDU_FUNC_OFF]; + *usLen = MB_PDU_FUNC_OFF; + + /* First byte contains the function code. */ + *pucFrameCur++ = MB_FUNC_READ_INPUT_REGISTER; + *usLen += 1; + + /* Second byte in the response contain the number of bytes. */ + *pucFrameCur++ = ( UCHAR )( usRegCount * 2 ); + *usLen += 1; + + eRegStatus = + eMBRegInputCB( pucFrameCur, usRegAddress, usRegCount ); + + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + else + { + *usLen += usRegCount * 2; + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid read input register request because the length + * is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#endif + +#endif diff --git a/components/freemodbus/modbus/functions/mbfuncinput_m.c b/components/freemodbus/modbus/functions/mbfuncinput_m.c new file mode 100644 index 00000000..3a686955 --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfuncinput_m.c @@ -0,0 +1,147 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (C) 2013 Armink + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfuncinput_m.c,v 1.60 2013/10/12 14:23:40 Armink Add Master Functions Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb_m.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbconfig.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_PDU_REQ_READ_ADDR_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_REQ_READ_REGCNT_OFF ( MB_PDU_DATA_OFF + 2 ) +#define MB_PDU_REQ_READ_SIZE ( 4 ) +#define MB_PDU_FUNC_READ_BYTECNT_OFF ( MB_PDU_DATA_OFF + 0 ) +#define MB_PDU_FUNC_READ_VALUES_OFF ( MB_PDU_DATA_OFF + 1 ) +#define MB_PDU_FUNC_READ_SIZE_MIN ( 1 ) + +#define MB_PDU_FUNC_READ_RSP_BYTECNT_OFF ( MB_PDU_DATA_OFF ) + +/* ----------------------- Static functions ---------------------------------*/ +eMBException prveMBError2Exception( eMBErrorCode eErrorCode ); + +/* ----------------------- Start implementation -----------------------------*/ +#if MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED +#if MB_FUNC_READ_INPUT_ENABLED + +/** + * This function will request read input register. + * + * @param ucSndAddr salve address + * @param usRegAddr register start address + * @param usNRegs register total number + * @param lTimeOut timeout (-1 will waiting forever) + * + * @return error code + */ +eMBMasterReqErrCode +eMBMasterReqReadInputRegister( UCHAR ucSndAddr, USHORT usRegAddr, USHORT usNRegs, LONG lTimeOut ) +{ + UCHAR *ucMBFrame; + eMBMasterReqErrCode eErrStatus = MB_MRE_NO_ERR; + + if ( ucSndAddr > MB_MASTER_TOTAL_SLAVE_NUM ) eErrStatus = MB_MRE_ILL_ARG; + else if ( xMBMasterRunResTake( lTimeOut ) == FALSE ) eErrStatus = MB_MRE_MASTER_BUSY; + else + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + vMBMasterSetDestAddress(ucSndAddr); + ucMBFrame[MB_PDU_FUNC_OFF] = MB_FUNC_READ_INPUT_REGISTER; + ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF] = usRegAddr >> 8; + ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF + 1] = usRegAddr; + ucMBFrame[MB_PDU_REQ_READ_REGCNT_OFF] = usNRegs >> 8; + ucMBFrame[MB_PDU_REQ_READ_REGCNT_OFF + 1] = usNRegs; + vMBMasterSetPDUSndLength( MB_PDU_SIZE_MIN + MB_PDU_REQ_READ_SIZE ); + ( void ) xMBMasterPortEventPost( EV_MASTER_FRAME_TRANSMIT ); + eErrStatus = eMBMasterWaitRequestFinish( ); + } + return eErrStatus; +} + +eMBException +eMBMasterFuncReadInputRegister( UCHAR * pucFrame, USHORT * usLen ) +{ + UCHAR *ucMBFrame; + USHORT usRegAddress; + USHORT usRegCount; + + eMBException eStatus = MB_EX_NONE; + eMBErrorCode eRegStatus; + + /* If this request is broadcast, and it's read mode. This request don't need execute. */ + if ( xMBMasterRequestIsBroadcast() ) + { + eStatus = MB_EX_NONE; + } + else if( *usLen >= MB_PDU_SIZE_MIN + MB_PDU_FUNC_READ_SIZE_MIN ) + { + vMBMasterGetPDUSndBuf(&ucMBFrame); + usRegAddress = ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF] << 8 ); + usRegAddress |= ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_ADDR_OFF + 1] ); + usRegAddress++; + + usRegCount = ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_REGCNT_OFF] << 8 ); + usRegCount |= ( USHORT )( ucMBFrame[MB_PDU_REQ_READ_REGCNT_OFF + 1] ); + + /* Check if the number of registers to read is valid. If not + * return Modbus illegal data value exception. + */ + if( ( usRegCount >= 1 ) && ( 2 * usRegCount == pucFrame[MB_PDU_FUNC_READ_BYTECNT_OFF] ) ) + { + /* Make callback to fill the buffer. */ + eRegStatus = eMBMasterRegInputCB( &pucFrame[MB_PDU_FUNC_READ_VALUES_OFF], usRegAddress, usRegCount ); + /* If an error occured convert it into a Modbus exception. */ + if( eRegStatus != MB_ENOERR ) + { + eStatus = prveMBError2Exception( eRegStatus ); + } + } + else + { + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + } + else + { + /* Can't be a valid request because the length is incorrect. */ + eStatus = MB_EX_ILLEGAL_DATA_VALUE; + } + return eStatus; +} + +#endif +#endif // #if MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED diff --git a/components/freemodbus/modbus/functions/mbfuncother.c b/components/freemodbus/modbus/functions/mbfuncother.c new file mode 100644 index 00000000..a488a5b7 --- /dev/null +++ b/components/freemodbus/modbus/functions/mbfuncother.c @@ -0,0 +1,92 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfuncother.c,v 1.8 2006/12/07 22:10:34 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbconfig.h" + +#if MB_SLAVE_RTU_ENABLED || MB_SLAVE_ASCII_ENABLED || MB_TCP_ENABLED + +#if MB_FUNC_OTHER_REP_SLAVEID_ENABLED + +/* ----------------------- Static variables ---------------------------------*/ +static UCHAR ucMBSlaveID[MB_FUNC_OTHER_REP_SLAVEID_BUF]; +static USHORT usMBSlaveIDLen; + +/* ----------------------- Start implementation -----------------------------*/ + +eMBErrorCode +eMBSetSlaveID( UCHAR ucSlaveID, BOOL xIsRunning, + UCHAR const *pucAdditional, USHORT usAdditionalLen ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + /* the first byte and second byte in the buffer is reserved for + * the parameter ucSlaveID and the running flag. The rest of + * the buffer is available for additional data. */ + if( usAdditionalLen + 2 < MB_FUNC_OTHER_REP_SLAVEID_BUF ) + { + usMBSlaveIDLen = 0; + ucMBSlaveID[usMBSlaveIDLen++] = ucSlaveID; + ucMBSlaveID[usMBSlaveIDLen++] = ( UCHAR )( xIsRunning ? 0xFF : 0x00 ); + if( usAdditionalLen > 0 ) + { + memcpy( &ucMBSlaveID[usMBSlaveIDLen], pucAdditional, + ( size_t )usAdditionalLen ); + usMBSlaveIDLen += usAdditionalLen; + } + } + else + { + eStatus = MB_ENORES; + } + return eStatus; +} + +eMBException +eMBFuncReportSlaveID( UCHAR * pucFrame, USHORT * usLen ) +{ + memcpy( &pucFrame[MB_PDU_DATA_OFF], &ucMBSlaveID[0], ( size_t )usMBSlaveIDLen ); + *usLen = ( USHORT )( MB_PDU_DATA_OFF + usMBSlaveIDLen ); + return MB_EX_NONE; +} + +#endif + +#endif diff --git a/components/freemodbus/modbus/functions/mbutils.c b/components/freemodbus/modbus/functions/mbutils.c new file mode 100644 index 00000000..6a725703 --- /dev/null +++ b/components/freemodbus/modbus/functions/mbutils.c @@ -0,0 +1,141 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbutils.c,v 1.6 2007/02/18 23:49:07 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbproto.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define BITS_UCHAR 8U + +/* ----------------------- Start implementation -----------------------------*/ +void +xMBUtilSetBits( UCHAR * ucByteBuf, USHORT usBitOffset, UCHAR ucNBits, + UCHAR ucValue ) +{ + USHORT usWordBuf; + USHORT usMask; + USHORT usByteOffset; + USHORT usNPreBits; + USHORT usValue = ucValue; + + assert( ucNBits <= 8 ); + assert( ( size_t )BITS_UCHAR == sizeof( UCHAR ) * 8 ); + + /* Calculate byte offset for first byte containing the bit values starting + * at usBitOffset. */ + usByteOffset = ( USHORT )( ( usBitOffset ) / BITS_UCHAR ); + + /* How many bits precede our bits to set. */ + usNPreBits = ( USHORT )( usBitOffset - usByteOffset * BITS_UCHAR ); + + /* Move bit field into position over bits to set */ + usValue <<= usNPreBits; + + /* Prepare a mask for setting the new bits. */ + usMask = ( USHORT )( ( 1 << ( USHORT ) ucNBits ) - 1 ); + usMask <<= usBitOffset - usByteOffset * BITS_UCHAR; + + /* copy bits into temporary storage. */ + usWordBuf = ucByteBuf[usByteOffset]; + usWordBuf |= ucByteBuf[usByteOffset + 1] << BITS_UCHAR; + + /* Zero out bit field bits and then or value bits into them. */ + usWordBuf = ( USHORT )( ( usWordBuf & ( ~usMask ) ) | usValue ); + + /* move bits back into storage */ + ucByteBuf[usByteOffset] = ( UCHAR )( usWordBuf & 0xFF ); + ucByteBuf[usByteOffset + 1] = ( UCHAR )( usWordBuf >> BITS_UCHAR ); +} + +UCHAR +xMBUtilGetBits( UCHAR * ucByteBuf, USHORT usBitOffset, UCHAR ucNBits ) +{ + USHORT usWordBuf; + USHORT usMask; + USHORT usByteOffset; + USHORT usNPreBits; + + /* Calculate byte offset for first byte containing the bit values starting + * at usBitOffset. */ + usByteOffset = ( USHORT )( ( usBitOffset ) / BITS_UCHAR ); + + /* How many bits precede our bits to set. */ + usNPreBits = ( USHORT )( usBitOffset - usByteOffset * BITS_UCHAR ); + + /* Prepare a mask for setting the new bits. */ + usMask = ( USHORT )( ( 1 << ( USHORT ) ucNBits ) - 1 ); + + /* copy bits into temporary storage. */ + usWordBuf = ucByteBuf[usByteOffset]; + usWordBuf |= ucByteBuf[usByteOffset + 1] << BITS_UCHAR; + + /* throw away unneeded bits. */ + usWordBuf >>= usNPreBits; + + /* mask away bits above the requested bitfield. */ + usWordBuf &= usMask; + + return ( UCHAR ) usWordBuf; +} + +eMBException +prveMBError2Exception( eMBErrorCode eErrorCode ) +{ + eMBException eStatus; + + switch ( eErrorCode ) + { + case MB_ENOERR: + eStatus = MB_EX_NONE; + break; + + case MB_ENOREG: + eStatus = MB_EX_ILLEGAL_DATA_ADDRESS; + break; + + case MB_ETIMEDOUT: + eStatus = MB_EX_SLAVE_BUSY; + break; + + default: + eStatus = MB_EX_SLAVE_DEVICE_FAILURE; + break; + } + + return eStatus; +} diff --git a/components/freemodbus/modbus/include/mb.h b/components/freemodbus/modbus/include/mb.h new file mode 100644 index 00000000..abfa92bd --- /dev/null +++ b/components/freemodbus/modbus/include/mb.h @@ -0,0 +1,417 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mb.h,v 1.17 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_H +#define _MB_H + +#include "port.h" + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +#include "mbport.h" +#include "mbproto.h" + +/*! \defgroup modbus Modbus + * \code #include "mb.h" \endcode + * + * This module defines the interface for the application. It contains + * the basic functions and types required to use the Modbus protocol stack. + * A typical application will want to call eMBInit() first. If the device + * is ready to answer network requests it must then call eMBEnable() to activate + * the protocol stack. In the main loop the function eMBPoll() must be called + * periodically. The time interval between pooling depends on the configured + * Modbus timeout. If an RTOS is available a separate task should be created + * and the task should always call the function eMBPoll(). + * + * \code + * // Initialize protocol stack in RTU mode for a slave with address 10 = 0x0A + * eMBInit( MB_RTU, 0x0A, 38400, MB_PAR_EVEN ); + * // Enable the Modbus Protocol Stack. + * eMBEnable( ); + * for( ;; ) + * { + * // Call the main polling loop of the Modbus protocol stack. + * eMBPoll( ); + * ... + * } + * \endcode + */ + +/* ----------------------- Defines ------------------------------------------*/ + +/*! \ingroup modbus + * \brief Use the default Modbus TCP port (502) + */ +#define MB_TCP_PORT_USE_DEFAULT 0 + +#define MB_FUNC_CODE_MAX 127 + +/* ----------------------- Type definitions ---------------------------------*/ +/*! \ingroup modbus + * \brief Modbus serial transmission modes (RTU/ASCII). + * + * Modbus serial supports two transmission modes. Either ASCII or RTU. RTU + * is faster but has more hardware requirements and requires a network with + * a low jitter. ASCII is slower and more reliable on slower links (E.g. modems) + */ +typedef enum +{ + MB_RTU, /*!< RTU transmission mode. */ + MB_ASCII, /*!< ASCII transmission mode. */ + MB_TCP /*!< TCP mode. */ +} eMBMode; + +/*! \ingroup modbus + * \brief If register should be written or read. + * + * This value is passed to the callback functions which support either + * reading or writing register values. Writing means that the application + * registers should be updated and reading means that the modbus protocol + * stack needs to know the current register values. + * + * \see eMBRegHoldingCB( ), eMBRegCoilsCB( ), eMBRegDiscreteCB( ) and + * eMBRegInputCB( ). + */ +typedef enum +{ + MB_REG_READ, /*!< Read register values and pass to protocol stack. */ + MB_REG_WRITE /*!< Update register values. */ +} eMBRegisterMode; + +/*! \ingroup modbus + * \brief Errorcodes used by all function in the protocol stack. + */ +typedef enum +{ + MB_ENOERR, /*!< no error. */ + MB_ENOREG, /*!< illegal register address. */ + MB_EINVAL, /*!< illegal argument. */ + MB_EPORTERR, /*!< porting layer error. */ + MB_ENORES, /*!< insufficient resources. */ + MB_EIO, /*!< I/O error. */ + MB_EILLSTATE, /*!< protocol stack in illegal state. */ + MB_ETIMEDOUT /*!< timeout error occurred. */ +} eMBErrorCode; + +/* ----------------------- Function prototypes ------------------------------*/ +/*! \ingroup modbus + * \brief Initialize the Modbus protocol stack. + * + * This functions initializes the ASCII or RTU module and calls the + * init functions of the porting layer to prepare the hardware. Please + * note that the receiver is still disabled and no Modbus frames are + * processed until eMBEnable( ) has been called. + * + * \param eMode If ASCII or RTU mode should be used. + * \param ucSlaveAddress The slave address. Only frames sent to this + * address or to the broadcast address are processed. + * \param ucPort The port to use. E.g. 1 for COM1 on windows. This value + * is platform dependent and some ports simply choose to ignore it. + * \param ulBaudRate The baudrate. E.g. 19200. Supported baudrates depend + * on the porting layer. + * \param eParity Parity used for serial transmission. + * + * \return If no error occurs the function returns eMBErrorCode::MB_ENOERR. + * The protocol is then in the disabled state and ready for activation + * by calling eMBEnable( ). Otherwise one of the following error codes + * is returned: + * - eMBErrorCode::MB_EINVAL If the slave address was not valid. Valid + * slave addresses are in the range 1 - 247. + * - eMBErrorCode::MB_EPORTERR IF the porting layer returned an error. + */ +eMBErrorCode eMBInit( eMBMode eMode, UCHAR ucSlaveAddress, + UCHAR ucPort, ULONG ulBaudRate, eMBParity eParity ); + +/*! \ingroup modbus + * \brief Initialize the Modbus protocol stack for Modbus TCP. + * + * This function initializes the Modbus TCP Module. Please note that + * frame processing is still disabled until eMBEnable( ) is called. + * + * \param usTCPPort The TCP port to listen on. + * \return If the protocol stack has been initialized correctly the function + * returns eMBErrorCode::MB_ENOERR. Otherwise one of the following error + * codes is returned: + * - eMBErrorCode::MB_EINVAL If the slave address was not valid. Valid + * slave addresses are in the range 1 - 247. + * - eMBErrorCode::MB_EPORTERR IF the porting layer returned an error. + */ +eMBErrorCode eMBTCPInit( USHORT usTCPPort ); + +/*! \ingroup modbus + * \brief Release resources used by the protocol stack. + * + * This function disables the Modbus protocol stack and release all + * hardware resources. It must only be called when the protocol stack + * is disabled. + * + * \note Note all ports implement this function. A port which wants to + * get an callback must define the macro MB_PORT_HAS_CLOSE to 1. + * + * \return If the resources where released it return eMBErrorCode::MB_ENOERR. + * If the protocol stack is not in the disabled state it returns + * eMBErrorCode::MB_EILLSTATE. + */ +eMBErrorCode eMBClose( void ); + +/*! \ingroup modbus + * \brief Enable the Modbus protocol stack. + * + * This function enables processing of Modbus frames. Enabling the protocol + * stack is only possible if it is in the disabled state. + * + * \return If the protocol stack is now in the state enabled it returns + * eMBErrorCode::MB_ENOERR. If it was not in the disabled state it + * return eMBErrorCode::MB_EILLSTATE. + */ +eMBErrorCode eMBEnable( void ); + +/*! \ingroup modbus + * \brief Disable the Modbus protocol stack. + * + * This function disables processing of Modbus frames. + * + * \return If the protocol stack has been disabled it returns + * eMBErrorCode::MB_ENOERR. If it was not in the enabled state it returns + * eMBErrorCode::MB_EILLSTATE. + */ +eMBErrorCode eMBDisable( void ); + +/*! \ingroup modbus + * \brief The main pooling loop of the Modbus protocol stack. + * + * This function must be called periodically. The timer interval required + * is given by the application dependent Modbus slave timeout. Internally the + * function calls xMBPortEventGet() and waits for an event from the receiver or + * transmitter state machines. + * + * \return If the protocol stack is not in the enabled state the function + * returns eMBErrorCode::MB_EILLSTATE. Otherwise it returns + * eMBErrorCode::MB_ENOERR. + */ +eMBErrorCode eMBPoll( void ); + +/*! \ingroup modbus + * \brief Configure the slave id of the device. + * + * This function should be called when the Modbus function Report Slave ID + * is enabled ( By defining MB_FUNC_OTHER_REP_SLAVEID_ENABLED in mbconfig.h ). + * + * \param ucSlaveID Values is returned in the Slave ID byte of the + * Report Slave ID response. + * \param xIsRunning If TRUE the Run Indicator Status byte is set to 0xFF. + * otherwise the Run Indicator Status is 0x00. + * \param pucAdditional Values which should be returned in the Additional + * bytes of the Report Slave ID response. + * \param usAdditionalLen Length of the buffer pucAdditonal. + * + * \return If the static buffer defined by MB_FUNC_OTHER_REP_SLAVEID_BUF in + * mbconfig.h is to small it returns eMBErrorCode::MB_ENORES. Otherwise + * it returns eMBErrorCode::MB_ENOERR. + */ +eMBErrorCode eMBSetSlaveID( UCHAR ucSlaveID, BOOL xIsRunning, + UCHAR const *pucAdditional, + USHORT usAdditionalLen ); + +/*! \ingroup modbus + * \brief Registers a callback handler for a given function code. + * + * This function registers a new callback handler for a given function code. + * The callback handler supplied is responsible for interpreting the Modbus PDU and + * the creation of an appropriate response. In case of an error it should return + * one of the possible Modbus exceptions which results in a Modbus exception frame + * sent by the protocol stack. + * + * \param ucFunctionCode The Modbus function code for which this handler should + * be registers. Valid function codes are in the range 1 to 127. + * \param pxHandler The function handler which should be called in case + * such a frame is received. If \c NULL a previously registered function handler + * for this function code is removed. + * + * \return eMBErrorCode::MB_ENOERR if the handler has been installed. If no + * more resources are available it returns eMBErrorCode::MB_ENORES. In this + * case the values in mbconfig.h should be adjusted. If the argument was not + * valid it returns eMBErrorCode::MB_EINVAL. + */ +eMBErrorCode eMBRegisterCB( UCHAR ucFunctionCode, + pxMBFunctionHandler pxHandler ); + +/* ----------------------- Callback -----------------------------------------*/ + +/*! \defgroup modbus_registers Modbus Registers + * \code #include "mb.h" \endcode + * The protocol stack does not internally allocate any memory for the + * registers. This makes the protocol stack very small and also usable on + * low end targets. In addition the values don't have to be in the memory + * and could for example be stored in a flash.
+ * Whenever the protocol stack requires a value it calls one of the callback + * function with the register address and the number of registers to read + * as an argument. The application should then read the actual register values + * (for example the ADC voltage) and should store the result in the supplied + * buffer.
+ * If the protocol stack wants to update a register value because a write + * register function was received a buffer with the new register values is + * passed to the callback function. The function should then use these values + * to update the application register values. + */ + +/*! \ingroup modbus_registers + * \brief Callback function used if the value of a Input Register + * is required by the protocol stack. The starting register address is given + * by \c usAddress and the last register is given by usAddress + + * usNRegs - 1. + * + * \param pucRegBuffer A buffer where the callback function should write + * the current value of the modbus registers to. + * \param usAddress The starting address of the register. Input registers + * are in the range 1 - 65535. + * \param usNRegs Number of registers the callback function must supply. + * + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If the application can not supply values + * for registers within this range. In this case a + * ILLEGAL DATA ADDRESS exception frame is sent as a response. + * - eMBErrorCode::MB_ETIMEDOUT If the requested register block is + * currently not available and the application dependent response + * timeout would be violated. In this case a SLAVE DEVICE BUSY + * exception is sent as a response. + * - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case + * a SLAVE DEVICE FAILURE exception is sent as a response. + */ +eMBErrorCode eMBRegInputCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs ); + +/*! \ingroup modbus_registers + * \brief Callback function used if a Holding Register value is + * read or written by the protocol stack. The starting register address + * is given by \c usAddress and the last register is given by + * usAddress + usNRegs - 1. + * + * \param pucRegBuffer If the application registers values should be updated the + * buffer points to the new registers values. If the protocol stack needs + * to now the current values the callback function should write them into + * this buffer. + * \param usAddress The starting address of the register. + * \param usNRegs Number of registers to read or write. + * \param eMode If eMBRegisterMode::MB_REG_WRITE the application register + * values should be updated from the values in the buffer. For example + * this would be the case when the Modbus master has issued an + * WRITE SINGLE REGISTER command. + * If the value eMBRegisterMode::MB_REG_READ the application should copy + * the current values into the buffer \c pucRegBuffer. + * + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If the application can not supply values + * for registers within this range. In this case a + * ILLEGAL DATA ADDRESS exception frame is sent as a response. + * - eMBErrorCode::MB_ETIMEDOUT If the requested register block is + * currently not available and the application dependent response + * timeout would be violated. In this case a SLAVE DEVICE BUSY + * exception is sent as a response. + * - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case + * a SLAVE DEVICE FAILURE exception is sent as a response. + */ +eMBErrorCode eMBRegHoldingCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs, eMBRegisterMode eMode ); + +/*! \ingroup modbus_registers + * \brief Callback function used if a Coil Register value is + * read or written by the protocol stack. If you are going to use + * this function you might use the functions xMBUtilSetBits( ) and + * xMBUtilGetBits( ) for working with bitfields. + * + * \param pucRegBuffer The bits are packed in bytes where the first coil + * starting at address \c usAddress is stored in the LSB of the + * first byte in the buffer pucRegBuffer. + * If the buffer should be written by the callback function unused + * coil values (I.e. if not a multiple of eight coils is used) should be set + * to zero. + * \param usAddress The first coil number. + * \param usNCoils Number of coil values requested. + * \param eMode If eMBRegisterMode::MB_REG_WRITE the application values should + * be updated from the values supplied in the buffer \c pucRegBuffer. + * If eMBRegisterMode::MB_REG_READ the application should store the current + * values in the buffer \c pucRegBuffer. + * + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If the application does not map an coils + * within the requested address range. In this case a + * ILLEGAL DATA ADDRESS is sent as a response. + * - eMBErrorCode::MB_ETIMEDOUT If the requested register block is + * currently not available and the application dependent response + * timeout would be violated. In this case a SLAVE DEVICE BUSY + * exception is sent as a response. + * - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case + * a SLAVE DEVICE FAILURE exception is sent as a response. + */ +eMBErrorCode eMBRegCoilsCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNCoils, eMBRegisterMode eMode ); + +/*! \ingroup modbus_registers + * \brief Callback function used if a Input Discrete Register value is + * read by the protocol stack. + * + * If you are going to use his function you might use the functions + * xMBUtilSetBits( ) and xMBUtilGetBits( ) for working with bitfields. + * + * \param pucRegBuffer The buffer should be updated with the current + * coil values. The first discrete input starting at \c usAddress must be + * stored at the LSB of the first byte in the buffer. If the requested number + * is not a multiple of eight the remaining bits should be set to zero. + * \param usAddress The starting address of the first discrete input. + * \param usNDiscrete Number of discrete input values. + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If no such discrete inputs exists. + * In this case a ILLEGAL DATA ADDRESS exception frame is sent + * as a response. + * - eMBErrorCode::MB_ETIMEDOUT If the requested register block is + * currently not available and the application dependent response + * timeout would be violated. In this case a SLAVE DEVICE BUSY + * exception is sent as a response. + * - eMBErrorCode::MB_EIO If an unrecoverable error occurred. In this case + * a SLAVE DEVICE FAILURE exception is sent as a response. + */ +eMBErrorCode eMBRegDiscreteCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNDiscrete ); + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/include/mb_m.h b/components/freemodbus/modbus/include/mb_m.h new file mode 100644 index 00000000..f17867e1 --- /dev/null +++ b/components/freemodbus/modbus/include/mb_m.h @@ -0,0 +1,410 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (C) 2013 Armink + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mb_m.h,v 1.60 2013/09/03 10:20:05 Armink Add Master Functions $ + */ + +#ifndef _MB_M_H +#define _MB_M_H + +#include "mbconfig.h" +#include "port.h" +#include "mb.h" + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +#include "mbport.h" +#include "mbproto.h" +/*! \defgroup modbus Modbus + * \code #include "mb.h" \endcode + * + * This module defines the interface for the application. It contains + * the basic functions and types required to use the Modbus Master protocol stack. + * A typical application will want to call eMBMasterInit() first. If the device + * is ready to answer network requests it must then call eMBEnable() to activate + * the protocol stack. In the main loop the function eMBMasterPoll() must be called + * periodically. The time interval between pooling depends on the configured + * Modbus timeout. If an RTOS is available a separate task should be created + * and the task should always call the function eMBMasterPoll(). + * + * \code + * // Initialize protocol stack in RTU mode for a Master + * eMBMasterInit( MB_RTU, 38400, MB_PAR_EVEN ); + * // Enable the Modbus Protocol Stack. + * eMBMasterEnable( ); + * for( ;; ) + * { + * // Call the main polling loop of the Modbus Master protocol stack. + * eMBMasterPoll( ); + * ... + * } + * \endcode + */ + +/* ----------------------- Defines ------------------------------------------*/ + +/*! \ingroup modbus + * \brief Use the default Modbus Master TCP port (502) + */ +#define MB_MASTER_TCP_PORT_USE_DEFAULT 0 + +/*! \ingroup modbus + * \brief Errorcodes used by all function in the Master request. + */ +typedef enum +{ + MB_MRE_NO_ERR, /*!< no error. */ + MB_MRE_NO_REG, /*!< illegal register address. */ + MB_MRE_ILL_ARG, /*!< illegal argument. */ + MB_MRE_REV_DATA, /*!< receive data error. */ + MB_MRE_TIMEDOUT, /*!< timeout error occurred. */ + MB_MRE_MASTER_BUSY, /*!< master is busy now. */ + MB_MRE_EXE_FUN /*!< execute function error. */ +} eMBMasterReqErrCode; + +/*! \ingroup modbus + * \brief TimerMode is Master 3 kind of Timer modes. + */ +typedef enum +{ + MB_TMODE_T35, /*!< Master receive frame T3.5 timeout. */ + MB_TMODE_RESPOND_TIMEOUT, /*!< Master wait respond for slave. */ + MB_TMODE_CONVERT_DELAY /*!< Master sent broadcast ,then delay sometime.*/ +}eMBMasterTimerMode; + +/* ----------------------- Function prototypes ------------------------------*/ +/*! \ingroup modbus + * \brief Initialize the Modbus Master protocol stack. + * + * This functions initializes the ASCII or RTU module and calls the + * init functions of the porting layer to prepare the hardware. Please + * note that the receiver is still disabled and no Modbus frames are + * processed until eMBMasterEnable( ) has been called. + * + * \param eMode If ASCII or RTU mode should be used. + * \param ucPort The port to use. E.g. 1 for COM1 on windows. This value + * is platform dependent and some ports simply choose to ignore it. + * \param ulBaudRate The baudrate. E.g. 19200. Supported baudrates depend + * on the porting layer. + * \param eParity Parity used for serial transmission. + * + * \return If no error occurs the function returns eMBErrorCode::MB_ENOERR. + * The protocol is then in the disabled state and ready for activation + * by calling eMBMasterEnable( ). Otherwise one of the following error codes + * is returned: + * - eMBErrorCode::MB_EPORTERR IF the porting layer returned an error. + */ +eMBErrorCode eMBMasterSerialInit( eMBMode eMode, UCHAR ucPort, + ULONG ulBaudRate, eMBParity eParity ); + +/*! \ingroup modbus + * \brief Initialize the Modbus Master protocol stack for Modbus TCP. + * + * This function initializes the Modbus TCP Module. Please note that + * frame processing is still disabled until eMBEnable( ) is called. + * + * \param usTCPPort The TCP port to listen on. + * \return If the protocol stack has been initialized correctly the function + * returns eMBErrorCode::MB_ENOERR. Otherwise one of the following error + * codes is returned: + * - eMBErrorCode::MB_EINVAL If the slave address was not valid. Valid + * slave addresses are in the range 1 - 247. + * - eMBErrorCode::MB_EPORTERR IF the porting layer returned an error. + */ +eMBErrorCode eMBMasterTCPInit( USHORT usTCPPort ); + +/*! \ingroup modbus + * \brief Release resources used by the protocol stack. + * + * This function disables the Modbus Master protocol stack and release all + * hardware resources. It must only be called when the protocol stack + * is disabled. + * + * \note Note all ports implement this function. A port which wants to + * get an callback must define the macro MB_PORT_HAS_CLOSE to 1. + * + * \return If the resources where released it return eMBErrorCode::MB_ENOERR. + * If the protocol stack is not in the disabled state it returns + * eMBErrorCode::MB_EILLSTATE. + */ +eMBErrorCode eMBMasterClose( void ); + +/*! \ingroup modbus + * \brief Enable the Modbus Master protocol stack. + * + * This function enables processing of Modbus Master frames. Enabling the protocol + * stack is only possible if it is in the disabled state. + * + * \return If the protocol stack is now in the state enabled it returns + * eMBErrorCode::MB_ENOERR. If it was not in the disabled state it + * return eMBErrorCode::MB_EILLSTATE. + */ +eMBErrorCode eMBMasterEnable( void ); + +/*! \ingroup modbus + * \brief Disable the Modbus Master protocol stack. + * + * This function disables processing of Modbus frames. + * + * \return If the protocol stack has been disabled it returns + * eMBErrorCode::MB_ENOERR. If it was not in the enabled state it returns + * eMBErrorCode::MB_EILLSTATE. + */ +eMBErrorCode eMBMasterDisable( void ); + +/*! \ingroup modbus + * \brief The main pooling loop of the Modbus Master protocol stack. + * + * This function must be called periodically. The timer interval required + * is given by the application dependent Modbus slave timeout. Internally the + * function calls xMBMasterPortEventGet() and waits for an event from the receiver or + * transmitter state machines. + * + * \return If the protocol stack is not in the enabled state the function + * returns eMBErrorCode::MB_EILLSTATE. Otherwise it returns + * eMBErrorCode::MB_ENOERR. + */ +eMBErrorCode eMBMasterPoll( void ); + +/*! \ingroup modbus + * \brief Registers a callback handler for a given function code. + * + * This function registers a new callback handler for a given function code. + * The callback handler supplied is responsible for interpreting the Modbus PDU and + * the creation of an appropriate response. In case of an error it should return + * one of the possible Modbus exceptions which results in a Modbus exception frame + * sent by the protocol stack. + * + * \param ucFunctionCode The Modbus function code for which this handler should + * be registers. Valid function codes are in the range 1 to 127. + * \param pxHandler The function handler which should be called in case + * such a frame is received. If \c NULL a previously registered function handler + * for this function code is removed. + * + * \return eMBErrorCode::MB_ENOERR if the handler has been installed. If no + * more resources are available it returns eMBErrorCode::MB_ENORES. In this + * case the values in mbconfig.h should be adjusted. If the argument was not + * valid it returns eMBErrorCode::MB_EINVAL. + */ +eMBErrorCode eMBMasterRegisterCB( UCHAR ucFunctionCode, + pxMBFunctionHandler pxHandler ); + +/* ----------------------- Callback -----------------------------------------*/ + +/*! \defgroup modbus_master registers Modbus Registers + * \code #include "mb_m.h" \endcode + * The protocol stack does not internally allocate any memory for the + * registers. This makes the protocol stack very small and also usable on + * low end targets. In addition the values don't have to be in the memory + * and could for example be stored in a flash.
+ * Whenever the protocol stack requires a value it calls one of the callback + * function with the register address and the number of registers to read + * as an argument. The application should then read the actual register values + * (for example the ADC voltage) and should store the result in the supplied + * buffer.
+ * If the protocol stack wants to update a register value because a write + * register function was received a buffer with the new register values is + * passed to the callback function. The function should then use these values + * to update the application register values. + */ + +/*! \ingroup modbus_registers + * \brief Callback function used if the value of a Input Register + * is required by the protocol stack. The starting register address is given + * by \c usAddress and the last register is given by usAddress + + * usNRegs - 1. + * + * \param pucRegBuffer A buffer where the callback function should write + * the current value of the modbus registers to. + * \param usAddress The starting address of the register. Input registers + * are in the range 1 - 65535. + * \param usNRegs Number of registers the callback function must supply. + * + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If the application does not map an coils + * within the requested address range. In this case a + * ILLEGAL DATA ADDRESS is sent as a response. + */ +eMBErrorCode eMBMasterRegInputCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs ); + +/*! \ingroup modbus_registers + * \brief Callback function used if a Holding Register value is + * read or written by the protocol stack. The starting register address + * is given by \c usAddress and the last register is given by + * usAddress + usNRegs - 1. + * + * \param pucRegBuffer If the application registers values should be updated the + * buffer points to the new registers values. If the protocol stack needs + * to now the current values the callback function should write them into + * this buffer. + * \param usAddress The starting address of the register. + * \param usNRegs Number of registers to read or write. + * \param eMode If eMBRegisterMode::MB_REG_WRITE the application register + * values should be updated from the values in the buffer. For example + * this would be the case when the Modbus master has issued an + * WRITE SINGLE REGISTER command. + * If the value eMBRegisterMode::MB_REG_READ the application should copy + * the current values into the buffer \c pucRegBuffer. + * + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If the application does not map an coils + * within the requested address range. In this case a + * ILLEGAL DATA ADDRESS is sent as a response. + */ +eMBErrorCode eMBMasterRegHoldingCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs, eMBRegisterMode eMode ); + +/*! \ingroup modbus_registers + * \brief Callback function used if a Coil Register value is + * read or written by the protocol stack. If you are going to use + * this function you might use the functions xMBUtilSetBits( ) and + * xMBUtilGetBits( ) for working with bitfields. + * + * \param pucRegBuffer The bits are packed in bytes where the first coil + * starting at address \c usAddress is stored in the LSB of the + * first byte in the buffer pucRegBuffer. + * If the buffer should be written by the callback function unused + * coil values (I.e. if not a multiple of eight coils is used) should be set + * to zero. + * \param usAddress The first coil number. + * \param usNCoils Number of coil values requested. + * \param eMode If eMBRegisterMode::MB_REG_WRITE the application values should + * be updated from the values supplied in the buffer \c pucRegBuffer. + * If eMBRegisterMode::MB_REG_READ the application should store the current + * values in the buffer \c pucRegBuffer. + * + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If the application does not map an coils + * within the requested address range. In this case a + * ILLEGAL DATA ADDRESS is sent as a response. + */ +eMBErrorCode eMBMasterRegCoilsCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNCoils, eMBRegisterMode eMode ); + +/*! \ingroup modbus_registers + * \brief Callback function used if a Input Discrete Register value is + * read by the protocol stack. + * + * If you are going to use his function you might use the functions + * xMBUtilSetBits( ) and xMBUtilGetBits( ) for working with bitfields. + * + * \param pucRegBuffer The buffer should be updated with the current + * coil values. The first discrete input starting at \c usAddress must be + * stored at the LSB of the first byte in the buffer. If the requested number + * is not a multiple of eight the remaining bits should be set to zero. + * \param usAddress The starting address of the first discrete input. + * \param usNDiscrete Number of discrete input values. + * \return The function must return one of the following error codes: + * - eMBErrorCode::MB_ENOERR If no error occurred. In this case a normal + * Modbus response is sent. + * - eMBErrorCode::MB_ENOREG If the application does not map an coils + * within the requested address range. In this case a + * ILLEGAL DATA ADDRESS is sent as a response. + */ +eMBErrorCode eMBMasterRegDiscreteCB( UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNDiscrete ); + +/*! \ingroup modbus + *\brief These Modbus functions are called for user when Modbus run in Master Mode. + */ +eMBMasterReqErrCode +eMBMasterReqReadInputRegister( UCHAR ucSndAddr, USHORT usRegAddr, USHORT usNRegs, LONG lTimeOut ); +eMBMasterReqErrCode +eMBMasterReqWriteHoldingRegister( UCHAR ucSndAddr, USHORT usRegAddr, USHORT usRegData, LONG lTimeOut ); +eMBMasterReqErrCode +eMBMasterReqWriteMultipleHoldingRegister( UCHAR ucSndAddr, USHORT usRegAddr, + USHORT usNRegs, USHORT * pusDataBuffer, LONG lTimeOut ); +eMBMasterReqErrCode +eMBMasterReqReadHoldingRegister( UCHAR ucSndAddr, USHORT usRegAddr, USHORT usNRegs, LONG lTimeOut ); +eMBMasterReqErrCode +eMBMasterReqReadWriteMultipleHoldingRegister( UCHAR ucSndAddr, + USHORT usReadRegAddr, USHORT usNReadRegs, USHORT * pusDataBuffer, + USHORT usWriteRegAddr, USHORT usNWriteRegs, LONG lTimeOut ); +eMBMasterReqErrCode +eMBMasterReqReadCoils( UCHAR ucSndAddr, USHORT usCoilAddr, USHORT usNCoils, LONG lTimeOut ); +eMBMasterReqErrCode +eMBMasterReqWriteCoil( UCHAR ucSndAddr, USHORT usCoilAddr, USHORT usCoilData, LONG lTimeOut ); +eMBMasterReqErrCode +eMBMasterReqWriteMultipleCoils( UCHAR ucSndAddr, + USHORT usCoilAddr, USHORT usNCoils, UCHAR * pucDataBuffer, LONG lTimeOut ); +eMBMasterReqErrCode +eMBMasterReqReadDiscreteInputs( UCHAR ucSndAddr, USHORT usDiscreteAddr, USHORT usNDiscreteIn, LONG lTimeOut ); + +eMBException +eMBMasterFuncReportSlaveID( UCHAR * pucFrame, USHORT * usLen ); +eMBException +eMBMasterFuncReadInputRegister( UCHAR * pucFrame, USHORT * usLen ); +eMBException +eMBMasterFuncReadHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); +eMBException +eMBMasterFuncWriteHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); +eMBException +eMBMasterFuncWriteMultipleHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); +eMBException +eMBMasterFuncReadCoils( UCHAR * pucFrame, USHORT * usLen ); +eMBException +eMBMasterFuncWriteCoil( UCHAR * pucFrame, USHORT * usLen ); +eMBException +eMBMasterFuncWriteMultipleCoils( UCHAR * pucFrame, USHORT * usLen ); +eMBException +eMBMasterFuncReadDiscreteInputs( UCHAR * pucFrame, USHORT * usLen ); +eMBException +eMBMasterFuncReadWriteMultipleHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); + +/* \ingroup modbus + * \brief These functions are interface for Modbus Master + */ +void vMBMasterGetPDUSndBuf( UCHAR ** pucFrame ); +UCHAR ucMBMasterGetDestAddress( void ); +void vMBMasterSetDestAddress( UCHAR Address ); +BOOL xMBMasterGetCBRunInMasterMode( void ); +void vMBMasterSetCBRunInMasterMode( BOOL IsMasterMode ); +USHORT usMBMasterGetPDUSndLength( void ); +void vMBMasterSetPDUSndLength( USHORT SendPDULength ); +void vMBMasterSetCurTimerMode( eMBMasterTimerMode eMBTimerMode ); +void vMBMasterRequestSetType( BOOL xIsBroadcast ); +eMBMasterTimerMode xMBMasterGetCurTimerMode( void ); +BOOL xMBMasterRequestIsBroadcast( void ); +eMBMasterErrorEventType eMBMasterGetErrorType( void ); +void vMBMasterSetErrorType( eMBMasterErrorEventType errorType ); +eMBMasterReqErrCode eMBMasterWaitRequestFinish( void ); + +/* ----------------------- Callback -----------------------------------------*/ + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/include/mbconfig.h b/components/freemodbus/modbus/include/mbconfig.h new file mode 100644 index 00000000..f32be6c2 --- /dev/null +++ b/components/freemodbus/modbus/include/mbconfig.h @@ -0,0 +1,170 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbconfig.h,v 1.15 2010/06/06 13:54:40 wolti Exp $ + * $Id: mbconfig.h,v 1.60 2013/08/13 21:19:55 Armink Add Master Functions $ + */ + +#ifndef _MB_CONFIG_H +#define _MB_CONFIG_H + +#include "sdkconfig.h" // for KConfig options + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif +/* ----------------------- Defines ------------------------------------------*/ +/*! \defgroup modbus_cfg Modbus Configuration + * + * Most modules in the protocol stack are completly optional and can be + * excluded. This is specially important if target resources are very small + * and program memory space should be saved.
+ * + * All of these settings are available in the file mbconfig.h + */ +/*! \addtogroup modbus_cfg + * @{ + */ +/*! \brief If Modbus Master ASCII support is enabled. */ +#define MB_MASTER_ASCII_ENABLED ( CONFIG_FMB_COMM_MODE_ASCII_EN ) +/*! \brief If Modbus Master RTU support is enabled. */ +#define MB_MASTER_RTU_ENABLED ( CONFIG_FMB_COMM_MODE_RTU_EN ) +/*! \brief If Modbus Master TCP support is enabled. */ +#define MB_MASTER_TCP_ENABLED ( CONFIG_FMB_COMM_MODE_TCP_EN ) +/*! \brief If Modbus Slave ASCII support is enabled. */ +#define MB_SLAVE_ASCII_ENABLED ( CONFIG_FMB_COMM_MODE_ASCII_EN ) +/*! \brief If Modbus Slave RTU support is enabled. */ +#define MB_SLAVE_RTU_ENABLED ( CONFIG_FMB_COMM_MODE_RTU_EN ) +/*! \brief If Modbus Slave TCP support is enabled. */ +#define MB_TCP_ENABLED ( CONFIG_FMB_COMM_MODE_TCP_EN ) + +#if !CONFIG_FMB_COMM_MODE_ASCII_EN && !CONFIG_FMB_COMM_MODE_RTU_EN && !MB_MASTER_TCP_ENABLED && !MB_TCP_ENABLED +#error "None of Modbus communication mode is enabled. Please enable one of (ASCII, RTU, TCP) mode in Kconfig." +#endif + +/*! \brief This option defines the number of data bits per ASCII character. + * + * A parity bit is added before the stop bit which keeps the actual byte size at 10 bits. + */ +#ifdef CONFIG_FMB_SERIAL_ASCII_BITS_PER_SYMB +#define MB_ASCII_BITS_PER_SYMB ( CONFIG_FMB_SERIAL_ASCII_BITS_PER_SYMB ) +#endif + +/*! \brief The character timeout value for Modbus ASCII. + * + * The character timeout value is not fixed for Modbus ASCII and is therefore + * a configuration option. It should be set to the maximum expected delay + * time of the network. + */ +#ifdef CONFIG_FMB_SERIAL_ASCII_TIMEOUT_RESPOND_MS +#define MB_ASCII_TIMEOUT_MS ( CONFIG_FMB_SERIAL_ASCII_TIMEOUT_RESPOND_MS ) +#endif + +/*! \brief Timeout to wait in ASCII prior to enabling transmitter. + * + * If defined the function calls vMBPortSerialDelay with the argument + * MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS to allow for a delay before + * the serial transmitter is enabled. This is required because some + * targets are so fast that there is no time between receiving and + * transmitting the frame. If the master is to slow with enabling its + * receiver then he will not receive the response correctly. + */ +#ifndef MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS +#define MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS ( 0 ) +#endif + +/*! \brief Maximum number of Modbus functions codes the protocol stack + * should support. + * + * The maximum number of supported Modbus functions must be greater than + * the sum of all enabled functions in this file and custom function + * handlers. If set to small adding more functions will fail. + */ +#define MB_FUNC_HANDLERS_MAX ( 16 ) + +/*! \brief Number of bytes which should be allocated for the Report Slave ID + * command. + * + * This number limits the maximum size of the additional segment in the + * report slave id function. See eMBSetSlaveID( ) for more information on + * how to set this value. It is only used if MB_FUNC_OTHER_REP_SLAVEID_ENABLED + * is set to 1. + */ +#define MB_FUNC_OTHER_REP_SLAVEID_BUF ( 32 ) + +/*! \brief If the Report Slave ID function should be enabled. */ +#define MB_FUNC_OTHER_REP_SLAVEID_ENABLED ( CONFIG_FMB_CONTROLLER_SLAVE_ID_SUPPORT ) + +/*! \brief If the Read Input Registers function should be enabled. */ +#define MB_FUNC_READ_INPUT_ENABLED ( 1 ) + +/*! \brief If the Read Holding Registers function should be enabled. */ +#define MB_FUNC_READ_HOLDING_ENABLED ( 1 ) + +/*! \brief If the Write Single Register function should be enabled. */ +#define MB_FUNC_WRITE_HOLDING_ENABLED ( 1 ) + +/*! \brief If the Write Multiple registers function should be enabled. */ +#define MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED ( 1 ) + +/*! \brief If the Read Coils function should be enabled. */ +#define MB_FUNC_READ_COILS_ENABLED ( 1 ) + +/*! \brief If the Write Coils function should be enabled. */ +#define MB_FUNC_WRITE_COIL_ENABLED ( 1 ) + +/*! \brief If the Write Multiple Coils function should be enabled. */ +#define MB_FUNC_WRITE_MULTIPLE_COILS_ENABLED ( 1 ) + +/*! \brief If the Read Discrete Inputs function should be enabled. */ +#define MB_FUNC_READ_DISCRETE_INPUTS_ENABLED ( 1 ) + +/*! \brief If the Read/Write Multiple Registers function should be enabled. */ +#define MB_FUNC_READWRITE_HOLDING_ENABLED ( 1 ) + +/*! \brief Check the option to place timer handler into IRAM */ +#define MB_PORT_TIMER_ISR_IN_IRAM ( CONFIG_FMB_TIMER_ISR_IN_IRAM ) + +/*! @} */ +#ifdef __cplusplus + PR_END_EXTERN_C +#endif + +#if MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED +/*! \brief If master send a broadcast frame, the master will wait time of convert to delay, + * then master can send other frame */ +#define MB_MASTER_DELAY_MS_CONVERT ( CONFIG_FMB_MASTER_DELAY_MS_CONVERT ) +/*! \brief If master send a frame which is not broadcast,the master will wait sometime for slave. + * And if slave is not respond in this time,the master will process this timeout error. + * Then master can send other frame */ +#define MB_MASTER_TIMEOUT_MS_RESPOND ( CONFIG_FMB_MASTER_TIMEOUT_MS_RESPOND ) +/*! \brief The total slaves in Modbus Master system. + * \note : The slave ID must be continuous from 1.*/ +#define MB_MASTER_TOTAL_SLAVE_NUM ( 247 ) +#endif + +#endif diff --git a/components/freemodbus/modbus/include/mbframe.h b/components/freemodbus/modbus/include/mbframe.h new file mode 100644 index 00000000..9dbfc394 --- /dev/null +++ b/components/freemodbus/modbus/include/mbframe.h @@ -0,0 +1,103 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbframe.h,v 1.9 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_FRAME_H +#define _MB_FRAME_H + +#include "port.h" + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +/*! + * Constants which defines the format of a modbus frame. The example is + * shown for a Modbus RTU/ASCII frame. Note that the Modbus PDU is not + * dependent on the underlying transport. + * + * + * <------------------------ MODBUS SERIAL LINE PDU (1) -------------------> + * <----------- MODBUS PDU (1') ----------------> + * +-----------+---------------+----------------------------+-------------+ + * | Address | Function Code | Data | CRC/LRC | + * +-----------+---------------+----------------------------+-------------+ + * | | | | + * (2) (3/2') (3') (4) + * + * (1) ... MB_SER_PDU_SIZE_MAX = 256 + * (2) ... MB_SER_PDU_ADDR_OFF = 0 + * (3) ... MB_SER_PDU_PDU_OFF = 1 + * (4) ... MB_SER_PDU_SIZE_CRC = 2 + * + * (1') ... MB_PDU_SIZE_MAX = 253 + * (2') ... MB_PDU_FUNC_OFF = 0 + * (3') ... MB_PDU_DATA_OFF = 1 + * + */ + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_PDU_SIZE_MAX 253 /*!< Maximum size of a PDU. */ +#define MB_PDU_SIZE_MIN 1 /*!< Function Code */ +#define MB_PDU_FUNC_OFF 0 /*!< Offset of function code in PDU. */ +#define MB_PDU_DATA_OFF 1 /*!< Offset for response data in PDU. */ + +#define MB_SER_PDU_SIZE_MAX MB_SERIAL_BUF_SIZE /*!< Maximum size of a Modbus frame. */ +#define MB_SER_PDU_SIZE_LRC 1 /*!< Size of LRC field in PDU. */ +#define MB_SER_PDU_ADDR_OFF 0 /*!< Offset of slave address in Ser-PDU. */ +#define MB_SER_PDU_PDU_OFF 1 /*!< Offset of Modbus-PDU in Ser-PDU. */ +#define MB_SER_PDU_SIZE_CRC 2 /*!< Size of CRC field in PDU. */ + +#define MB_TCP_TID 0 +#define MB_TCP_PID 2 +#define MB_TCP_LEN 4 +#define MB_TCP_UID 6 +#define MB_TCP_FUNC 7 + +#define MB_TCP_PSEUDO_ADDRESS 255 + +/* ----------------------- Prototypes 0-------------------------------------*/ +typedef void ( *pvMBFrameStart ) ( void ); + +typedef void ( *pvMBFrameStop ) ( void ); + +typedef eMBErrorCode( *peMBFrameReceive ) ( UCHAR * pucRcvAddress, + UCHAR ** pucFrame, + USHORT * pusLength ); + +typedef eMBErrorCode( *peMBFrameSend ) ( UCHAR slaveAddress, + const UCHAR * pucFrame, + USHORT usLength ); + +typedef void( *pvMBFrameClose ) ( void ); + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/include/mbfunc.h b/components/freemodbus/modbus/include/mbfunc.h new file mode 100644 index 00000000..aea14f75 --- /dev/null +++ b/components/freemodbus/modbus/include/mbfunc.h @@ -0,0 +1,80 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbfunc.h,v 1.12 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_FUNC_H +#define _MB_FUNC_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif +#if MB_FUNC_OTHER_REP_SLAVEID_BUF > 0 + eMBException eMBFuncReportSlaveID( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_READ_INPUT_ENABLED > 0 +eMBException eMBFuncReadInputRegister( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_READ_HOLDING_ENABLED > 0 +eMBException eMBFuncReadHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_WRITE_HOLDING_ENABLED > 0 +eMBException eMBFuncWriteHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED > 0 +eMBException eMBFuncWriteMultipleHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_READ_COILS_ENABLED > 0 +eMBException eMBFuncReadCoils( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_WRITE_COIL_ENABLED > 0 +eMBException eMBFuncWriteCoil( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_WRITE_MULTIPLE_COILS_ENABLED > 0 +eMBException eMBFuncWriteMultipleCoils( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_READ_DISCRETE_INPUTS_ENABLED > 0 +eMBException eMBFuncReadDiscreteInputs( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#if MB_FUNC_READWRITE_HOLDING_ENABLED > 0 +eMBException eMBFuncReadWriteMultipleHoldingRegister( UCHAR * pucFrame, USHORT * usLen ); +#endif + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/include/mbport.h b/components/freemodbus/modbus/include/mbport.h new file mode 100644 index 00000000..8dfe8b7c --- /dev/null +++ b/components/freemodbus/modbus/include/mbport.h @@ -0,0 +1,247 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbport.h,v 1.19 2010/06/06 13:54:40 wolti Exp $ + */ + +#ifndef _MB_PORT_H +#define _MB_PORT_H + +#include "mbconfig.h" // for options + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +#if CONFIG_UART_ISR_IN_IRAM +#define MB_PORT_SERIAL_ISR_FLAG ESP_INTR_FLAG_IRAM +#else +#define MB_PORT_SERIAL_ISR_FLAG ESP_INTR_FLAG_LOWMED +#endif + +#if MB_PORT_TIMER_ISR_IN_IRAM +#define MB_PORT_ISR_ATTR IRAM_ATTR +#define MB_PORT_TIMER_ISR_FLAG ESP_INTR_FLAG_IRAM +#else +#define MB_PORT_ISR_ATTR +#define MB_PORT_TIMER_ISR_FLAG ESP_INTR_FLAG_LOWMED +#endif + +/* ----------------------- Type definitions ---------------------------------*/ + +typedef enum +{ + EV_READY = 0x01, /*!< Startup finished. */ + EV_FRAME_RECEIVED = 0x02, /*!< Frame received. */ + EV_EXECUTE = 0x04, /*!< Execute function. */ + EV_FRAME_SENT = 0x08, /*!< Frame sent. */ + EV_FRAME_TRANSMIT = 0x10 /*!< Frame transmit. */ +} eMBEventType; + +#if MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED +typedef enum { + EV_MASTER_NO_EVENT = 0x0000, + EV_MASTER_READY = 0x0001, /*!< Startup finished. */ + EV_MASTER_FRAME_RECEIVED = 0x0002, /*!< Frame received. */ + EV_MASTER_EXECUTE = 0x0004, /*!< Execute function. */ + EV_MASTER_FRAME_SENT = 0x0008, /*!< Frame sent. */ + EV_MASTER_FRAME_TRANSMIT = 0x0010, /*!< Frame transmission. */ + EV_MASTER_ERROR_PROCESS = 0x0020, /*!< Frame error process. */ + EV_MASTER_PROCESS_SUCCESS = 0x0040, /*!< Request process success. */ + EV_MASTER_ERROR_RESPOND_TIMEOUT = 0x0080, /*!< Request respond timeout. */ + EV_MASTER_ERROR_RECEIVE_DATA = 0x0100, /*!< Request receive data error. */ + EV_MASTER_ERROR_EXECUTE_FUNCTION = 0x0200 /*!< Request execute function error. */ +} eMBMasterEventType; + +typedef enum { + EV_ERROR_INIT, /*!< No error, initial state. */ + EV_ERROR_RESPOND_TIMEOUT, /*!< Slave respond timeout. */ + EV_ERROR_RECEIVE_DATA, /*!< Receive frame data error. */ + EV_ERROR_EXECUTE_FUNCTION, /*!< Execute function error. */ + EV_ERROR_OK /*!< No error, processing completed. */ +} eMBMasterErrorEventType; +#endif + +/*! \ingroup modbus + * \brief Parity used for characters in serial mode. + * + * The parity which should be applied to the characters sent over the serial + * link. Please note that this values are actually passed to the porting + * layer and therefore not all parity modes might be available. + */ +typedef enum +{ + MB_PAR_NONE, /*!< No parity. */ + MB_PAR_ODD, /*!< Odd parity. */ + MB_PAR_EVEN /*!< Even parity. */ +} eMBParity; + +/* ----------------------- Supporting functions -----------------------------*/ +BOOL xMBPortEventInit( void ); + +BOOL xMBPortEventPost( eMBEventType eEvent ); + +BOOL xMBPortEventGet( /*@out@ */ eMBEventType * eEvent ); + +#if MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED +BOOL xMBMasterPortEventInit( void ); + +BOOL xMBMasterPortEventPost( eMBMasterEventType eEvent ); + +BOOL xMBMasterPortEventGet( /*@out@ */ eMBMasterEventType * eEvent ); + +eMBMasterEventType + xMBMasterPortFsmWaitConfirmation( eMBMasterEventType eEventMask, ULONG ulTimeout); + +void vMBMasterOsResInit( void ); + +BOOL xMBMasterRunResTake( LONG time ); + +void vMBMasterRunResRelease( void ); +#endif // MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED +/* ----------------------- Serial port functions ----------------------------*/ + +BOOL xMBPortSerialInit( UCHAR ucPort, ULONG ulBaudRate, + UCHAR ucDataBits, eMBParity eParity ); + +void vMBPortClose( void ); + +void xMBPortSerialClose( void ); + +void vMBPortSerialEnable( BOOL xRxEnable, BOOL xTxEnable ); + +BOOL xMBPortSerialGetByte( CHAR * pucByte ); + +BOOL xMBPortSerialPutByte( CHAR ucByte ); + +#if MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED +BOOL xMBMasterPortSerialInit( UCHAR ucPort, ULONG ulBaudRate, + UCHAR ucDataBits, eMBParity eParity ); + +void vMBMasterPortClose( void ); + +void xMBMasterPortSerialClose( void ); + +void vMBMasterPortSerialEnable( BOOL xRxEnable, BOOL xTxEnable ); + +BOOL xMBMasterPortSerialGetByte( CHAR * pucByte ); + +BOOL xMBMasterPortSerialPutByte( CHAR ucByte ); +#endif + +/* ----------------------- Timers functions ---------------------------------*/ +BOOL xMBPortTimersInit( USHORT usTimeOut50us ); + +void xMBPortTimersClose( void ); + +void vMBPortTimersEnable( void ); + +void vMBPortTimersDisable( void ); + +void vMBPortTimersDelay( USHORT usTimeOutMS ); + +#if MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED +BOOL xMBMasterPortTimersInit( USHORT usTimeOut50us ); + +void xMBMasterPortTimersClose( void ); + +void vMBMasterPortTimersT35Enable( void ); + +void vMBMasterPortTimersConvertDelayEnable( void ); + +void vMBMasterPortTimersRespondTimeoutEnable( void ); + +void vMBMasterPortTimersDisable( void ); + + +/* ----------------- Callback for the master error process ------------------*/ +void vMBMasterErrorCBRespondTimeout( UCHAR ucDestAddress, const UCHAR* pucPDUData, + USHORT ucPDULength ); + +void vMBMasterErrorCBReceiveData( UCHAR ucDestAddress, const UCHAR* pucPDUData, + USHORT ucPDULength ); + +void vMBMasterErrorCBExecuteFunction( UCHAR ucDestAddress, const UCHAR* pucPDUData, + USHORT ucPDULength ); + +void vMBMasterCBRequestSuccess( void ); +#endif +/* ----------------------- Callback for the protocol stack ------------------*/ +/*! + * \brief Callback function for the porting layer when a new byte is + * available. + * + * Depending upon the mode this callback function is used by the RTU or + * ASCII transmission layers. In any case a call to xMBPortSerialGetByte() + * must immediately return a new character. + * + * \return TRUE if a event was posted to the queue because + * a new byte was received. The port implementation should wake up the + * tasks which are currently blocked on the eventqueue. + */ +extern BOOL( *pxMBFrameCBByteReceived ) ( void ); + +extern BOOL( *pxMBFrameCBTransmitterEmpty ) ( void ); + +extern BOOL( *pxMBPortCBTimerExpired ) ( void ); + +#if MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED +extern BOOL( *pxMBMasterFrameCBByteReceived ) ( void ); + +extern BOOL( *pxMBMasterFrameCBTransmitterEmpty ) ( void ); + +extern BOOL( *pxMBMasterPortCBTimerExpired ) ( void ); +#endif +/* ----------------------- TCP port functions -------------------------------*/ +#if MB_TCP_ENABLED +BOOL xMBTCPPortInit( USHORT usTCPPort ); + +void vMBTCPPortClose( void ); + +void vMBTCPPortDisable( void ); + +BOOL xMBTCPPortGetRequest( UCHAR **ppucMBTCPFrame, USHORT * usTCPLength ); + +BOOL xMBTCPPortSendResponse( UCHAR *pucMBTCPFrame, USHORT usTCPLength ); + +#endif + +#if MB_MASTER_TCP_ENABLED +BOOL xMBMasterTCPPortInit( USHORT usTCPPort ); + +void vMBMasterTCPPortClose( void ); + +void vMBMasterTCPPortDisable( void ); + +BOOL xMBMasterTCPPortGetRequest( UCHAR **ppucMBTCPFrame, USHORT * usTCPLength ); + +BOOL xMBMasterTCPPortSendResponse( UCHAR *pucMBTCPFrame, USHORT usTCPLength ); +#endif +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/include/mbproto.h b/components/freemodbus/modbus/include/mbproto.h new file mode 100644 index 00000000..f84cb3ed --- /dev/null +++ b/components/freemodbus/modbus/include/mbproto.h @@ -0,0 +1,83 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbproto.h,v 1.14 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_PROTO_H +#define _MB_PROTO_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif +/* ----------------------- Defines ------------------------------------------*/ +#define MB_ADDRESS_BROADCAST ( 0 ) /*! Modbus broadcast address. */ +#define MB_ADDRESS_MIN ( 1 ) /*! Smallest possible slave address. */ +#define MB_ADDRESS_MAX ( 247 ) /*! Biggest possible slave address. */ +#define MB_FUNC_NONE ( 0 ) +#define MB_FUNC_READ_COILS ( 1 ) +#define MB_FUNC_READ_DISCRETE_INPUTS ( 2 ) +#define MB_FUNC_WRITE_SINGLE_COIL ( 5 ) +#define MB_FUNC_WRITE_MULTIPLE_COILS ( 15 ) +#define MB_FUNC_READ_HOLDING_REGISTER ( 3 ) +#define MB_FUNC_READ_INPUT_REGISTER ( 4 ) +#define MB_FUNC_WRITE_REGISTER ( 6 ) +#define MB_FUNC_WRITE_MULTIPLE_REGISTERS ( 16 ) +#define MB_FUNC_READWRITE_MULTIPLE_REGISTERS ( 23 ) +#define MB_FUNC_DIAG_READ_EXCEPTION ( 7 ) +#define MB_FUNC_DIAG_DIAGNOSTIC ( 8 ) +#define MB_FUNC_DIAG_GET_COM_EVENT_CNT ( 11 ) +#define MB_FUNC_DIAG_GET_COM_EVENT_LOG ( 12 ) +#define MB_FUNC_OTHER_REPORT_SLAVEID ( 17 ) +#define MB_FUNC_ERROR ( 128u ) +/* ----------------------- Type definitions ---------------------------------*/ + typedef enum +{ + MB_EX_NONE = 0x00, + MB_EX_ILLEGAL_FUNCTION = 0x01, + MB_EX_ILLEGAL_DATA_ADDRESS = 0x02, + MB_EX_ILLEGAL_DATA_VALUE = 0x03, + MB_EX_SLAVE_DEVICE_FAILURE = 0x04, + MB_EX_ACKNOWLEDGE = 0x05, + MB_EX_SLAVE_BUSY = 0x06, + MB_EX_MEMORY_PARITY_ERROR = 0x08, + MB_EX_GATEWAY_PATH_FAILED = 0x0A, + MB_EX_GATEWAY_TGT_FAILED = 0x0B +} eMBException; + +typedef eMBException( *pxMBFunctionHandler ) ( UCHAR * pucFrame, USHORT * pusLength ); + +typedef struct +{ + UCHAR ucFunctionCode; + pxMBFunctionHandler pxHandler; +} xMBFunctionHandler; + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/include/mbutils.h b/components/freemodbus/modbus/include/mbutils.h new file mode 100644 index 00000000..61495751 --- /dev/null +++ b/components/freemodbus/modbus/include/mbutils.h @@ -0,0 +1,108 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbutils.h,v 1.5 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_UTILS_H +#define _MB_UTILS_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif +/*! \defgroup modbus_utils Utilities + * + * This module contains some utility functions which can be used by + * the application. It includes some special functions for working with + * bitfields backed by a character array buffer. + * + */ +/*! \addtogroup modbus_utils + * @{ + */ +/*! \brief Function to set bits in a byte buffer. + * + * This function allows the efficient use of an array to implement bitfields. + * The array used for storing the bits must always be a multiple of two + * bytes. Up to eight bits can be set or cleared in one operation. + * + * \param ucByteBuf A buffer where the bit values are stored. Must be a + * multiple of 2 bytes. No length checking is performed and if + * usBitOffset / 8 is greater than the size of the buffer memory contents + * is overwritten. + * \param usBitOffset The starting address of the bits to set. The first + * bit has the offset 0. + * \param ucNBits Number of bits to modify. The value must always be smaller + * than 8. + * \param ucValues Thew new values for the bits. The value for the first bit + * starting at usBitOffset is the LSB of the value + * ucValues + * + * \code + * ucBits[2] = {0, 0}; + * + * // Set bit 4 to 1 (read: set 1 bit starting at bit offset 4 to value 1) + * xMBUtilSetBits( ucBits, 4, 1, 1 ); + * + * // Set bit 7 to 1 and bit 8 to 0. + * xMBUtilSetBits( ucBits, 7, 2, 0x01 ); + * + * // Set bits 8 - 11 to 0x05 and bits 12 - 15 to 0x0A; + * xMBUtilSetBits( ucBits, 8, 8, 0x5A); + * \endcode + */ +void xMBUtilSetBits( UCHAR * ucByteBuf, USHORT usBitOffset, + UCHAR ucNBits, UCHAR ucValues ); + +/*! \brief Function to read bits in a byte buffer. + * + * This function is used to extract up bit values from an array. Up to eight + * bit values can be extracted in one step. + * + * \param ucByteBuf A buffer where the bit values are stored. + * \param usBitOffset The starting address of the bits to set. The first + * bit has the offset 0. + * \param ucNBits Number of bits to modify. The value must always be smaller + * than 8. + * + * \code + * UCHAR ucBits[2] = {0, 0}; + * UCHAR ucResult; + * + * // Extract the bits 3 - 10. + * ucResult = xMBUtilGetBits( ucBits, 3, 8 ); + * \endcode + */ +UCHAR xMBUtilGetBits( UCHAR * ucByteBuf, USHORT usBitOffset, + UCHAR ucNBits ); + +/*! @} */ + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/mb.c b/components/freemodbus/modbus/mb.c new file mode 100644 index 00000000..90fef652 --- /dev/null +++ b/components/freemodbus/modbus/mb.c @@ -0,0 +1,428 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mb.c,v 1.28 2010/06/06 13:54:40 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbconfig.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbfunc.h" +#include "mbport.h" + +#if MB_SLAVE_RTU_ENABLED +#include "mbrtu.h" +#endif +#if MB_SLAVE_ASCII_ENABLED +#include "mbascii.h" +#endif +#if MB_TCP_ENABLED +#include "mbtcp.h" +#endif + +#ifndef MB_PORT_HAS_CLOSE +#define MB_PORT_HAS_CLOSE 0 +#endif + +/* ----------------------- Static variables ---------------------------------*/ + +static UCHAR ucMBAddress; +static eMBMode eMBCurrentMode; + +volatile UCHAR ucMbSlaveBuf[MB_SERIAL_BUF_SIZE]; + +static enum +{ + STATE_ENABLED, + STATE_DISABLED, + STATE_NOT_INITIALIZED +} eMBState = STATE_NOT_INITIALIZED; + +/* Functions pointer which are initialized in eMBInit( ). Depending on the + * mode (RTU or ASCII) the are set to the correct implementations. + */ +static peMBFrameSend peMBFrameSendCur; +static pvMBFrameStart pvMBFrameStartCur; +static pvMBFrameStop pvMBFrameStopCur; +static peMBFrameReceive peMBFrameReceiveCur; +static pvMBFrameClose pvMBFrameCloseCur; + +/* Callback functions required by the porting layer. They are called when + * an external event has happend which includes a timeout or the reception + * or transmission of a character. + */ +BOOL( *pxMBFrameCBByteReceived ) ( void ); +BOOL( *pxMBFrameCBTransmitterEmpty ) ( void ); +BOOL( *pxMBPortCBTimerExpired ) ( void ); +BOOL( *pxMBFrameCBReceiveFSMCur ) ( void ); +BOOL( *pxMBFrameCBTransmitFSMCur ) ( void ); + +/* An array of Modbus functions handlers which associates Modbus function + * codes with implementing functions. + */ +static xMBFunctionHandler xFuncHandlers[MB_FUNC_HANDLERS_MAX] = { +#if MB_FUNC_OTHER_REP_SLAVEID_ENABLED > 0 + {MB_FUNC_OTHER_REPORT_SLAVEID, eMBFuncReportSlaveID}, +#endif +#if MB_FUNC_READ_INPUT_ENABLED > 0 + {MB_FUNC_READ_INPUT_REGISTER, eMBFuncReadInputRegister}, +#endif +#if MB_FUNC_READ_HOLDING_ENABLED > 0 + {MB_FUNC_READ_HOLDING_REGISTER, eMBFuncReadHoldingRegister}, +#endif +#if MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED > 0 + {MB_FUNC_WRITE_MULTIPLE_REGISTERS, eMBFuncWriteMultipleHoldingRegister}, +#endif +#if MB_FUNC_WRITE_HOLDING_ENABLED > 0 + {MB_FUNC_WRITE_REGISTER, eMBFuncWriteHoldingRegister}, +#endif +#if MB_FUNC_READWRITE_HOLDING_ENABLED > 0 + {MB_FUNC_READWRITE_MULTIPLE_REGISTERS, eMBFuncReadWriteMultipleHoldingRegister}, +#endif +#if MB_FUNC_READ_COILS_ENABLED > 0 + {MB_FUNC_READ_COILS, eMBFuncReadCoils}, +#endif +#if MB_FUNC_WRITE_COIL_ENABLED > 0 + {MB_FUNC_WRITE_SINGLE_COIL, eMBFuncWriteCoil}, +#endif +#if MB_FUNC_WRITE_MULTIPLE_COILS_ENABLED > 0 + {MB_FUNC_WRITE_MULTIPLE_COILS, eMBFuncWriteMultipleCoils}, +#endif +#if MB_FUNC_READ_DISCRETE_INPUTS_ENABLED > 0 + {MB_FUNC_READ_DISCRETE_INPUTS, eMBFuncReadDiscreteInputs}, +#endif +}; + +/* ----------------------- Start implementation -----------------------------*/ +eMBErrorCode +eMBInit( eMBMode eMode, UCHAR ucSlaveAddress, UCHAR ucPort, ULONG ulBaudRate, eMBParity eParity ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + /* check preconditions */ + if( ( ucSlaveAddress == MB_ADDRESS_BROADCAST ) || + ( ucSlaveAddress < MB_ADDRESS_MIN ) || ( ucSlaveAddress > MB_ADDRESS_MAX ) ) + { + eStatus = MB_EINVAL; + } + else + { + ucMBAddress = ucSlaveAddress; + + switch ( eMode ) + { +#if MB_SLAVE_RTU_ENABLED > 0 + case MB_RTU: + pvMBFrameStartCur = eMBRTUStart; + pvMBFrameStopCur = eMBRTUStop; + peMBFrameSendCur = eMBRTUSend; + peMBFrameReceiveCur = eMBRTUReceive; + pvMBFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBPortClose : NULL; + pxMBFrameCBByteReceived = xMBRTUReceiveFSM; + pxMBFrameCBTransmitterEmpty = xMBRTUTransmitFSM; + pxMBPortCBTimerExpired = xMBRTUTimerT35Expired; + + eStatus = eMBRTUInit( ucMBAddress, ucPort, ulBaudRate, eParity ); + break; +#endif +#if MB_SLAVE_ASCII_ENABLED > 0 + case MB_ASCII: + pvMBFrameStartCur = eMBASCIIStart; + pvMBFrameStopCur = eMBASCIIStop; + peMBFrameSendCur = eMBASCIISend; + peMBFrameReceiveCur = eMBASCIIReceive; + pvMBFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBPortClose : NULL; + pxMBFrameCBByteReceived = xMBASCIIReceiveFSM; + pxMBFrameCBTransmitterEmpty = xMBASCIITransmitFSM; + pxMBPortCBTimerExpired = xMBASCIITimerT1SExpired; + + eStatus = eMBASCIIInit( ucMBAddress, ucPort, ulBaudRate, eParity ); + break; +#endif + default: + eStatus = MB_EINVAL; + } + + if( eStatus == MB_ENOERR ) + { + if( !xMBPortEventInit( ) ) + { + /* port dependent event module initalization failed. */ + eStatus = MB_EPORTERR; + } + else + { + eMBCurrentMode = eMode; + eMBState = STATE_DISABLED; + } + } + } + return eStatus; +} + +#if MB_TCP_ENABLED > 0 +eMBErrorCode +eMBTCPInit( USHORT ucTCPPort ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + if( ( eStatus = eMBTCPDoInit( ucTCPPort ) ) != MB_ENOERR ) + { + eMBState = STATE_DISABLED; + } + else if( !xMBPortEventInit( ) ) + { + /* Port dependent event module initalization failed. */ + eStatus = MB_EPORTERR; + } + else + { + pvMBFrameStartCur = eMBTCPStart; + pvMBFrameStopCur = eMBTCPStop; + peMBFrameReceiveCur = eMBTCPReceive; + peMBFrameSendCur = eMBTCPSend; + pvMBFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBTCPPortClose : NULL; + ucMBAddress = MB_TCP_PSEUDO_ADDRESS; + eMBCurrentMode = MB_TCP; + eMBState = STATE_DISABLED; + } + return eStatus; +} +#endif + +eMBErrorCode +eMBRegisterCB( UCHAR ucFunctionCode, pxMBFunctionHandler pxHandler ) +{ + int i; + eMBErrorCode eStatus; + + if( ( 0 < ucFunctionCode ) && ( ucFunctionCode <= MB_FUNC_CODE_MAX ) ) + { + ENTER_CRITICAL_SECTION( ); + if( pxHandler != NULL ) + { + for( i = 0; i < MB_FUNC_HANDLERS_MAX; i++ ) + { + if( ( xFuncHandlers[i].pxHandler == NULL ) || + ( xFuncHandlers[i].pxHandler == pxHandler ) ) + { + xFuncHandlers[i].ucFunctionCode = ucFunctionCode; + xFuncHandlers[i].pxHandler = pxHandler; + break; + } + } + eStatus = ( i != MB_FUNC_HANDLERS_MAX ) ? MB_ENOERR : MB_ENORES; + } + else + { + for( i = 0; i < MB_FUNC_HANDLERS_MAX; i++ ) + { + if( xFuncHandlers[i].ucFunctionCode == ucFunctionCode ) + { + xFuncHandlers[i].ucFunctionCode = 0; + xFuncHandlers[i].pxHandler = NULL; + break; + } + } + /* Remove can't fail. */ + eStatus = MB_ENOERR; + } + EXIT_CRITICAL_SECTION( ); + } + else + { + eStatus = MB_EINVAL; + } + return eStatus; +} + + +eMBErrorCode +eMBClose( void ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + if( eMBState == STATE_DISABLED ) + { + if( pvMBFrameCloseCur != NULL ) + { + pvMBFrameCloseCur( ); + } + } + else + { + eStatus = MB_EILLSTATE; + } + return eStatus; +} + +eMBErrorCode +eMBEnable( void ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + if( eMBState == STATE_DISABLED ) + { + /* Activate the protocol stack. */ + pvMBFrameStartCur( ); + eMBState = STATE_ENABLED; + } + else + { + eStatus = MB_EILLSTATE; + } + return eStatus; +} + +eMBErrorCode +eMBDisable( void ) +{ + eMBErrorCode eStatus; + + if( eMBState == STATE_ENABLED ) + { + pvMBFrameStopCur( ); + eMBState = STATE_DISABLED; + eStatus = MB_ENOERR; + } + else if( eMBState == STATE_DISABLED ) + { + eStatus = MB_ENOERR; + } + else + { + eStatus = MB_EILLSTATE; + } + return eStatus; +} + +eMBErrorCode +eMBPoll( void ) +{ + static UCHAR *ucMBFrame = NULL; + static UCHAR ucRcvAddress; + static UCHAR ucFunctionCode; + static USHORT usLength; + static eMBException eException; + + int i; + eMBErrorCode eStatus = MB_ENOERR; + eMBEventType eEvent; + + /* Check if the protocol stack is ready. */ + if( eMBState != STATE_ENABLED ) + { + return MB_EILLSTATE; + } + + /* Check if there is a event available. If not return control to caller. + * Otherwise we will handle the event. */ + if( xMBPortEventGet( &eEvent ) == TRUE ) + { + switch ( eEvent ) + { + case EV_READY: + ESP_LOGD(MB_PORT_TAG, "%s:EV_READY", __func__); + break; + + case EV_FRAME_RECEIVED: + ESP_LOGD(MB_PORT_TAG, "EV_FRAME_RECEIVED"); + eStatus = peMBFrameReceiveCur( &ucRcvAddress, &ucMBFrame, &usLength ); + if( eStatus == MB_ENOERR ) + { + /* Check if the frame is for us. If not ignore the frame. */ + if( ( ucRcvAddress == ucMBAddress ) || ( ucRcvAddress == MB_ADDRESS_BROADCAST ) ) + { + ( void )xMBPortEventPost( EV_EXECUTE ); + ESP_LOG_BUFFER_HEX_LEVEL(MB_PORT_TAG, &ucMBFrame[MB_PDU_FUNC_OFF], usLength, ESP_LOG_DEBUG); + } + } + break; + + case EV_EXECUTE: + if ( !ucMBFrame ) { + return MB_EILLSTATE; + } + ESP_LOGD(MB_PORT_TAG, "%s:EV_EXECUTE", __func__); + ucFunctionCode = ucMBFrame[MB_PDU_FUNC_OFF]; + eException = MB_EX_ILLEGAL_FUNCTION; + for( i = 0; i < MB_FUNC_HANDLERS_MAX; i++ ) + { + /* No more function handlers registered. Abort. */ + if( xFuncHandlers[i].ucFunctionCode == 0 ) + { + break; + } + if( xFuncHandlers[i].ucFunctionCode == ucFunctionCode ) + { + eException = xFuncHandlers[i].pxHandler( ucMBFrame, &usLength ); + break; + } + } + + /* If the request was not sent to the broadcast address we + * return a reply. */ + if( ucRcvAddress != MB_ADDRESS_BROADCAST ) + { + if( eException != MB_EX_NONE ) + { + /* An exception occurred. Build an error frame. */ + usLength = 0; + ucMBFrame[usLength++] = ( UCHAR )( ucFunctionCode | MB_FUNC_ERROR ); + ucMBFrame[usLength++] = eException; + } + if( ( eMBCurrentMode == MB_ASCII ) && MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS ) + { + vMBPortTimersDelay( MB_ASCII_TIMEOUT_WAIT_BEFORE_SEND_MS ); + } + eStatus = peMBFrameSendCur( ucMBAddress, ucMBFrame, usLength ); + } + break; + + case EV_FRAME_TRANSMIT: + ESP_LOGD(MB_PORT_TAG, "%s:EV_FRAME_TRANSMIT", __func__); + break; + + case EV_FRAME_SENT: + ESP_LOGD(MB_PORT_TAG, "%s:EV_FRAME_SENT", __func__); + break; + + default: + break; + } + } + return eStatus; +} diff --git a/components/freemodbus/modbus/mb_m.c b/components/freemodbus/modbus/mb_m.c new file mode 100644 index 00000000..38a031c2 --- /dev/null +++ b/components/freemodbus/modbus/mb_m.c @@ -0,0 +1,547 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (C) 2013 Armink + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbrtu_m.c,v 1.60 2013/08/20 11:18:10 Armink Add Master Functions $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ + +#include "mb_m.h" +#include "mbconfig.h" +#include "mbframe.h" +#include "mbproto.h" +#include "mbfunc.h" + +#include "mbport.h" +#if MB_MASTER_RTU_ENABLED +#include "mbrtu.h" +#endif +#if MB_MASTER_ASCII_ENABLED +#include "mbascii.h" +#endif +#if MB_MASTER_TCP_ENABLED +#include "mbtcp.h" +#include "mbtcp_m.h" +#endif + +#if MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED + +#ifndef MB_PORT_HAS_CLOSE +#define MB_PORT_HAS_CLOSE 1 +#endif + +/* ----------------------- Static variables ---------------------------------*/ + +static UCHAR ucMBMasterDestAddress; +static BOOL xMBRunInMasterMode = FALSE; +static volatile eMBMasterErrorEventType eMBMasterCurErrorType; +static volatile USHORT usMasterSendPDULength; +static volatile eMBMode eMBMasterCurrentMode; + +/*------------------------ Shared variables ---------------------------------*/ + +volatile UCHAR ucMasterSndBuf[MB_SERIAL_BUF_SIZE]; +volatile UCHAR ucMasterRcvBuf[MB_SERIAL_BUF_SIZE]; +volatile eMBMasterTimerMode eMasterCurTimerMode; +volatile BOOL xFrameIsBroadcast = FALSE; + +static enum +{ + STATE_ENABLED, + STATE_DISABLED, + STATE_NOT_INITIALIZED +} eMBState = STATE_NOT_INITIALIZED; + +/* Functions pointer which are initialized in eMBInit( ). Depending on the + * mode (RTU or ASCII) the are set to the correct implementations. + * Using for Modbus Master,Add by Armink 20130813 + */ +static peMBFrameSend peMBMasterFrameSendCur; +static pvMBFrameStart pvMBMasterFrameStartCur; +static pvMBFrameStop pvMBMasterFrameStopCur; +static peMBFrameReceive peMBMasterFrameReceiveCur; +static pvMBFrameClose pvMBMasterFrameCloseCur; + +/* Callback functions required by the porting layer. They are called when + * an external event has happend which includes a timeout or the reception + * or transmission of a character. + * Using for Modbus Master,Add by Armink 20130813 + */ +BOOL( *pxMBMasterFrameCBByteReceived ) ( void ); + +BOOL( *pxMBMasterFrameCBTransmitterEmpty ) ( void ); + +BOOL( *pxMBMasterPortCBTimerExpired ) ( void ); + +BOOL( *pxMBMasterFrameCBReceiveFSMCur ) ( void ); + +BOOL( *pxMBMasterFrameCBTransmitFSMCur ) ( void ); + +/* An array of Modbus functions handlers which associates Modbus function + * codes with implementing functions. + */ +static xMBFunctionHandler xMasterFuncHandlers[MB_FUNC_HANDLERS_MAX] = { +#if MB_FUNC_OTHER_REP_SLAVEID_ENABLED > 0 + {MB_FUNC_OTHER_REPORT_SLAVEID, eMBFuncReportSlaveID}, +#endif +#if MB_FUNC_READ_INPUT_ENABLED > 0 + {MB_FUNC_READ_INPUT_REGISTER, eMBMasterFuncReadInputRegister}, +#endif +#if MB_FUNC_READ_HOLDING_ENABLED > 0 + {MB_FUNC_READ_HOLDING_REGISTER, eMBMasterFuncReadHoldingRegister}, +#endif +#if MB_FUNC_WRITE_MULTIPLE_HOLDING_ENABLED > 0 + {MB_FUNC_WRITE_MULTIPLE_REGISTERS, eMBMasterFuncWriteMultipleHoldingRegister}, +#endif +#if MB_FUNC_WRITE_HOLDING_ENABLED > 0 + {MB_FUNC_WRITE_REGISTER, eMBMasterFuncWriteHoldingRegister}, +#endif +#if MB_FUNC_READWRITE_HOLDING_ENABLED > 0 + {MB_FUNC_READWRITE_MULTIPLE_REGISTERS, eMBMasterFuncReadWriteMultipleHoldingRegister}, +#endif +#if MB_FUNC_READ_COILS_ENABLED > 0 + {MB_FUNC_READ_COILS, eMBMasterFuncReadCoils}, +#endif +#if MB_FUNC_WRITE_COIL_ENABLED > 0 + {MB_FUNC_WRITE_SINGLE_COIL, eMBMasterFuncWriteCoil}, +#endif +#if MB_FUNC_WRITE_MULTIPLE_COILS_ENABLED > 0 + {MB_FUNC_WRITE_MULTIPLE_COILS, eMBMasterFuncWriteMultipleCoils}, +#endif +#if MB_FUNC_READ_DISCRETE_INPUTS_ENABLED > 0 + {MB_FUNC_READ_DISCRETE_INPUTS, eMBMasterFuncReadDiscreteInputs}, +#endif +}; + +/* ----------------------- Start implementation -----------------------------*/ +#if MB_MASTER_TCP_ENABLED > 0 +eMBErrorCode +eMBMasterTCPInit( USHORT ucTCPPort ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + if( ( eStatus = eMBMasterTCPDoInit( ucTCPPort ) ) != MB_ENOERR ) { + eMBState = STATE_DISABLED; + } + else if( !xMBMasterPortEventInit( ) ) { + /* Port dependent event module initialization failed. */ + eStatus = MB_EPORTERR; + } else { + pvMBMasterFrameStartCur = eMBMasterTCPStart; + pvMBMasterFrameStopCur = eMBMasterTCPStop; + peMBMasterFrameReceiveCur = eMBMasterTCPReceive; + peMBMasterFrameSendCur = eMBMasterTCPSend; + pxMBMasterPortCBTimerExpired = xMBMasterTCPTimerExpired; + pvMBMasterFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBMasterTCPPortClose : NULL; + ucMBMasterDestAddress = MB_TCP_PSEUDO_ADDRESS; + eMBMasterCurrentMode = MB_TCP; + eMBState = STATE_DISABLED; + + // initialize the OS resource for modbus master. + vMBMasterOsResInit(); + if( xMBMasterPortTimersInit( MB_MASTER_TIMEOUT_MS_RESPOND * MB_TIMER_TICS_PER_MS ) != TRUE ) + { + eStatus = MB_EPORTERR; + } + + } + return eStatus; +} +#endif + +eMBErrorCode +eMBMasterSerialInit( eMBMode eMode, UCHAR ucPort, ULONG ulBaudRate, eMBParity eParity ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + switch (eMode) + { +#if MB_MASTER_RTU_ENABLED > 0 + case MB_RTU: + pvMBMasterFrameStartCur = eMBMasterRTUStart; + pvMBMasterFrameStopCur = eMBMasterRTUStop; + peMBMasterFrameSendCur = eMBMasterRTUSend; + peMBMasterFrameReceiveCur = eMBMasterRTUReceive; + pvMBMasterFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBMasterPortClose : NULL; + pxMBMasterFrameCBByteReceived = xMBMasterRTUReceiveFSM; + pxMBMasterFrameCBTransmitterEmpty = xMBMasterRTUTransmitFSM; + pxMBMasterPortCBTimerExpired = xMBMasterRTUTimerExpired; + eMBMasterCurrentMode = MB_ASCII; + + eStatus = eMBMasterRTUInit(ucPort, ulBaudRate, eParity); + break; +#endif +#if MB_MASTER_ASCII_ENABLED > 0 + case MB_ASCII: + pvMBMasterFrameStartCur = eMBMasterASCIIStart; + pvMBMasterFrameStopCur = eMBMasterASCIIStop; + peMBMasterFrameSendCur = eMBMasterASCIISend; + peMBMasterFrameReceiveCur = eMBMasterASCIIReceive; + pvMBMasterFrameCloseCur = MB_PORT_HAS_CLOSE ? vMBMasterPortClose : NULL; + pxMBMasterFrameCBByteReceived = xMBMasterASCIIReceiveFSM; + pxMBMasterFrameCBTransmitterEmpty = xMBMasterASCIITransmitFSM; + pxMBMasterPortCBTimerExpired = xMBMasterASCIITimerT1SExpired; + eMBMasterCurrentMode = MB_RTU; + + eStatus = eMBMasterASCIIInit(ucPort, ulBaudRate, eParity ); + break; +#endif + default: + eStatus = MB_EINVAL; + break; + } + + if (eStatus == MB_ENOERR) + { + if (!xMBMasterPortEventInit()) + { + /* port dependent event module initalization failed. */ + eStatus = MB_EPORTERR; + } + else + { + eMBState = STATE_DISABLED; + } + /* initialize the OS resource for modbus master. */ + vMBMasterOsResInit(); + } + return eStatus; +} + +eMBErrorCode +eMBMasterClose( void ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + if( eMBState == STATE_DISABLED ) + { + if( pvMBMasterFrameCloseCur != NULL ) + { + pvMBMasterFrameCloseCur( ); + } + } + else + { + eStatus = MB_EILLSTATE; + } + return eStatus; +} + +eMBErrorCode +eMBMasterEnable( void ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + if( eMBState == STATE_DISABLED ) + { + /* Activate the protocol stack. */ + pvMBMasterFrameStartCur( ); + /* Release the resource, because it created in busy state */ + //vMBMasterRunResRelease( ); + eMBState = STATE_ENABLED; + } + else + { + eStatus = MB_EILLSTATE; + } + return eStatus; +} + +eMBErrorCode +eMBMasterDisable( void ) +{ + eMBErrorCode eStatus; + + if( eMBState == STATE_ENABLED ) + { + pvMBMasterFrameStopCur( ); + eMBState = STATE_DISABLED; + eStatus = MB_ENOERR; + } + else if( eMBState == STATE_DISABLED ) + { + eStatus = MB_ENOERR; + } + else + { + eStatus = MB_EILLSTATE; + } + return eStatus; +} + +eMBErrorCode +eMBMasterPoll( void ) +{ + static UCHAR *ucMBFrame = NULL; + static UCHAR ucRcvAddress; + static UCHAR ucFunctionCode; + static USHORT usLength; + static eMBException eException; + int i; + int j; + eMBErrorCode eStatus = MB_ENOERR; + eMBMasterEventType eEvent; + eMBMasterErrorEventType errorType; + + /* Check if the protocol stack is ready. */ + if( eMBState != STATE_ENABLED ) + { + return MB_EILLSTATE; + } + + /* Check if there is a event available. If not return control to caller. + * Otherwise we will handle the event. */ + if ( xMBMasterPortEventGet( &eEvent ) == TRUE ) + { + // In some cases it is possible that more than one event set + // together (even from one subset mask) than process them consistently + if ( MB_PORT_CHECK_EVENT( eEvent, EV_MASTER_READY ) ) { + ESP_LOGD(MB_PORT_TAG, "%s:EV_MASTER_READY", __func__); + MB_PORT_CLEAR_EVENT( eEvent, EV_MASTER_READY ); + } else if ( MB_PORT_CHECK_EVENT( eEvent, EV_MASTER_FRAME_TRANSMIT ) ) { + ESP_LOGD(MB_PORT_TAG, "%s:EV_MASTER_FRAME_TRANSMIT", __func__); + /* Master is busy now. */ + vMBMasterGetPDUSndBuf( &ucMBFrame ); + ESP_LOG_BUFFER_HEX_LEVEL("POLL transmit buffer", (void*)ucMBFrame, usMBMasterGetPDUSndLength(), ESP_LOG_DEBUG); + eStatus = peMBMasterFrameSendCur( ucMBMasterGetDestAddress(), ucMBFrame, usMBMasterGetPDUSndLength() ); + if (eStatus != MB_ENOERR) + { + ESP_LOGE( MB_PORT_TAG, "%s:Frame send error. %d", __func__, eStatus ); + } + MB_PORT_CLEAR_EVENT( eEvent, EV_MASTER_FRAME_TRANSMIT ); + } else if ( MB_PORT_CHECK_EVENT( eEvent, EV_MASTER_FRAME_SENT ) ) { + ESP_LOGD( MB_PORT_TAG, "%s:EV_MASTER_FRAME_SENT", __func__ ); + ESP_LOG_BUFFER_HEX_LEVEL("POLL sent buffer", (void*)ucMBFrame, usMBMasterGetPDUSndLength(), ESP_LOG_DEBUG); + MB_PORT_CLEAR_EVENT( eEvent, EV_MASTER_FRAME_SENT ); + } else if ( MB_PORT_CHECK_EVENT( eEvent, EV_MASTER_FRAME_RECEIVED ) ) { + eStatus = peMBMasterFrameReceiveCur( &ucRcvAddress, &ucMBFrame, &usLength); + + // Check if the frame is for us. If not ,send an error process event. + if ( ( eStatus == MB_ENOERR ) && ( ( ucRcvAddress == ucMBMasterGetDestAddress() ) + || ( ucRcvAddress == MB_TCP_PSEUDO_ADDRESS ) ) ) + { + ( void ) xMBMasterPortEventPost( EV_MASTER_EXECUTE ); + ESP_LOGD(MB_PORT_TAG, "%s: Packet data received successfully (%u).", __func__, eStatus); + ESP_LOG_BUFFER_HEX_LEVEL("POLL receive buffer", (void*)ucMBFrame, (uint16_t)usLength, ESP_LOG_DEBUG); + ( void ) xMBMasterPortEventPost( EV_MASTER_EXECUTE ); + } + else + { + vMBMasterSetErrorType(EV_ERROR_RECEIVE_DATA); + ( void ) xMBMasterPortEventPost( EV_MASTER_ERROR_PROCESS ); + ESP_LOGD( MB_PORT_TAG, "%s: Packet data receive failed (addr=%u)(%u).", + __func__, ucRcvAddress, eStatus); + } + MB_PORT_CLEAR_EVENT( eEvent, EV_MASTER_FRAME_RECEIVED ); + } else if ( MB_PORT_CHECK_EVENT( eEvent, EV_MASTER_EXECUTE ) ) { + if ( !ucMBFrame ) + { + return MB_EILLSTATE; + } + ESP_LOGD(MB_PORT_TAG, "%s:EV_MASTER_EXECUTE", __func__); + ucFunctionCode = ucMBFrame[MB_PDU_FUNC_OFF]; + eException = MB_EX_ILLEGAL_FUNCTION; + /* If receive frame has exception. The receive function code highest bit is 1.*/ + if (ucFunctionCode & MB_FUNC_ERROR) + { + eException = (eMBException)ucMBFrame[MB_PDU_DATA_OFF]; + } else { + for ( i = 0; i < MB_FUNC_HANDLERS_MAX; i++ ) + { + /* No more function handlers registered. Abort. */ + if (xMasterFuncHandlers[i].ucFunctionCode == 0) + { + break; + } + if (xMasterFuncHandlers[i].ucFunctionCode == ucFunctionCode) + { + vMBMasterSetCBRunInMasterMode(TRUE); + /* If master request is broadcast, + * the master need execute function for all slave. + */ + if ( xMBMasterRequestIsBroadcast() ) + { + usLength = usMBMasterGetPDUSndLength(); + for(j = 1; j <= MB_MASTER_TOTAL_SLAVE_NUM; j++) + { + vMBMasterSetDestAddress(j); + eException = xMasterFuncHandlers[i].pxHandler(ucMBFrame, &usLength); + } + } + else + { + eException = xMasterFuncHandlers[i].pxHandler( ucMBFrame, &usLength ); + } + vMBMasterSetCBRunInMasterMode( FALSE ); + break; + } + } + } + /* If master has exception, will send error process event. Otherwise the master is idle.*/ + if ( eException != MB_EX_NONE ) + { + vMBMasterSetErrorType( EV_ERROR_EXECUTE_FUNCTION ); + ( void ) xMBMasterPortEventPost( EV_MASTER_ERROR_PROCESS ); + } + else + { + if ( eMBMasterGetErrorType( ) == EV_ERROR_INIT ) { + vMBMasterSetErrorType(EV_ERROR_OK); + ESP_LOGD( MB_PORT_TAG, "%s: set event EV_ERROR_OK", __func__ ); + ( void ) xMBMasterPortEventPost( EV_MASTER_ERROR_PROCESS ); + } + } + MB_PORT_CLEAR_EVENT( eEvent, EV_MASTER_EXECUTE ); + } else if ( MB_PORT_CHECK_EVENT( eEvent, EV_MASTER_ERROR_PROCESS ) ) { + ESP_LOGD( MB_PORT_TAG, "%s:EV_MASTER_ERROR_PROCESS", __func__ ); + /* Execute specified error process callback function. */ + errorType = eMBMasterGetErrorType( ); + vMBMasterGetPDUSndBuf( &ucMBFrame ); + switch ( errorType ) + { + case EV_ERROR_RESPOND_TIMEOUT: + vMBMasterErrorCBRespondTimeout( ucMBMasterGetDestAddress( ), + ucMBFrame, usMBMasterGetPDUSndLength( ) ); + break; + case EV_ERROR_RECEIVE_DATA: + vMBMasterErrorCBReceiveData( ucMBMasterGetDestAddress( ), + ucMBFrame, usMBMasterGetPDUSndLength( ) ); + break; + case EV_ERROR_EXECUTE_FUNCTION: + vMBMasterErrorCBExecuteFunction( ucMBMasterGetDestAddress( ), + ucMBFrame, usMBMasterGetPDUSndLength( ) ); + break; + case EV_ERROR_OK: + vMBMasterCBRequestSuccess( ); + break; + default: + ESP_LOGE( MB_PORT_TAG, "%s: incorrect error type = %d.", __func__, errorType); + break; + } + vMBMasterSetErrorType( EV_ERROR_INIT ); + MB_PORT_CLEAR_EVENT( eEvent, EV_MASTER_ERROR_PROCESS ); + vMBMasterRunResRelease( ); + } + if ( eEvent ) { + // Event processing is done, but some poll events still set then + // postpone its processing for next poll cycle (rare case). + ESP_LOGW( MB_PORT_TAG, "%s: Postpone event %x.", __func__, eEvent ); + ( void ) xMBMasterPortEventPost( eEvent ); + } + } else { + // Something went wrong and task unblocked but there are no any correct events set + ESP_LOGE( MB_PORT_TAG, "%s: Unexpected event triggered 0x%02x.", __func__, eEvent ); + eStatus = MB_EILLSTATE; + } + return eStatus; +} + +// Get whether the Modbus Master is run in master mode. +BOOL xMBMasterGetCBRunInMasterMode( void ) +{ + return xMBRunInMasterMode; +} + +// Set whether the Modbus Master is run in master mode. +void vMBMasterSetCBRunInMasterMode( BOOL IsMasterMode ) +{ + xMBRunInMasterMode = IsMasterMode; +} + +// Get Modbus Master send destination address. +UCHAR ucMBMasterGetDestAddress( void ) +{ + return ucMBMasterDestAddress; +} + +// Set Modbus Master send destination address. +void vMBMasterSetDestAddress( UCHAR Address ) +{ + ucMBMasterDestAddress = Address; +} + +// Get Modbus Master current error event type. +eMBMasterErrorEventType inline eMBMasterGetErrorType( void ) +{ + return eMBMasterCurErrorType; +} + +// Set Modbus Master current error event type. +void IRAM_ATTR vMBMasterSetErrorType( eMBMasterErrorEventType errorType ) +{ + eMBMasterCurErrorType = errorType; +} + +/* Get Modbus Master send PDU's buffer address pointer.*/ +void vMBMasterGetPDUSndBuf( UCHAR ** pucFrame ) +{ + *pucFrame = ( UCHAR * ) &ucMasterSndBuf[MB_SER_PDU_PDU_OFF]; +} + +/* Set Modbus Master send PDU's buffer length.*/ +void vMBMasterSetPDUSndLength( USHORT SendPDULength ) +{ + usMasterSendPDULength = SendPDULength; +} + +/* Get Modbus Master send PDU's buffer length.*/ +USHORT usMBMasterGetPDUSndLength( void ) +{ + return usMasterSendPDULength; +} + +/* Set Modbus Master current timer mode.*/ +void vMBMasterSetCurTimerMode( eMBMasterTimerMode eMBTimerMode ) +{ + eMasterCurTimerMode = eMBTimerMode; +} + +/* Get Modbus Master current timer mode.*/ +eMBMasterTimerMode MB_PORT_ISR_ATTR xMBMasterGetCurTimerMode( void ) +{ + return eMasterCurTimerMode; +} + +/* The master request is broadcast? */ +BOOL MB_PORT_ISR_ATTR xMBMasterRequestIsBroadcast( void ) +{ + return xFrameIsBroadcast; +} + +/* The master request is broadcast? */ +void vMBMasterRequestSetType( BOOL xIsBroadcast ){ + xFrameIsBroadcast = xIsBroadcast; +} + +#endif // MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED diff --git a/components/freemodbus/modbus/rtu/mbcrc.c b/components/freemodbus/modbus/rtu/mbcrc.c new file mode 100644 index 00000000..1cd0a6ec --- /dev/null +++ b/components/freemodbus/modbus/rtu/mbcrc.c @@ -0,0 +1,103 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbcrc.c,v 1.7 2007/02/18 23:50:27 wolti Exp $ + */ + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" +#include "mbconfig.h" + +#if MB_MASTER_RTU_ENABLED || MB_SLAVE_RTU_ENABLED + +static const UCHAR aucCRCHi[] = { + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, + 0x00, 0xC1, 0x81, 0x40 +}; + +static const UCHAR aucCRCLo[] = { + 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 0x07, 0xC7, + 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E, + 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, + 0x1B, 0xDB, 0xDA, 0x1A, 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, + 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, + 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32, + 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 0x3C, 0xFC, 0xFD, 0x3D, + 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, + 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, + 0x2D, 0xED, 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, + 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 0x61, 0xA1, + 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4, + 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, + 0x69, 0xA9, 0xA8, 0x68, 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, + 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, + 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0, + 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 0x96, 0x56, 0x57, 0x97, + 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, + 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, + 0x4B, 0x8B, 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, + 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 0x43, 0x83, + 0x41, 0x81, 0x80, 0x40 +}; + +USHORT +usMBCRC16( UCHAR * pucFrame, USHORT usLen ) +{ + UCHAR ucCRCHi = 0xFF; + UCHAR ucCRCLo = 0xFF; + int iIndex; + + while( usLen-- ) + { + iIndex = ucCRCLo ^ *( pucFrame++ ); + ucCRCLo = ( UCHAR )( ucCRCHi ^ aucCRCHi[iIndex] ); + ucCRCHi = aucCRCLo[iIndex]; + } + return ( USHORT )( ucCRCHi << 8 | ucCRCLo ); +} + +#endif diff --git a/components/freemodbus/modbus/rtu/mbcrc.h b/components/freemodbus/modbus/rtu/mbcrc.h new file mode 100644 index 00000000..db227763 --- /dev/null +++ b/components/freemodbus/modbus/rtu/mbcrc.h @@ -0,0 +1,36 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbcrc.h,v 1.5 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_CRC_H +#define _MB_CRC_H + +USHORT usMBCRC16( UCHAR * pucFrame, USHORT usLen ); + +#endif diff --git a/components/freemodbus/modbus/rtu/mbrtu.c b/components/freemodbus/modbus/rtu/mbrtu.c new file mode 100644 index 00000000..066fea3e --- /dev/null +++ b/components/freemodbus/modbus/rtu/mbrtu.c @@ -0,0 +1,350 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbrtu.c,v 1.18 2007/09/12 10:15:56 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbrtu.h" +#include "mbframe.h" + +#include "mbcrc.h" +#include "mbport.h" + +#if MB_SLAVE_RTU_ENABLED > 0 + +/* ----------------------- Type definitions ---------------------------------*/ +typedef enum +{ + STATE_RX_INIT, /*!< Receiver is in initial state. */ + STATE_RX_IDLE, /*!< Receiver is in idle state. */ + STATE_RX_RCV, /*!< Frame is beeing received. */ + STATE_RX_ERROR /*!< If the frame is invalid. */ +} eMBRcvState; + +typedef enum +{ + STATE_TX_IDLE, /*!< Transmitter is in idle state. */ + STATE_TX_XMIT /*!< Transmitter is in transfer state. */ +} eMBSndState; + +/* ----------------------- Shared variables ---------------------------------*/ +extern volatile UCHAR ucMbSlaveBuf[]; + +/* ----------------------- Static variables ---------------------------------*/ +static volatile eMBSndState eSndState; +static volatile eMBRcvState eRcvState; + +static volatile UCHAR *pucSndBufferCur; +static volatile USHORT usSndBufferCount; + +static volatile USHORT usRcvBufferPos; +static volatile UCHAR *ucRTUBuf = ucMbSlaveBuf; + +/* ----------------------- Start implementation -----------------------------*/ +eMBErrorCode +eMBRTUInit( UCHAR ucSlaveAddress, UCHAR ucPort, ULONG ulBaudRate, eMBParity eParity ) +{ + eMBErrorCode eStatus = MB_ENOERR; + ULONG usTimerT35_50us; + + ( void )ucSlaveAddress; + ENTER_CRITICAL_SECTION( ); + + /* Modbus RTU uses 8 Databits. */ + if( xMBPortSerialInit( ucPort, ulBaudRate, 8, eParity ) != TRUE ) + { + eStatus = MB_EPORTERR; + } + else + { + /* If baudrate > 19200 then we should use the fixed timer values + * t35 = 1750us. Otherwise t35 must be 3.5 times the character time. + */ + if( ulBaudRate > 19200 ) + { + usTimerT35_50us = 35; /* 1800us. */ + } + else + { + /* The timer reload value for a character is given by: + * + * ChTimeValue = Ticks_per_1s / ( Baudrate / 11 ) + * = 11 * Ticks_per_1s / Baudrate + * = 220000 / Baudrate + * The reload for t3.5 is 1.5 times this value and similary + * for t3.5. + */ + usTimerT35_50us = ( 7UL * 220000UL ) / ( 2UL * ulBaudRate ); + } + if( xMBPortTimersInit( ( USHORT ) usTimerT35_50us ) != TRUE ) + { + eStatus = MB_EPORTERR; + } + } + EXIT_CRITICAL_SECTION( ); + + return eStatus; +} + +void +eMBRTUStart( void ) +{ + ENTER_CRITICAL_SECTION( ); + /* Initially the receiver is in the state STATE_RX_INIT. we start + * the timer and if no character is received within t3.5 we change + * to STATE_RX_IDLE. This makes sure that we delay startup of the + * modbus protocol stack until the bus is free. + */ + eRcvState = STATE_RX_INIT; + vMBPortSerialEnable( TRUE, FALSE ); + vMBPortTimersEnable( ); + + EXIT_CRITICAL_SECTION( ); +} + +void +eMBRTUStop( void ) +{ + ENTER_CRITICAL_SECTION( ); + vMBPortSerialEnable( FALSE, FALSE ); + vMBPortTimersDisable( ); + EXIT_CRITICAL_SECTION( ); +} + +eMBErrorCode +eMBRTUReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, USHORT * pusLength ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + ENTER_CRITICAL_SECTION( ); + assert( usRcvBufferPos < MB_SER_PDU_SIZE_MAX ); + + /* Length and CRC check */ + if( ( usRcvBufferPos >= MB_SER_PDU_SIZE_MIN ) + && ( usMBCRC16( ( UCHAR * ) ucRTUBuf, usRcvBufferPos ) == 0 ) ) + { + /* Save the address field. All frames are passed to the upper layed + * and the decision if a frame is used is done there. + */ + *pucRcvAddress = ucRTUBuf[MB_SER_PDU_ADDR_OFF]; + + /* Total length of Modbus-PDU is Modbus-Serial-Line-PDU minus + * size of address field and CRC checksum. + */ + *pusLength = ( USHORT )( usRcvBufferPos - MB_SER_PDU_PDU_OFF - MB_SER_PDU_SIZE_CRC ); + + /* Return the start of the Modbus PDU to the caller. */ + *pucFrame = ( UCHAR * ) & ucRTUBuf[MB_SER_PDU_PDU_OFF]; + } + else + { + eStatus = MB_EIO; + } + + EXIT_CRITICAL_SECTION( ); + return eStatus; +} + +eMBErrorCode +eMBRTUSend( UCHAR ucSlaveAddress, const UCHAR * pucFrame, USHORT usLength ) +{ + eMBErrorCode eStatus = MB_ENOERR; + USHORT usCRC16; + + ENTER_CRITICAL_SECTION( ); + + /* Check if the receiver is still in idle state. If not we where to + * slow with processing the received frame and the master sent another + * frame on the network. We have to abort sending the frame. + */ + if( eRcvState == STATE_RX_IDLE ) + { + /* First byte before the Modbus-PDU is the slave address. */ + pucSndBufferCur = ( UCHAR * ) pucFrame - 1; + usSndBufferCount = 1; + + /* Now copy the Modbus-PDU into the Modbus-Serial-Line-PDU. */ + pucSndBufferCur[MB_SER_PDU_ADDR_OFF] = ucSlaveAddress; + usSndBufferCount += usLength; + + /* Calculate CRC16 checksum for Modbus-Serial-Line-PDU. */ + usCRC16 = usMBCRC16( ( UCHAR * ) pucSndBufferCur, usSndBufferCount ); + ucRTUBuf[usSndBufferCount++] = ( UCHAR )( usCRC16 & 0xFF ); + ucRTUBuf[usSndBufferCount++] = ( UCHAR )( usCRC16 >> 8 ); + + /* Activate the transmitter. */ + eSndState = STATE_TX_XMIT; + vMBPortSerialEnable( FALSE, TRUE ); + } + else + { + eStatus = MB_EIO; + } + EXIT_CRITICAL_SECTION( ); + return eStatus; +} + +BOOL +xMBRTUReceiveFSM( void ) +{ + BOOL xStatus = FALSE; + UCHAR ucByte; + + assert( eSndState == STATE_TX_IDLE ); + + /* Always read the character. */ + xStatus = xMBPortSerialGetByte( ( CHAR * ) & ucByte ); + + switch ( eRcvState ) + { + /* If we have received a character in the init state we have to + * wait until the frame is finished. + */ + case STATE_RX_INIT: + vMBPortTimersEnable( ); + break; + + /* In the error state we wait until all characters in the + * damaged frame are transmitted. + */ + case STATE_RX_ERROR: + vMBPortTimersEnable( ); + break; + + /* In the idle state we wait for a new character. If a character + * is received the t1.5 and t3.5 timers are started and the + * receiver is in the state STATE_RX_RCV. + */ + case STATE_RX_IDLE: + usRcvBufferPos = 0; + ucRTUBuf[usRcvBufferPos++] = ucByte; + eRcvState = STATE_RX_RCV; + + /* Enable t3.5 timers. */ + vMBPortTimersEnable( ); + break; + + /* We are currently receiving a frame. Reset the timer after + * every character received. If more than the maximum possible + * number of bytes in a modbus frame is received the frame is + * ignored. + */ + case STATE_RX_RCV: + if( usRcvBufferPos < MB_SER_PDU_SIZE_MAX ) + { + if ( xStatus ) { + ucRTUBuf[usRcvBufferPos++] = ucByte; + } + } + else + { + eRcvState = STATE_RX_ERROR; + } + vMBPortTimersEnable( ); + break; + } + + return xStatus; +} + +BOOL +xMBRTUTransmitFSM( void ) +{ + BOOL xNeedPoll = TRUE; + + assert( eRcvState == STATE_RX_IDLE ); + + switch ( eSndState ) + { + /* We should not get a transmitter event if the transmitter is in + * idle state. */ + case STATE_TX_IDLE: + break; + + case STATE_TX_XMIT: + /* check if we are finished. */ + if( usSndBufferCount != 0 ) + { + xMBPortSerialPutByte( ( CHAR )*pucSndBufferCur ); + pucSndBufferCur++; /* next byte in sendbuffer. */ + usSndBufferCount--; + } + else + { + xMBPortEventPost( EV_FRAME_TRANSMIT ); + xNeedPoll = FALSE; + eSndState = STATE_TX_IDLE; + vMBPortTimersEnable( ); + } + break; + } + + return xNeedPoll; +} + +BOOL MB_PORT_ISR_ATTR +xMBRTUTimerT35Expired( void ) +{ + BOOL xNeedPoll = FALSE; + + switch ( eRcvState ) + { + /* Timer t35 expired. Startup phase is finished. */ + case STATE_RX_INIT: + xNeedPoll = xMBPortEventPost( EV_READY ); + break; + + /* A frame was received and t35 expired. Notify the listener that + * a new frame was received. */ + case STATE_RX_RCV: + xNeedPoll = xMBPortEventPost( EV_FRAME_RECEIVED ); + break; + + /* An error occured while receiving the frame. */ + case STATE_RX_ERROR: + break; + + /* Function called in an illegal state. */ + default: + assert( ( eRcvState == STATE_RX_IDLE ) || ( eRcvState == STATE_RX_ERROR ) ); + } + + vMBPortTimersDisable( ); + eRcvState = STATE_RX_IDLE; + + return xNeedPoll; +} +#endif diff --git a/components/freemodbus/modbus/rtu/mbrtu.h b/components/freemodbus/modbus/rtu/mbrtu.h new file mode 100644 index 00000000..4adf99fa --- /dev/null +++ b/components/freemodbus/modbus/rtu/mbrtu.h @@ -0,0 +1,69 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbrtu.h,v 1.9 2006/12/07 22:10:34 wolti Exp $ + */ +#include "mbconfig.h" + +#ifndef _MB_RTU_H +#define _MB_RTU_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_SER_PDU_SIZE_MIN 4 /*!< Minimum size of a Modbus RTU frame. */ + +#if MB_SLAVE_RTU_ENABLED +eMBErrorCode eMBRTUInit( UCHAR slaveAddress, UCHAR ucPort, ULONG ulBaudRate, + eMBParity eParity ); +void eMBRTUStart( void ); +void eMBRTUStop( void ); +eMBErrorCode eMBRTUReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, USHORT * pusLength ); +eMBErrorCode eMBRTUSend( UCHAR slaveAddress, const UCHAR * pucFrame, USHORT usLength ); +BOOL xMBRTUReceiveFSM( void ); +BOOL xMBRTUTransmitFSM( void ); +BOOL xMBRTUTimerT15Expired( void ); +BOOL xMBRTUTimerT35Expired( void ); +#endif + +#if MB_MASTER_RTU_ENABLED +eMBErrorCode eMBMasterRTUInit( UCHAR ucPort, ULONG ulBaudRate,eMBParity eParity ); +void eMBMasterRTUStart( void ); +void eMBMasterRTUStop( void ); +eMBErrorCode eMBMasterRTUReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, USHORT * pusLength ); +eMBErrorCode eMBMasterRTUSend( UCHAR slaveAddress, const UCHAR * pucFrame, USHORT usLength ); +BOOL xMBMasterRTUReceiveFSM( void ); +BOOL xMBMasterRTUTransmitFSM( void ); +BOOL xMBMasterRTUTimerExpired( void ); +#endif + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/rtu/mbrtu_m.c b/components/freemodbus/modbus/rtu/mbrtu_m.c new file mode 100644 index 00000000..19be4b8a --- /dev/null +++ b/components/freemodbus/modbus/rtu/mbrtu_m.c @@ -0,0 +1,408 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2013 China Beijing Armink + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbrtu_m.c,v 1.60 2013/08/17 11:42:56 Armink Add Master Functions $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" +#include "stdio.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ + +#include "mb_m.h" +#include "mbrtu.h" +#include "mbframe.h" + +#include "mbcrc.h" +#include "mbport.h" + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_RTU_SER_PDU_SIZE_MIN 4 /*!< Minimum size of a Modbus RTU frame. */ + +/* ----------------------- Type definitions ---------------------------------*/ +typedef enum +{ + STATE_M_RX_INIT, /*!< Receiver is in initial state. */ + STATE_M_RX_IDLE, /*!< Receiver is in idle state. */ + STATE_M_RX_RCV, /*!< Frame is beeing received. */ + STATE_M_RX_ERROR, /*!< If the frame is invalid. */ +} eMBMasterRcvState; + +typedef enum +{ + STATE_M_TX_IDLE, /*!< Transmitter is in idle state. */ + STATE_M_TX_XMIT, /*!< Transmitter is in transfer state. */ + STATE_M_TX_XFWR, /*!< Transmitter is in transfer finish and wait receive state. */ +} eMBMasterSndState; + +#if MB_MASTER_RTU_ENABLED > 0 +/*------------------------ Shared variables ---------------------------------*/ +extern volatile UCHAR ucMasterRcvBuf[]; +extern volatile UCHAR ucMasterSndBuf[]; + +/* ----------------------- Static variables ---------------------------------*/ +static volatile eMBMasterSndState eSndState; +static volatile eMBMasterRcvState eRcvState; + +static volatile UCHAR *pucMasterSndBufferCur; +static volatile USHORT usMasterSndBufferCount; +static volatile USHORT usMasterRcvBufferPos; + +static volatile UCHAR *ucMasterRTURcvBuf = ucMasterRcvBuf; +static volatile UCHAR *ucMasterRTUSndBuf = ucMasterSndBuf; + +/* ----------------------- Start implementation -----------------------------*/ +eMBErrorCode +eMBMasterRTUInit(UCHAR ucPort, ULONG ulBaudRate, eMBParity eParity ) +{ + eMBErrorCode eStatus = MB_ENOERR; + ULONG usTimerT35_50us; + + ENTER_CRITICAL_SECTION( ); + + /* Modbus RTU uses 8 Databits. */ + if( xMBMasterPortSerialInit( ucPort, ulBaudRate, 8, eParity ) != TRUE ) + { + eStatus = MB_EPORTERR; + } + else + { + /* If baudrate > 19200 then we should use the fixed timer values + * t35 = 1750us. Otherwise t35 must be 3.5 times the character time. + */ + if( ulBaudRate > 19200 ) + { + usTimerT35_50us = 35; /* 1800us. */ + } + else + { + /* The timer reload value for a character is given by: + * + * ChTimeValue = Ticks_per_1s / ( Baudrate / 11 ) + * = 11 * Ticks_per_1s / Baudrate + * = 220000 / Baudrate + * The reload for t3.5 is 1.5 times this value and similary + * for t3.5. + */ + usTimerT35_50us = ( 7UL * 220000UL ) / ( 2UL * ulBaudRate ); + } + if( xMBMasterPortTimersInit( ( USHORT ) usTimerT35_50us ) != TRUE ) + { + eStatus = MB_EPORTERR; + } + } + EXIT_CRITICAL_SECTION( ); + + return eStatus; +} + +void +eMBMasterRTUStart( void ) +{ + ENTER_CRITICAL_SECTION( ); + /* Initially the receiver is in the state STATE_M_RX_INIT. we start + * the timer and if no character is received within t3.5 we change + * to STATE_M_RX_IDLE. This makes sure that we delay startup of the + * modbus protocol stack until the bus is free. + */ + eRcvState = STATE_M_RX_IDLE; //STATE_M_RX_INIT (We start processing immediately) + vMBMasterPortSerialEnable( TRUE, FALSE ); + vMBMasterPortTimersT35Enable( ); + + EXIT_CRITICAL_SECTION( ); +} + +void +eMBMasterRTUStop( void ) +{ + ENTER_CRITICAL_SECTION( ); + vMBMasterPortSerialEnable( FALSE, FALSE ); + vMBMasterPortTimersDisable( ); + EXIT_CRITICAL_SECTION( ); +} + +eMBErrorCode +eMBMasterRTUReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, USHORT * pusLength ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + ENTER_CRITICAL_SECTION( ); + assert( usMasterRcvBufferPos < MB_SER_PDU_SIZE_MAX ); + + /* Length and CRC check */ + if( ( usMasterRcvBufferPos >= MB_RTU_SER_PDU_SIZE_MIN ) + && ( usMBCRC16( ( UCHAR * ) ucMasterRTURcvBuf, usMasterRcvBufferPos ) == 0 ) ) + { + /* Save the address field. All frames are passed to the upper layed + * and the decision if a frame is used is done there. + */ + *pucRcvAddress = ucMasterRTURcvBuf[MB_SER_PDU_ADDR_OFF]; + + /* Total length of Modbus-PDU is Modbus-Serial-Line-PDU minus + * size of address field and CRC checksum. + */ + *pusLength = ( USHORT )( usMasterRcvBufferPos - MB_SER_PDU_PDU_OFF - MB_SER_PDU_SIZE_CRC ); + + /* Return the start of the Modbus PDU to the caller. */ + *pucFrame = ( UCHAR * ) & ucMasterRTURcvBuf[MB_SER_PDU_PDU_OFF]; + } + else + { + eStatus = MB_EIO; + } + + EXIT_CRITICAL_SECTION( ); + return eStatus; +} + +eMBErrorCode +eMBMasterRTUSend( UCHAR ucSlaveAddress, const UCHAR * pucFrame, USHORT usLength ) +{ + eMBErrorCode eStatus = MB_ENOERR; + USHORT usCRC16; + + if ( ucSlaveAddress > MB_MASTER_TOTAL_SLAVE_NUM ) return MB_EINVAL; + + ENTER_CRITICAL_SECTION( ); + + /* Check if the receiver is still in idle state. If not we where to + * slow with processing the received frame and the master sent another + * frame on the network. We have to abort sending the frame. + */ + if( eRcvState == STATE_M_RX_IDLE ) + { + /* First byte before the Modbus-PDU is the slave address. */ + pucMasterSndBufferCur = ( UCHAR * ) pucFrame - 1; + usMasterSndBufferCount = 1; + + /* Now copy the Modbus-PDU into the Modbus-Serial-Line-PDU. */ + pucMasterSndBufferCur[MB_SER_PDU_ADDR_OFF] = ucSlaveAddress; + usMasterSndBufferCount += usLength; + + /* Calculate CRC16 checksum for Modbus-Serial-Line-PDU. */ + usCRC16 = usMBCRC16( ( UCHAR * ) pucMasterSndBufferCur, usMasterSndBufferCount ); + ucMasterRTUSndBuf[usMasterSndBufferCount++] = ( UCHAR )( usCRC16 & 0xFF ); + ucMasterRTUSndBuf[usMasterSndBufferCount++] = ( UCHAR )( usCRC16 >> 8 ); + + /* Activate the transmitter. */ + eSndState = STATE_M_TX_XMIT; + // The place to enable RS485 driver + vMBMasterPortSerialEnable( FALSE, TRUE ); + } + else + { + eStatus = MB_EIO; + } + EXIT_CRITICAL_SECTION( ); + return eStatus; +} + +BOOL +xMBMasterRTUReceiveFSM( void ) +{ + BOOL xStatus = FALSE; + UCHAR ucByte; + + assert(( eSndState == STATE_M_TX_IDLE ) || ( eSndState == STATE_M_TX_XFWR )); + + /* Always read the character. */ + xStatus = xMBMasterPortSerialGetByte( ( CHAR * ) & ucByte ); + + switch ( eRcvState ) + { + /* If we have received a character in the init state we have to + * wait until the frame is finished. + */ + case STATE_M_RX_INIT: + vMBMasterPortTimersT35Enable( ); + break; + + /* In the error state we wait until all characters in the + * damaged frame are transmitted. + */ + case STATE_M_RX_ERROR: + vMBMasterPortTimersT35Enable( ); + break; + + /* In the idle state we wait for a new character. If a character + * is received the t1.5 and t3.5 timers are started and the + * receiver is in the state STATE_M_RX_RCV and disable early + * the timer of respond timeout . + */ + case STATE_M_RX_IDLE: + /* In time of respond timeout,the receiver receive a frame. + * Disable timer of respond timeout and change the transmiter state to idle. + */ + vMBMasterPortTimersDisable( ); + eSndState = STATE_M_TX_IDLE; + + usMasterRcvBufferPos = 0; + ucMasterRTURcvBuf[usMasterRcvBufferPos++] = ucByte; + eRcvState = STATE_M_RX_RCV; + + /* Enable t3.5 timers. */ + vMBMasterPortTimersT35Enable( ); + break; + + /* We are currently receiving a frame. Reset the timer after + * every character received. If more than the maximum possible + * number of bytes in a modbus frame is received the frame is + * ignored. + */ + case STATE_M_RX_RCV: + if( usMasterRcvBufferPos < MB_SER_PDU_SIZE_MAX ) + { + if ( xStatus ) { + ucMasterRTURcvBuf[usMasterRcvBufferPos++] = ucByte; + } + } + else + { + eRcvState = STATE_M_RX_ERROR; + } + vMBMasterPortTimersT35Enable( ); + break; + } + return xStatus; +} + +BOOL +xMBMasterRTUTransmitFSM( void ) +{ + BOOL xNeedPoll = TRUE; + BOOL xFrameIsBroadcast = FALSE; + + assert( eRcvState == STATE_M_RX_IDLE ); + + switch ( eSndState ) + { + /* We should not get a transmitter event if the transmitter is in + * idle state. */ + case STATE_M_TX_XFWR: + xNeedPoll = FALSE; + break; + + case STATE_M_TX_IDLE: + break; + + case STATE_M_TX_XMIT: + /* check if we are finished. */ + if( usMasterSndBufferCount != 0 ) + { + xMBMasterPortSerialPutByte( ( CHAR )*pucMasterSndBufferCur ); + pucMasterSndBufferCur++; /* next byte in sendbuffer. */ + usMasterSndBufferCount--; + } + else + { + xFrameIsBroadcast = ( ucMasterRTUSndBuf[MB_SER_PDU_ADDR_OFF] == MB_ADDRESS_BROADCAST ) ? TRUE : FALSE; + vMBMasterRequestSetType( xFrameIsBroadcast ); + eSndState = STATE_M_TX_XFWR; + /* If the frame is broadcast ,master will enable timer of convert delay, + * else master will enable timer of respond timeout. */ + if ( xFrameIsBroadcast == TRUE ) + { + vMBMasterPortTimersConvertDelayEnable( ); + } + else + { + vMBMasterPortTimersRespondTimeoutEnable( ); + } + } + break; + } + + return xNeedPoll; +} + +BOOL MB_PORT_ISR_ATTR +xMBMasterRTUTimerExpired(void) +{ + BOOL xNeedPoll = FALSE; + + switch (eRcvState) + { + /* Timer t35 expired. Startup phase is finished. */ + case STATE_M_RX_INIT: + xNeedPoll = xMBMasterPortEventPost(EV_MASTER_READY); + break; + + /* A frame was received and t35 expired. Notify the listener that + * a new frame was received. */ + case STATE_M_RX_RCV: + xNeedPoll = xMBMasterPortEventPost(EV_MASTER_FRAME_RECEIVED); + break; + + /* An error occured while receiving the frame. */ + case STATE_M_RX_ERROR: + vMBMasterSetErrorType(EV_ERROR_RECEIVE_DATA); + xNeedPoll = xMBMasterPortEventPost(EV_MASTER_ERROR_PROCESS); + break; + + /* Function called in an illegal state. */ + default: + assert(eRcvState == STATE_M_RX_IDLE); + break; + } + eRcvState = STATE_M_RX_IDLE; + + switch (eSndState) + { + /* A frame was send finish and convert delay or respond timeout expired. + * If the frame is broadcast,The master will idle,and if the frame is not + * broadcast. Notify the listener process error.*/ + case STATE_M_TX_XFWR: + if ( xMBMasterRequestIsBroadcast( ) == FALSE ) { + vMBMasterSetErrorType(EV_ERROR_RESPOND_TIMEOUT); + xNeedPoll = xMBMasterPortEventPost(EV_MASTER_ERROR_PROCESS); + } + break; + /* Function called in an illegal state. */ + default: + assert( ( eSndState == STATE_M_TX_XMIT ) || ( eSndState == STATE_M_TX_IDLE )); + break; + } + eSndState = STATE_M_TX_IDLE; + + vMBMasterPortTimersDisable( ); + /* If timer mode is convert delay, the master event then turns EV_MASTER_EXECUTE status. */ + if (xMBMasterGetCurTimerMode() == MB_TMODE_CONVERT_DELAY) { + xNeedPoll = xMBMasterPortEventPost(EV_MASTER_EXECUTE); + } + + return xNeedPoll; +} + + +#endif + + diff --git a/components/freemodbus/modbus/tcp/mbtcp.c b/components/freemodbus/modbus/tcp/mbtcp.c new file mode 100644 index 00000000..58542d8c --- /dev/null +++ b/components/freemodbus/modbus/tcp/mbtcp.c @@ -0,0 +1,152 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbtcp.c,v 1.3 2006/12/07 22:10:34 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbconfig.h" +#include "mbtcp.h" +#include "mbframe.h" +#include "mbport.h" + +#if MB_TCP_ENABLED + +/* ----------------------- Defines ------------------------------------------*/ + +/* ----------------------- MBAP Header --------------------------------------*/ +/* + * + * <------------------------ MODBUS TCP/IP ADU(1) -------------------------> + * <----------- MODBUS PDU (1') ----------------> + * +-----------+---------------+------------------------------------------+ + * | TID | PID | Length | UID |Code | Data | + * +-----------+---------------+------------------------------------------+ + * | | | | | + * (2) (3) (4) (5) (6) + * + * (2) ... MB_TCP_TID = 0 (Transaction Identifier - 2 Byte) + * (3) ... MB_TCP_PID = 2 (Protocol Identifier - 2 Byte) + * (4) ... MB_TCP_LEN = 4 (Number of bytes - 2 Byte) + * (5) ... MB_TCP_UID = 6 (Unit Identifier - 1 Byte) + * (6) ... MB_TCP_FUNC = 7 (Modbus Function Code) + * + * (1) ... Modbus TCP/IP Application Data Unit + * (1') ... Modbus Protocol Data Unit + */ + +#define MB_TCP_PROTOCOL_ID 0 /* 0 = Modbus Protocol */ + + +/* ----------------------- Start implementation -----------------------------*/ +eMBErrorCode +eMBTCPDoInit( USHORT ucTCPPort ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + if( xMBTCPPortInit( ucTCPPort ) == FALSE ) + { + eStatus = MB_EPORTERR; + } + return eStatus; +} + +void +eMBTCPStart( void ) +{ +} + +void +eMBTCPStop( void ) +{ + /* Make sure that no more clients are connected. */ + vMBTCPPortDisable( ); +} + +eMBErrorCode +eMBTCPReceive( UCHAR * pucRcvAddress, UCHAR ** ppucFrame, USHORT * pusLength ) +{ + eMBErrorCode eStatus = MB_EIO; + UCHAR *pucMBTCPFrame; + USHORT usLength; + USHORT usPID; + + if( xMBTCPPortGetRequest( &pucMBTCPFrame, &usLength ) != FALSE ) + { + usPID = pucMBTCPFrame[MB_TCP_PID] << 8U; + usPID |= pucMBTCPFrame[MB_TCP_PID + 1]; + + if( usPID == MB_TCP_PROTOCOL_ID ) + { + *ppucFrame = &pucMBTCPFrame[MB_TCP_FUNC]; + *pusLength = usLength - MB_TCP_FUNC; + eStatus = MB_ENOERR; + + /* Modbus TCP does not use any addresses. Fake the source address such + * that the processing part deals with this frame. + */ + *pucRcvAddress = MB_TCP_PSEUDO_ADDRESS; + } + } + else + { + eStatus = MB_EIO; + } + return eStatus; +} + +eMBErrorCode +eMBTCPSend( UCHAR _unused, const UCHAR * pucFrame, USHORT usLength ) +{ + eMBErrorCode eStatus = MB_ENOERR; + UCHAR *pucMBTCPFrame = ( UCHAR * ) pucFrame - MB_TCP_FUNC; + USHORT usTCPLength = usLength + MB_TCP_FUNC; + + /* The MBAP header is already initialized because the caller calls this + * function with the buffer returned by the previous call. Therefore we + * only have to update the length in the header. Note that the length + * header includes the size of the Modbus PDU and the UID Byte. Therefore + * the length is usLength plus one. + */ + pucMBTCPFrame[MB_TCP_LEN] = ( usLength + 1 ) >> 8U; + pucMBTCPFrame[MB_TCP_LEN + 1] = ( usLength + 1 ) & 0xFF; + if( xMBTCPPortSendResponse( pucMBTCPFrame, usTCPLength ) == FALSE ) + { + eStatus = MB_EIO; + } + return eStatus; +} + +#endif diff --git a/components/freemodbus/modbus/tcp/mbtcp.h b/components/freemodbus/modbus/tcp/mbtcp.h new file mode 100644 index 00000000..6e55718c --- /dev/null +++ b/components/freemodbus/modbus/tcp/mbtcp.h @@ -0,0 +1,56 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbtcp.h,v 1.2 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_TCP_H +#define _MB_TCP_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +/* ----------------------- Defines ------------------------------------------*/ + +#if MB_TCP_ENABLED + +/* ----------------------- Function prototypes ------------------------------*/ +eMBErrorCode eMBTCPDoInit( USHORT ucTCPPort ); +void eMBTCPStart( void ); +void eMBTCPStop( void ); +eMBErrorCode eMBTCPReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, + USHORT * pusLength ); +eMBErrorCode eMBTCPSend( UCHAR _unused, const UCHAR * pucFrame, + USHORT usLength ); + +#endif + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/modbus/tcp/mbtcp_m.c b/components/freemodbus/modbus/tcp/mbtcp_m.c new file mode 100644 index 00000000..419710de --- /dev/null +++ b/components/freemodbus/modbus/tcp/mbtcp_m.c @@ -0,0 +1,152 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbtcp.c,v 1.3 2006/12/07 22:10:34 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include "stdlib.h" +#include "string.h" + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbconfig.h" +#include "mbtcp_m.h" +#include "mbframe.h" +#include "mbport.h" + +#if MB_MASTER_TCP_ENABLED + +/* ----------------------- Defines ------------------------------------------*/ + +/* ----------------------- MBAP Header --------------------------------------*/ +/* + * + * <------------------------ MODBUS TCP/IP ADU(1) -------------------------> + * <----------- MODBUS PDU (1') ----------------> + * +-----------+---------------+------------------------------------------+ + * | TID | PID | Length | UID |Code | Data | + * +-----------+---------------+------------------------------------------+ + * | | | | | + * (2) (3) (4) (5) (6) + * + * (2) ... MB_TCP_TID = 0 (Transaction Identifier - 2 Byte) + * (3) ... MB_TCP_PID = 2 (Protocol Identifier - 2 Byte) + * (4) ... MB_TCP_LEN = 4 (Number of bytes - 2 Byte) + * (5) ... MB_TCP_UID = 6 (Unit Identifier - 1 Byte) + * (6) ... MB_TCP_FUNC = 7 (Modbus Function Code) + * + * (1) ... Modbus TCP/IP Application Data Unit + * (1') ... Modbus Protocol Data Unit + */ + +#define MB_TCP_PROTOCOL_ID 0 /* 0 = Modbus Protocol */ + + +/* ----------------------- Start implementation -----------------------------*/ +eMBErrorCode +eMBMasterTCPDoInit( USHORT ucTCPPort ) +{ + eMBErrorCode eStatus = MB_ENOERR; + + if( xMBMasterTCPPortInit( ucTCPPort ) == FALSE ) + { + eStatus = MB_EPORTERR; + } + return eStatus; +} + +void +eMBMasterTCPStart( void ) +{ +} + +void +eMBMasterTCPStop( void ) +{ + /* Make sure that no more clients are connected. */ + vMBMasterTCPPortDisable( ); +} + +eMBErrorCode +eMBMasterTCPReceive( UCHAR * pucRcvAddress, UCHAR ** ppucFrame, USHORT * pusLength ) +{ + eMBErrorCode eStatus = MB_EIO; + UCHAR *pucMBTCPFrame; + USHORT usLength; + USHORT usPID; + + if( xMBMasterTCPPortGetRequest( &pucMBTCPFrame, &usLength ) != FALSE ) + { + usPID = pucMBTCPFrame[MB_TCP_PID] << 8U; + usPID |= pucMBTCPFrame[MB_TCP_PID + 1]; + + if( usPID == MB_TCP_PROTOCOL_ID ) + { + *ppucFrame = &pucMBTCPFrame[MB_TCP_FUNC]; + *pusLength = usLength - MB_TCP_FUNC; + eStatus = MB_ENOERR; + + /* Modbus TCP does not use any addresses. Fake the source address such + * that the processing part deals with this frame. + */ + *pucRcvAddress = MB_TCP_PSEUDO_ADDRESS; + } + } + else + { + eStatus = MB_EIO; + } + return eStatus; +} + +eMBErrorCode +eMBMasterTCPSend( UCHAR _unused, const UCHAR * pucFrame, USHORT usLength ) +{ + eMBErrorCode eStatus = MB_ENOERR; + UCHAR *pucMBTCPFrame = ( UCHAR * ) pucFrame - MB_TCP_FUNC; + USHORT usTCPLength = usLength + MB_TCP_FUNC; + + /* The MBAP header is already initialized because the caller calls this + * function with the buffer returned by the previous call. Therefore we + * only have to update the length in the header. Note that the length + * header includes the size of the Modbus PDU and the UID Byte. Therefore + * the length is usLength plus one. + */ + pucMBTCPFrame[MB_TCP_LEN] = ( usLength + 1 ) >> 8U; + pucMBTCPFrame[MB_TCP_LEN + 1] = ( usLength + 1 ) & 0xFF; + if( xMBMasterTCPPortSendResponse( pucMBTCPFrame, usTCPLength ) == FALSE ) + { + eStatus = MB_EIO; + } + return eStatus; +} + +#endif diff --git a/components/freemodbus/modbus/tcp/mbtcp_m.h b/components/freemodbus/modbus/tcp/mbtcp_m.h new file mode 100644 index 00000000..3445ca9e --- /dev/null +++ b/components/freemodbus/modbus/tcp/mbtcp_m.h @@ -0,0 +1,57 @@ +/* + * FreeModbus Libary: A portable Modbus implementation for Modbus ASCII/RTU. + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: mbtcp.h,v 1.2 2006/12/07 22:10:34 wolti Exp $ + */ + +#ifndef _MB_TCP_M_H +#define _MB_TCP_M_H + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +/* ----------------------- Defines ------------------------------------------*/ + +#if MB_MASTER_TCP_ENABLED + +/* ----------------------- Function prototypes ------------------------------*/ +eMBErrorCode eMBMasterTCPDoInit( USHORT ucTCPPort ); +void eMBMasterTCPStart( void ); +void eMBMasterTCPStop( void ); +eMBErrorCode eMBMasterTCPReceive( UCHAR * pucRcvAddress, UCHAR ** pucFrame, + USHORT * pusLength ); +eMBErrorCode eMBMasterTCPSend( UCHAR _unused, const UCHAR * pucFrame, + USHORT usLength ); +BOOL xMBMasterTCPTimerExpired(void); + +#endif + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/port/port.c b/components/freemodbus/port/port.c new file mode 100644 index 00000000..dd9063f2 --- /dev/null +++ b/components/freemodbus/port/port.c @@ -0,0 +1,146 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * FreeModbus Libary: RT-Thread Port + * Copyright (C) 2013 Armink + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * File: $Id: port.c,v 1.60 2015/02/01 9:18:05 Armink $ + */ + +/* ----------------------- System includes --------------------------------*/ + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "freertos/FreeRTOS.h" +#include "sys/lock.h" +#include "port.h" + +/* ----------------------- Variables ----------------------------------------*/ +static _lock_t s_port_lock; +static UCHAR ucPortMode = 0; + +/* ----------------------- Start implementation -----------------------------*/ +inline void +vMBPortEnterCritical(void) +{ + _lock_acquire(&s_port_lock); +} + +inline void +vMBPortExitCritical(void) +{ + _lock_release(&s_port_lock); +} + +UCHAR +ucMBPortGetMode( void ) +{ + return ucPortMode; +} + +void +vMBPortSetMode( UCHAR ucMode ) +{ + ENTER_CRITICAL_SECTION(); + ucPortMode = ucMode; + EXIT_CRITICAL_SECTION(); +} + +#if MB_TCP_DEBUG + +// This function is kept to realize legacy freemodbus frame logging functionality +void +prvvMBTCPLogFrame( const CHAR * pucMsg, UCHAR * pucFrame, USHORT usFrameLen ) +{ + int i; + int res = 0; + int iBufPos = 0; + size_t iBufLeft = MB_TCP_FRAME_LOG_BUFSIZE; + static CHAR arcBuffer[MB_TCP_FRAME_LOG_BUFSIZE]; + + assert( pucFrame != NULL ); + + for ( i = 0; i < usFrameLen; i++ ) { + // Print some additional frame information. + switch ( i ) + { + case 0: + // TID = Transaction Identifier. + res = snprintf( &arcBuffer[iBufPos], iBufLeft, "| TID = " ); + break; + case 2: + // PID = Protocol Identifier. + res = snprintf( &arcBuffer[iBufPos], iBufLeft, " | PID = " ); + break; + case 4: + // Length + res = snprintf( &arcBuffer[iBufPos], iBufLeft, " | LEN = " ); + break; + case 6: + // UID = Unit Identifier. + res = snprintf( &arcBuffer[iBufPos], iBufLeft, " | UID = " ); + break; + case 7: + // MB Function Code. + res = snprintf( &arcBuffer[iBufPos], iBufLeft, " | FUNC = " ); + break; + case 8: + // MB PDU rest. + res = snprintf( &arcBuffer[iBufPos], iBufLeft, " | DATA = " ); + break; + default: + res = 0; + break; + } + if( res == -1 ) { + break; + } + else { + iBufPos += res; + iBufLeft -= res; + } + + // Print the data. + res = snprintf( &arcBuffer[iBufPos], iBufLeft, "%02X", pucFrame[i] ); + if( res == -1 ) { + break; + } else { + iBufPos += res; + iBufLeft -= res; + } + } + + if( res != -1 ) { + // Append an end of frame string. + res = snprintf( &arcBuffer[iBufPos], iBufLeft, " |" ); + if( res != -1 ) { + ESP_LOGD(pucMsg, "%s", arcBuffer); + } + } +} +#endif diff --git a/components/freemodbus/port/port.h b/components/freemodbus/port/port.h new file mode 100644 index 00000000..1924e67d --- /dev/null +++ b/components/freemodbus/port/port.h @@ -0,0 +1,145 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef PORT_COMMON_H_ +#define PORT_COMMON_H_ + +#include "freertos/FreeRTOS.h" +#include "freertos/xtensa_api.h" +#include "esp_log.h" // for ESP_LOGE macro +#include "mbconfig.h" + +#define INLINE inline +#define PR_BEGIN_EXTERN_C extern "C" { +#define PR_END_EXTERN_C } + +#define MB_PORT_TAG "MB_PORT_COMMON" + +#define MB_BAUD_RATE_DEFAULT (115200) +#define MB_QUEUE_LENGTH (CONFIG_FMB_QUEUE_LENGTH) + +#define MB_SERIAL_TASK_PRIO (CONFIG_FMB_PORT_TASK_PRIO) +#define MB_SERIAL_TASK_STACK_SIZE (CONFIG_FMB_PORT_TASK_STACK_SIZE) +#define MB_SERIAL_TOUT (3) // 3.5*8 = 28 ticks, TOUT=3 -> ~24..33 ticks + +// Set buffer size for transmission +#define MB_SERIAL_BUF_SIZE (CONFIG_FMB_SERIAL_BUF_SIZE) + +// common definitions for serial port implementations +#define MB_SERIAL_TX_TOUT_MS (100) +#define MB_SERIAL_TX_TOUT_TICKS (pdMS_TO_TICKS(MB_SERIAL_TX_TOUT_MS)) // timeout for transmission +#define MB_SERIAL_RX_TOUT_MS (1) +#define MB_SERIAL_RX_TOUT_TICKS (pdMS_TO_TICKS(MB_SERIAL_RX_TOUT_MS)) // timeout for receive + +#define MB_SERIAL_RESP_LEN_MIN (4) + +// Common definitions for TCP port +#define MB_TCP_BUF_SIZE (256 + 7) // Must hold a complete Modbus TCP frame. +#define MB_TCP_DEFAULT_PORT (CONFIG_FMB_TCP_PORT_DEFAULT) +#define MB_TCP_STACK_SIZE (CONFIG_FMB_PORT_TASK_STACK_SIZE) +#define MB_TCP_TASK_PRIO (CONFIG_FMB_PORT_TASK_PRIO) + +#define MB_TCP_READ_TIMEOUT_MS (100) // read timeout in mS +#define MB_TCP_READ_TIMEOUT (pdMS_TO_TICKS(MB_TCP_READ_TIMEOUT_MS)) +#define MB_TCP_SEND_TIMEOUT_MS (500) // send event timeout in mS +#define MB_TCP_SEND_TIMEOUT (pdMS_TO_TICKS(MB_TCP_SEND_TIMEOUT_MS)) +#define MB_TCP_PORT_MAX_CONN (CONFIG_FMB_TCP_PORT_MAX_CONN) + +#define MB_TCP_FRAME_LOG_BUFSIZE (256) + +// Define number of timer reloads per 1 mS +#define MB_TIMER_TICS_PER_MS (20UL) + +#define MB_TCP_DEBUG (LOG_LOCAL_LEVEL >= ESP_LOG_DEBUG) // Enable legacy debug output in TCP module. + +#define MB_TCP_GET_FIELD(buffer, field) ((USHORT)((buffer[field] << 8U) | buffer[field + 1])) + +#define MB_PORT_CHECK(a, ret_val, str, ...) \ + if (!(a)) { \ + ESP_LOGE(MB_PORT_TAG, "%s(%u): " str, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ + return ret_val; \ + } + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif /* __cplusplus */ + +#ifndef TRUE +#define TRUE 1 +#endif + +#ifndef FALSE +#define FALSE 0 +#endif + +typedef char BOOL; + +typedef unsigned char UCHAR; +typedef char CHAR; + +typedef unsigned short USHORT; +typedef short SHORT; + +typedef unsigned long ULONG; +typedef long LONG; + +#if MB_TCP_DEBUG +typedef enum +{ + MB_LOG_DEBUG, + MB_LOG_INFO, + MB_LOG_WARN, + MB_LOG_ERROR +} eMBPortLogLevel; +#endif + +typedef enum +{ + MB_PROTO_TCP, + MB_PROTO_UDP, +} eMBPortProto; + +typedef enum { + MB_PORT_IPV4 = 0, /*!< TCP IPV4 addressing */ + MB_PORT_IPV6 = 1 /*!< TCP IPV6 addressing */ +} eMBPortIpVer; + +void vMBPortEnterCritical(void); +void vMBPortExitCritical(void); + +#define ENTER_CRITICAL_SECTION( ) { ESP_EARLY_LOGD(MB_PORT_TAG,"%s: Port enter critical.", __func__); \ + vMBPortEnterCritical(); } + +#define EXIT_CRITICAL_SECTION( ) { vMBPortExitCritical(); \ + ESP_EARLY_LOGD(MB_PORT_TAG,"%s: Port exit critical", __func__); } + +#define MB_PORT_CHECK_EVENT( event, mask ) ( event & mask ) +#define MB_PORT_CLEAR_EVENT( event, mask ) do { event &= ~mask; } while(0) + +// Legacy Modbus logging function +#if MB_TCP_DEBUG +void vMBPortLog( eMBPortLogLevel eLevel, const CHAR * szModule, + const CHAR * szFmt, ... ); +void prvvMBTCPLogFrame( const CHAR * pucMsg, UCHAR * pucFrame, USHORT usFrameLen ); +#endif + +void vMBPortSetMode( UCHAR ucMode ); +UCHAR ucMBPortGetMode( void ); + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif /* __cplusplus */ + +#endif /* PORT_COMMON_H_ */ diff --git a/components/freemodbus/port/portevent.c b/components/freemodbus/port/portevent.c new file mode 100644 index 00000000..42dde249 --- /dev/null +++ b/components/freemodbus/port/portevent.c @@ -0,0 +1,132 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * FreeModbus Libary: ESP32 Port Demo Application + * Copyright (C) 2010 Christian Walter + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * IF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: portevent.c,v 1.1 2010/06/06 13:07:20 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include +#include +#include + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbport.h" +#include "port.h" +#include "sdkconfig.h" +#include "port_serial_slave.h" +/* ----------------------- Variables ----------------------------------------*/ +static xQueueHandle xQueueHdl; + +#define MB_EVENT_QUEUE_SIZE (6) +#define MB_EVENT_QUEUE_TIMEOUT (pdMS_TO_TICKS(CONFIG_FMB_EVENT_QUEUE_TIMEOUT)) + +/* ----------------------- Start implementation -----------------------------*/ +BOOL +xMBPortEventInit( void ) +{ + BOOL bStatus = FALSE; + if((xQueueHdl = xQueueCreate(MB_EVENT_QUEUE_SIZE, sizeof(eMBEventType))) != NULL) + { + vQueueAddToRegistry(xQueueHdl, "MbPortEventQueue"); + bStatus = TRUE; + } + return bStatus; +} + +void +vMBPortEventClose( void ) +{ + if(xQueueHdl != NULL) + { + vQueueDelete(xQueueHdl); + xQueueHdl = NULL; + } +} + +BOOL MB_PORT_ISR_ATTR +xMBPortEventPost( eMBEventType eEvent ) +{ + BaseType_t xStatus, xHigherPriorityTaskWoken = pdFALSE; + assert(xQueueHdl != NULL); + + if( (BOOL)xPortInIsrContext() == TRUE ) + { + xStatus = xQueueSendFromISR(xQueueHdl, (const void*)&eEvent, &xHigherPriorityTaskWoken); + if ( xHigherPriorityTaskWoken ) + { + portYIELD_FROM_ISR(); + } + if (xStatus != pdTRUE) { + ESP_EARLY_LOGV(MB_PORT_TAG, "%s: Post message failure = %d.", __func__, xStatus); + return FALSE; + } + } + else + { + xStatus = xQueueSend(xQueueHdl, (const void*)&eEvent, MB_EVENT_QUEUE_TIMEOUT); + MB_PORT_CHECK((xStatus == pdTRUE), FALSE, "%s: Post message failure.", __func__); + } + return TRUE; +} + +BOOL +xMBPortEventGet(eMBEventType * peEvent) +{ + assert(xQueueHdl != NULL); + BOOL xEventHappened = FALSE; + + if (xQueueReceive(xQueueHdl, peEvent, portMAX_DELAY) == pdTRUE) { + xEventHappened = TRUE; + } + return xEventHappened; +} + +xQueueHandle +xMBPortEventGetHandle(void) +{ + if(xQueueHdl != NULL) + { + return xQueueHdl; + } + return NULL; +} + diff --git a/components/freemodbus/port/portevent_m.c b/components/freemodbus/port/portevent_m.c new file mode 100644 index 00000000..81c3c3b6 --- /dev/null +++ b/components/freemodbus/port/portevent_m.c @@ -0,0 +1,317 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * FreeModbus Libary: ESP32 Port Demo Application + * Copyright (C) 2013 Armink + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * File: $Id: portevent.c v 1.60 2013/08/13 15:07:05 Armink add Master Functions$ + */ + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb_m.h" +#include "mbport.h" +#include "mbconfig.h" + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/event_groups.h" +#include "port.h" +#include "mbport.h" +#include "freertos/semphr.h" +#include "port_serial_master.h" + +#if MB_MASTER_RTU_ENABLED || MB_MASTER_ASCII_ENABLED || MB_MASTER_TCP_ENABLED +/* ----------------------- Defines ------------------------------------------*/ +// Event bit mask for xMBMasterPortEventGet() +#define MB_EVENT_POLL_MASK (EventBits_t)( EV_MASTER_READY | \ + EV_MASTER_FRAME_RECEIVED | \ + EV_MASTER_EXECUTE | \ + EV_MASTER_FRAME_SENT | \ + EV_MASTER_FRAME_TRANSMIT | \ + EV_MASTER_ERROR_PROCESS ) + +// Event bit mask for eMBMasterWaitRequestFinish() +#define MB_EVENT_REQ_MASK (EventBits_t)( EV_MASTER_PROCESS_SUCCESS | \ + EV_MASTER_ERROR_RESPOND_TIMEOUT | \ + EV_MASTER_ERROR_RECEIVE_DATA | \ + EV_MASTER_ERROR_EXECUTE_FUNCTION ) + +#define MB_EVENT_RESOURCE (EventBits_t)( 0x0080 ) + +/* ----------------------- Variables ----------------------------------------*/ +static EventGroupHandle_t xResourceMasterHdl; +static EventGroupHandle_t xEventGroupMasterHdl; +static EventGroupHandle_t xEventGroupMasterConfirmHdl; + +/* ----------------------- Start implementation -----------------------------*/ + +BOOL +xMBMasterPortEventInit( void ) +{ + xEventGroupMasterHdl = xEventGroupCreate(); + xEventGroupMasterConfirmHdl = xEventGroupCreate(); + MB_PORT_CHECK((xEventGroupMasterHdl != NULL) && (xEventGroupMasterConfirmHdl != NULL), + FALSE, "mb stack event group creation error."); + return TRUE; +} + +BOOL MB_PORT_ISR_ATTR +xMBMasterPortEventPost( eMBMasterEventType eEvent ) +{ + BOOL bStatus = FALSE; + eMBMasterEventType eTempEvent = eEvent; + + if( (BOOL)xPortInIsrContext() == TRUE ) + { + BaseType_t xHigherPriorityTaskWoken = pdFALSE; + BaseType_t xResult = xEventGroupSetBitsFromISR( xEventGroupMasterHdl, + (EventBits_t) eTempEvent, + &xHigherPriorityTaskWoken ); + // Was the message posted successfully? + if( xResult == pdPASS ) { + // If xHigherPriorityTaskWoken is now set to pdTRUE + // then a context switch should be requested. + if (xHigherPriorityTaskWoken) portYIELD_FROM_ISR(); + bStatus = TRUE; + } else { + bStatus = FALSE; + } + } + else + { + // Set event bits if the function is called from task + // The return result is not checked here because + // It might be that event bit was cleared automatically as a + // task that was waiting for the bit was removed from the Blocked state. + (void) xEventGroupSetBits( xEventGroupMasterHdl, (EventBits_t)eTempEvent ); + bStatus = TRUE; + } + return bStatus; +} + +eMBMasterEventType +xMBMasterPortFsmWaitConfirmation( eMBMasterEventType eEventMask, ULONG ulTimeout) +{ + EventBits_t uxBits; + uxBits = xEventGroupWaitBits( xEventGroupMasterConfirmHdl, // The event group being tested. + eEventMask, // The bits within the event group to wait for. + pdFALSE, // Keep masked bits. + pdFALSE, // Don't wait for both bits, either bit will do. + ulTimeout); // Wait timeout for either bit to be set. + if (ulTimeout && uxBits) { + // Clear confirmation events that where set in the mask + xEventGroupClearBits( xEventGroupMasterConfirmHdl, (uxBits & eEventMask) ); + } + return (eMBMasterEventType)(uxBits & eEventMask); +} + +BOOL +xMBMasterPortEventGet( eMBMasterEventType* eEvent ) +{ + EventBits_t uxBits; + BOOL xEventHappened = FALSE; + uxBits = xEventGroupWaitBits( xEventGroupMasterHdl, // The event group being tested. + MB_EVENT_POLL_MASK, // The bits within the event group to wait for. + pdTRUE, // Masked bits should be cleared before returning. + pdFALSE, // Don't wait for both bits, either bit will do. + portMAX_DELAY); // Wait forever for either bit to be set. + // Check if poll event is correct + if (MB_PORT_CHECK_EVENT(uxBits, MB_EVENT_POLL_MASK)) { + *eEvent = (eMBMasterEventType)(uxBits & MB_EVENT_POLL_MASK); + // Set event bits in confirmation group (for synchronization with port task) + xEventGroupSetBits( xEventGroupMasterConfirmHdl, *eEvent ); + xEventHappened = TRUE; + } else { + ESP_LOGE(MB_PORT_TAG,"%s: Incorrect event triggered = %d.", __func__, uxBits); + *eEvent = (eMBMasterEventType)uxBits; + xEventHappened = FALSE; + } + return xEventHappened; +} + +// This function is initialize the OS resource for modbus master. +void vMBMasterOsResInit( void ) +{ + xResourceMasterHdl = xEventGroupCreate(); + xEventGroupSetBits(xResourceMasterHdl, MB_EVENT_RESOURCE); + MB_PORT_CHECK((xResourceMasterHdl != NULL), ; , "Resource create error."); +} + +/** + * This function is take Mobus Master running resource. + * Note:The resource is define by Operating System. + * + * @param lTimeOut the waiting time. + * + * @return resource take result + */ +BOOL xMBMasterRunResTake( LONG lTimeOut ) +{ + EventBits_t uxBits; + uxBits = xEventGroupWaitBits( xResourceMasterHdl, // The event group being tested. + MB_EVENT_RESOURCE, // The bits within the event group to wait for. + pdTRUE, // Masked bits should be cleared before returning. + pdFALSE, // Don't wait for both bits, either bit will do. + lTimeOut); // Resource wait timeout. + MB_PORT_CHECK((uxBits == MB_EVENT_RESOURCE), FALSE , "Take resource failure."); + ESP_LOGD(MB_PORT_TAG,"%s:Take resource (%x) (%lu ticks).", __func__, uxBits, lTimeOut); + return TRUE; +} + +/** + * This function is release Modbus Master running resource. + * Note:The resource is define by Operating System.If you not use OS this function can be empty. + */ +void vMBMasterRunResRelease( void ) +{ + EventBits_t uxBits = xEventGroupSetBits( xResourceMasterHdl, MB_EVENT_RESOURCE ); + MB_PORT_CHECK((uxBits == MB_EVENT_RESOURCE), ; , "Resource release failure."); + ESP_LOGD(MB_PORT_TAG,"%s: Release resource (%x).", __func__, uxBits); +} + +/** + * This is modbus master respond timeout error process callback function. + * @note There functions will block modbus master poll while execute OS waiting. + * + * @param ucDestAddress destination salve address + * @param pucPDUData PDU buffer data + * @param ucPDULength PDU buffer length + * + */ +void vMBMasterErrorCBRespondTimeout(UCHAR ucDestAddress, const UCHAR* pucPDUData, USHORT ucPDULength) +{ + BOOL ret = xMBMasterPortEventPost(EV_MASTER_ERROR_RESPOND_TIMEOUT); + MB_PORT_CHECK((ret == TRUE), ; , "%s: Post event 'EV_MASTER_ERROR_RESPOND_TIMEOUT' failed!", __func__); + ESP_LOGD(MB_PORT_TAG,"%s:Callback respond timeout.", __func__); +} + +/** + * This is modbus master receive data error process callback function. + * @note There functions will block modbus master poll while execute OS waiting. + * + * @param ucDestAddress destination salve address + * @param pucPDUData PDU buffer data + * @param ucPDULength PDU buffer length + */ +void vMBMasterErrorCBReceiveData(UCHAR ucDestAddress, const UCHAR* pucPDUData, USHORT ucPDULength) +{ + BOOL ret = xMBMasterPortEventPost(EV_MASTER_ERROR_RECEIVE_DATA); + MB_PORT_CHECK((ret == TRUE), ; , "%s: Post event 'EV_MASTER_ERROR_RECEIVE_DATA' failed!", __func__); + ESP_LOGD(MB_PORT_TAG,"%s:Callback receive data timeout failure.", __func__); + ESP_LOG_BUFFER_HEX_LEVEL("Err rcv buf", (void*)pucPDUData, (uint16_t)ucPDULength, ESP_LOG_DEBUG); +} + +/** + * This is modbus master execute function error process callback function. + * @note There functions will block modbus master poll while execute OS waiting. + * So,for real-time of system.Do not execute too much waiting process. + * + * @param ucDestAddress destination salve address + * @param pucPDUData PDU buffer data + * @param ucPDULength PDU buffer length + * + */ +void vMBMasterErrorCBExecuteFunction(UCHAR ucDestAddress, const UCHAR* pucPDUData, USHORT ucPDULength) +{ + BOOL ret = xMBMasterPortEventPost(EV_MASTER_ERROR_EXECUTE_FUNCTION); + MB_PORT_CHECK((ret == TRUE), ; , "%s: Post event 'EV_MASTER_ERROR_EXECUTE_FUNCTION' failed!", __func__); + ESP_LOGD(MB_PORT_TAG,"%s:Callback execute data handler failure.", __func__); + ESP_LOG_BUFFER_HEX_LEVEL("Exec func buf", (void*)pucPDUData, (uint16_t)ucPDULength, ESP_LOG_DEBUG); +} + +/** + * This is modbus master request process success callback function. + * @note There functions will block modbus master poll while execute OS waiting. + * So,for real-time of system. Do not execute too much waiting process. + */ +void vMBMasterCBRequestSuccess( void ) { + /** + * @note This code is use OS's event mechanism for modbus master protocol stack. + * If you don't use OS, you can change it. + */ + BOOL ret = xMBMasterPortEventPost(EV_MASTER_PROCESS_SUCCESS); + MB_PORT_CHECK((ret == TRUE), ; , "%s: Post event 'EV_MASTER_PROCESS_SUCCESS' failed!", __func__); + ESP_LOGD(MB_PORT_TAG,"%s: Callback request success.", __func__); +} + +/** + * This function is wait for modbus master request finish and return result. + * Waiting result include request process success, request respond timeout, + * receive data error and execute function error.You can use the above callback function. + * @note If you are use OS, you can use OS's event mechanism. Otherwise you have to run + * much user custom delay for waiting. + * + * @return request error code + */ +eMBMasterReqErrCode eMBMasterWaitRequestFinish( void ) { + eMBMasterReqErrCode eErrStatus = MB_MRE_NO_ERR; + eMBMasterEventType xRecvedEvent; + + EventBits_t uxBits = xEventGroupWaitBits( xEventGroupMasterHdl, // The event group being tested. + MB_EVENT_REQ_MASK, // The bits within the event group to wait for. + pdTRUE, // Masked bits should be cleared before returning. + pdFALSE, // Don't wait for both bits, either bit will do. + portMAX_DELAY ); // Wait forever for either bit to be set. + xRecvedEvent = (eMBMasterEventType)(uxBits); + if (xRecvedEvent) { + ESP_LOGD(MB_PORT_TAG,"%s: returned event = 0x%x", __func__, xRecvedEvent); + if (!(xRecvedEvent & MB_EVENT_REQ_MASK)) { + // if we wait for certain event bits but get from poll subset + ESP_LOGE(MB_PORT_TAG,"%s: incorrect event set = 0x%x", __func__, xRecvedEvent); + } + xEventGroupSetBits( xEventGroupMasterConfirmHdl, (xRecvedEvent & MB_EVENT_REQ_MASK) ); + if (MB_PORT_CHECK_EVENT(xRecvedEvent, EV_MASTER_PROCESS_SUCCESS)) { + eErrStatus = MB_MRE_NO_ERR; + } else if (MB_PORT_CHECK_EVENT(xRecvedEvent, EV_MASTER_ERROR_RESPOND_TIMEOUT)) { + eErrStatus = MB_MRE_TIMEDOUT; + } else if (MB_PORT_CHECK_EVENT(xRecvedEvent, EV_MASTER_ERROR_RECEIVE_DATA)) { + eErrStatus = MB_MRE_REV_DATA; + } else if (MB_PORT_CHECK_EVENT(xRecvedEvent, EV_MASTER_ERROR_EXECUTE_FUNCTION)) { + eErrStatus = MB_MRE_EXE_FUN; + } + } else { + ESP_LOGE(MB_PORT_TAG,"%s: Incorrect event or timeout xRecvedEvent = 0x%x", __func__, uxBits); + // https://github.com/espressif/esp-idf/issues/5275 + // if a no event is received, that means vMBMasterPortEventClose() + // has been closed, so event group has been deleted by FreeRTOS, which + // triggers the send of 0 value to the event group to unlock this task + // waiting on it. For this patch, handles it as a time out without assert. + eErrStatus = MB_MRE_TIMEDOUT; + } + return eErrStatus; +} + +void vMBMasterPortEventClose(void) +{ + vEventGroupDelete(xEventGroupMasterHdl); + vEventGroupDelete(xEventGroupMasterConfirmHdl); + vEventGroupDelete(xResourceMasterHdl); +} + +#endif diff --git a/components/freemodbus/port/portother.c b/components/freemodbus/port/portother.c new file mode 100644 index 00000000..43b6e967 --- /dev/null +++ b/components/freemodbus/port/portother.c @@ -0,0 +1,76 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * FreeModbus Libary: ESP32 Demo Application + * Copyright (C) 2010 Christian Walter + * + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * IF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: portother.c,v 1.1 2010/06/06 13:07:20 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include +#include +#include + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbport.h" + +/* ----------------------- Modbus includes ----------------------------------*/ + +/* ----------------------- Variables ----------------------------------------*/ + +/* ----------------------- Start implementation -----------------------------*/ + +BOOL +bMBPortIsWithinException( void ) +{ + BOOL bIsWithinException = xPortInIsrContext(); + return bIsWithinException; +} + +void +vMBPortClose( void ) +{ + extern void vMBPortSerialClose( void ); + extern void vMBPortTimerClose( void ); + extern void vMBPortEventClose( void ); + vMBPortSerialClose( ); + vMBPortTimerClose( ); + vMBPortEventClose( ); +} diff --git a/components/freemodbus/port/portother_m.c b/components/freemodbus/port/portother_m.c new file mode 100644 index 00000000..15b727a4 --- /dev/null +++ b/components/freemodbus/port/portother_m.c @@ -0,0 +1,71 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * FreeModbus Libary: ESP32 Demo Application + * Copyright (c) 2006 Christian Walter + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: portother.c,v 1.1 2010/06/06 13:07:20 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include +#include +#include +#include + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb_m.h" +#include "mbport.h" + +/* ----------------------- Modbus includes ----------------------------------*/ + +/* ----------------------- Variables ----------------------------------------*/ + +/* ----------------------- Start implementation -----------------------------*/ + +void +vMBMasterPortClose( void ) +{ + extern void vMBMasterPortSerialClose( void ); + extern void vMBMasterPortTimerClose( void ); + extern void vMBMasterPortEventClose( void ); + vMBMasterPortSerialClose( ); + vMBMasterPortTimerClose( ); + vMBMasterPortEventClose( ); +} + diff --git a/components/freemodbus/port/portserial.c b/components/freemodbus/port/portserial.c new file mode 100644 index 00000000..10fc1b5b --- /dev/null +++ b/components/freemodbus/port/portserial.c @@ -0,0 +1,286 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * FreeModbus Libary: ESP32 Port Demo Application + * Copyright (C) 2010 Christian Walter + * + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * IF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: portother.c,v 1.1 2010/06/06 13:07:20 wolti Exp $ + */ +#include "port.h" +#include "driver/uart.h" +#include "freertos/queue.h" // for queue support +#include "soc/uart_periph.h" +#include "driver/gpio.h" +#include "esp_log.h" // for esp_log +#include "esp_err.h" // for ESP_ERROR_CHECK macro + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbport.h" +#include "sdkconfig.h" // for KConfig options +#include "port_serial_slave.h" + +// Note: This code uses mixed coding standard from legacy IDF code and used freemodbus stack + +// A queue to handle UART event. +static QueueHandle_t xMbUartQueue; +static TaskHandle_t xMbTaskHandle; +static const CHAR *TAG = "MB_SERIAL"; + +// The UART hardware port number +static UCHAR ucUartNumber = UART_NUM_MAX - 1; + +static BOOL bRxStateEnabled = FALSE; // Receiver enabled flag +static BOOL bTxStateEnabled = FALSE; // Transmitter enabled flag + +void vMBPortSerialEnable(BOOL bRxEnable, BOOL bTxEnable) +{ + // This function can be called from xMBRTUTransmitFSM() of different task + if (bTxEnable) { + bTxStateEnabled = TRUE; + } else { + bTxStateEnabled = FALSE; + } + if (bRxEnable) { + //uart_enable_rx_intr(ucUartNumber); + bRxStateEnabled = TRUE; + vTaskResume(xMbTaskHandle); // Resume receiver task + } else { + vTaskSuspend(xMbTaskHandle); // Block receiver task + bRxStateEnabled = FALSE; + } +} + +static USHORT usMBPortSerialRxPoll(size_t xEventSize) +{ + BOOL xReadStatus = TRUE; + USHORT usCnt = 0; + + if (bRxStateEnabled) { + // Get received packet into Rx buffer + while(xReadStatus && (usCnt++ <= MB_SERIAL_BUF_SIZE)) { + // Call the Modbus stack callback function and let it fill the buffers. + xReadStatus = pxMBFrameCBByteReceived(); // callback to execute receive FSM + } + uart_flush_input(ucUartNumber); + // Send event EV_FRAME_RECEIVED to allow stack process packet +#if !CONFIG_FMB_TIMER_PORT_ENABLED + // Let the stack know that T3.5 time is expired and data is received + (void)pxMBPortCBTimerExpired(); // calls callback xMBRTUTimerT35Expired(); +#endif + ESP_LOGD(TAG, "RX: %d bytes\n", usCnt); + } + return usCnt; +} + +BOOL xMBPortSerialTxPoll(void) +{ + USHORT usCount = 0; + BOOL bNeedPoll = TRUE; + + if( bTxStateEnabled ) { + // Continue while all response bytes put in buffer or out of buffer + while((bNeedPoll) && (usCount++ < MB_SERIAL_BUF_SIZE)) { + // Calls the modbus stack callback function to let it fill the UART transmit buffer. + bNeedPoll = pxMBFrameCBTransmitterEmpty( ); // callback to transmit FSM + } + ESP_LOGD(TAG, "MB_TX_buffer send: (%d) bytes\n", (uint16_t)usCount); + // Waits while UART sending the packet + esp_err_t xTxStatus = uart_wait_tx_done(ucUartNumber, MB_SERIAL_TX_TOUT_TICKS); + vMBPortSerialEnable(TRUE, FALSE); + MB_PORT_CHECK((xTxStatus == ESP_OK), FALSE, "mb serial sent buffer failure."); + return TRUE; + } + return FALSE; +} + +static void vUartTask(void *pvParameters) +{ + uart_event_t xEvent; + USHORT usResult = 0; + for(;;) { + if (xQueueReceive(xMbUartQueue, (void*)&xEvent, portMAX_DELAY) == pdTRUE) { + ESP_LOGD(TAG, "MB_uart[%d] event:", ucUartNumber); + switch(xEvent.type) { + //Event of UART receving data + case UART_DATA: + ESP_LOGD(TAG,"Data event, length: %d", xEvent.size); + // This flag set in the event means that no more + // data received during configured timeout and UART TOUT feature is triggered + if (xEvent.timeout_flag) { + // Read received data and send it to modbus stack + usResult = usMBPortSerialRxPoll(xEvent.size); + ESP_LOGD(TAG,"Timeout occured, processed: %d bytes", usResult); + } + break; + //Event of HW FIFO overflow detected + case UART_FIFO_OVF: + ESP_LOGD(TAG, "hw fifo overflow\n"); + xQueueReset(xMbUartQueue); + break; + //Event of UART ring buffer full + case UART_BUFFER_FULL: + ESP_LOGD(TAG, "ring buffer full\n"); + xQueueReset(xMbUartQueue); + uart_flush_input(ucUartNumber); + break; + //Event of UART RX break detected + case UART_BREAK: + ESP_LOGD(TAG, "uart rx break\n"); + break; + //Event of UART parity check error + case UART_PARITY_ERR: + ESP_LOGD(TAG, "uart parity error\n"); + break; + //Event of UART frame error + case UART_FRAME_ERR: + ESP_LOGD(TAG, "uart frame error\n"); + break; + default: + ESP_LOGD(TAG, "uart event type: %d\n", xEvent.type); + break; + } + } + } + vTaskDelete(NULL); +} + +BOOL xMBPortSerialInit(UCHAR ucPORT, ULONG ulBaudRate, + UCHAR ucDataBits, eMBParity eParity) +{ + esp_err_t xErr = ESP_OK; + MB_PORT_CHECK((eParity <= MB_PAR_EVEN), FALSE, "mb serial set parity failure."); + // Set communication port number + ucUartNumber = ucPORT; + // Configure serial communication parameters + UCHAR ucParity = UART_PARITY_DISABLE; + UCHAR ucData = UART_DATA_8_BITS; + switch(eParity){ + case MB_PAR_NONE: + ucParity = UART_PARITY_DISABLE; + break; + case MB_PAR_ODD: + ucParity = UART_PARITY_ODD; + break; + case MB_PAR_EVEN: + ucParity = UART_PARITY_EVEN; + break; + } + switch(ucDataBits){ + case 5: + ucData = UART_DATA_5_BITS; + break; + case 6: + ucData = UART_DATA_6_BITS; + break; + case 7: + ucData = UART_DATA_7_BITS; + break; + case 8: + ucData = UART_DATA_8_BITS; + break; + default: + ucData = UART_DATA_8_BITS; + break; + } + uart_config_t xUartConfig = { + .baud_rate = ulBaudRate, + .data_bits = ucData, + .parity = ucParity, + .stop_bits = UART_STOP_BITS_1, + .flow_ctrl = UART_HW_FLOWCTRL_DISABLE, + .rx_flow_ctrl_thresh = 2, + .use_ref_tick = UART_SCLK_APB, + }; + // Set UART config + xErr = uart_param_config(ucUartNumber, &xUartConfig); + MB_PORT_CHECK((xErr == ESP_OK), + FALSE, "mb config failure, uart_param_config() returned (0x%x).", xErr); + // Install UART driver, and get the queue. + xErr = uart_driver_install(ucUartNumber, MB_SERIAL_BUF_SIZE, MB_SERIAL_BUF_SIZE, + MB_QUEUE_LENGTH, &xMbUartQueue, MB_PORT_SERIAL_ISR_FLAG); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "mb serial driver failure, uart_driver_install() returned (0x%x).", xErr); +#if !CONFIG_FMB_TIMER_PORT_ENABLED + // Set timeout for TOUT interrupt (T3.5 modbus time) + xErr = uart_set_rx_timeout(ucUartNumber, MB_SERIAL_TOUT); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "mb serial set rx timeout failure, uart_set_rx_timeout() returned (0x%x).", xErr); +#endif + + // Set always timeout flag to trigger timeout interrupt even after rx fifo full + uart_set_always_rx_timeout(ucUartNumber, true); + + // Create a task to handle UART events + BaseType_t xStatus = xTaskCreate(vUartTask, "uart_queue_task", MB_SERIAL_TASK_STACK_SIZE, + NULL, MB_SERIAL_TASK_PRIO, &xMbTaskHandle); + if (xStatus != pdPASS) { + vTaskDelete(xMbTaskHandle); + // Force exit from function with failure + MB_PORT_CHECK(FALSE, FALSE, + "mb stack serial task creation error. xTaskCreate() returned (0x%x).", + xStatus); + } else { + vTaskSuspend(xMbTaskHandle); // Suspend serial task while stack is not started + } + return TRUE; +} + +void vMBPortSerialClose(void) +{ + (void)vTaskSuspend(xMbTaskHandle); + (void)vTaskDelete(xMbTaskHandle); + ESP_ERROR_CHECK(uart_driver_delete(ucUartNumber)); +} + +BOOL xMBPortSerialPutByte(CHAR ucByte) +{ + // Send one byte to UART transmission buffer + // This function is called by Modbus stack + UCHAR ucLength = uart_write_bytes(ucUartNumber, &ucByte, 1); + return (ucLength == 1); +} + +// Get one byte from intermediate RX buffer +BOOL xMBPortSerialGetByte(CHAR* pucByte) +{ + assert(pucByte != NULL); + USHORT usLength = uart_read_bytes(ucUartNumber, (uint8_t*)pucByte, 1, MB_SERIAL_RX_TOUT_TICKS); + return (usLength == 1); +} + diff --git a/components/freemodbus/port/portserial_m.c b/components/freemodbus/port/portserial_m.c new file mode 100644 index 00000000..65346079 --- /dev/null +++ b/components/freemodbus/port/portserial_m.c @@ -0,0 +1,279 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * FreeModbus Libary: ESP32 Port Demo Application + * Copyright (C) 2013 Armink + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * File: $Id: portserial.c,v 1.60 2013/08/13 15:07:05 Armink add Master Functions $ + */ + +#include +#include "driver/uart.h" +#include "soc/dport_access.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/queue.h" +#include "esp_log.h" +#include "sdkconfig.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "port.h" +#include "mbport.h" +#include "mb_m.h" +#include "mbrtu.h" +#include "mbconfig.h" +#include "port_serial_master.h" + +/* ----------------------- Defines ------------------------------------------*/ + +/* ----------------------- Static variables ---------------------------------*/ +static const CHAR *TAG = "MB_MASTER_SERIAL"; + +// A queue to handle UART event. +static QueueHandle_t xMbUartQueue; +static TaskHandle_t xMbTaskHandle; + +// The UART hardware port number +static UCHAR ucUartNumber = UART_NUM_MAX - 1; + +static BOOL bRxStateEnabled = FALSE; // Receiver enabled flag +static BOOL bTxStateEnabled = FALSE; // Transmitter enabled flag + +void vMBMasterPortSerialEnable(BOOL bRxEnable, BOOL bTxEnable) +{ + // This function can be called from xMBRTUTransmitFSM() of different task + if (bTxEnable) { + bTxStateEnabled = TRUE; + } else { + bTxStateEnabled = FALSE; + } + if (bRxEnable) { + bRxStateEnabled = TRUE; + vTaskResume(xMbTaskHandle); // Resume receiver task + } else { + vTaskSuspend(xMbTaskHandle); // Block receiver task + bRxStateEnabled = FALSE; + } +} + +static USHORT usMBMasterPortSerialRxPoll(size_t xEventSize) +{ + BOOL xReadStatus = TRUE; + USHORT usCnt = 0; + + if (bRxStateEnabled) { + while(xReadStatus && (usCnt++ <= MB_SERIAL_BUF_SIZE)) { + // Call the Modbus stack callback function and let it fill the stack buffers. + xReadStatus = pxMBMasterFrameCBByteReceived(); // callback to receive FSM + } + // The buffer is transferred into Modbus stack and is not needed here any more + uart_flush_input(ucUartNumber); + ESP_LOGD(TAG, "Received data: %d(bytes in buffer)\n", (uint32_t)usCnt); + } else { + ESP_LOGE(TAG, "%s: bRxState disabled but junk data (%d bytes) received. ", __func__, xEventSize); + } + return usCnt; +} + +BOOL xMBMasterPortSerialTxPoll(void) +{ + USHORT usCount = 0; + BOOL bNeedPoll = TRUE; + + if( bTxStateEnabled ) { + // Continue while all response bytes put in buffer or out of buffer + while(bNeedPoll && (usCount++ < MB_SERIAL_BUF_SIZE)) { + // Calls the modbus stack callback function to let it fill the UART transmit buffer. + bNeedPoll = pxMBMasterFrameCBTransmitterEmpty( ); // callback to transmit FSM + } + ESP_LOGD(TAG, "MB_TX_buffer sent: (%d) bytes.", (uint16_t)(usCount - 1)); + // Waits while UART sending the packet + esp_err_t xTxStatus = uart_wait_tx_done(ucUartNumber, MB_SERIAL_TX_TOUT_TICKS); + vMBMasterPortSerialEnable( TRUE, FALSE ); + MB_PORT_CHECK((xTxStatus == ESP_OK), FALSE, "mb serial sent buffer failure."); + return TRUE; + } + return FALSE; +} + +// UART receive event task +static void vUartTask(void* pvParameters) +{ + uart_event_t xEvent; + USHORT usResult = 0; + for(;;) { + if (xQueueReceive(xMbUartQueue, (void*)&xEvent, portMAX_DELAY) == pdTRUE) { + ESP_LOGD(TAG, "MB_uart[%d] event:", ucUartNumber); + switch(xEvent.type) { + //Event of UART receiving data + case UART_DATA: + ESP_LOGD(TAG,"Data event, len: %d.", xEvent.size); + // This flag set in the event means that no more + // data received during configured timeout and UART TOUT feature is triggered + if (xEvent.timeout_flag) { + // Read received data and send it to modbus stack + usResult = usMBMasterPortSerialRxPoll(xEvent.size); + ESP_LOGD(TAG,"Timeout occured, processed: %d bytes", usResult); + // Block receiver task until data is not processed + vTaskSuspend(NULL); + } + break; + //Event of HW FIFO overflow detected + case UART_FIFO_OVF: + ESP_LOGD(TAG, "hw fifo overflow."); + xQueueReset(xMbUartQueue); + break; + //Event of UART ring buffer full + case UART_BUFFER_FULL: + ESP_LOGD(TAG, "ring buffer full."); + xQueueReset(xMbUartQueue); + uart_flush_input(ucUartNumber); + break; + //Event of UART RX break detected + case UART_BREAK: + ESP_LOGD(TAG, "uart rx break."); + break; + //Event of UART parity check error + case UART_PARITY_ERR: + ESP_LOGD(TAG, "uart parity error."); + break; + //Event of UART frame error + case UART_FRAME_ERR: + ESP_LOGD(TAG, "uart frame error."); + break; + default: + ESP_LOGD(TAG, "uart event type: %d.", xEvent.type); + break; + } + } + } + vTaskDelete(NULL); +} + +/* ----------------------- Start implementation -----------------------------*/ +BOOL xMBMasterPortSerialInit( UCHAR ucPORT, ULONG ulBaudRate, UCHAR ucDataBits, eMBParity eParity ) +{ + esp_err_t xErr = ESP_OK; + MB_PORT_CHECK((eParity <= MB_PAR_EVEN), FALSE, "mb serial set parity failure."); + // Set communication port number + ucUartNumber = ucPORT; + // Configure serial communication parameters + UCHAR ucParity = UART_PARITY_DISABLE; + UCHAR ucData = UART_DATA_8_BITS; + switch(eParity){ + case MB_PAR_NONE: + ucParity = UART_PARITY_DISABLE; + break; + case MB_PAR_ODD: + ucParity = UART_PARITY_ODD; + break; + case MB_PAR_EVEN: + ucParity = UART_PARITY_EVEN; + break; + } + switch(ucDataBits){ + case 5: + ucData = UART_DATA_5_BITS; + break; + case 6: + ucData = UART_DATA_6_BITS; + break; + case 7: + ucData = UART_DATA_7_BITS; + break; + case 8: + ucData = UART_DATA_8_BITS; + break; + default: + ucData = UART_DATA_8_BITS; + break; + } + uart_config_t xUartConfig = { + .baud_rate = ulBaudRate, + .data_bits = ucData, + .parity = ucParity, + .stop_bits = UART_STOP_BITS_1, + .flow_ctrl = UART_HW_FLOWCTRL_DISABLE, + .rx_flow_ctrl_thresh = 2, + .source_clk = UART_SCLK_APB, + }; + // Set UART config + xErr = uart_param_config(ucUartNumber, &xUartConfig); + MB_PORT_CHECK((xErr == ESP_OK), + FALSE, "mb config failure, uart_param_config() returned (0x%x).", xErr); + // Install UART driver, and get the queue. + xErr = uart_driver_install(ucUartNumber, MB_SERIAL_BUF_SIZE, MB_SERIAL_BUF_SIZE, + MB_QUEUE_LENGTH, &xMbUartQueue, MB_PORT_SERIAL_ISR_FLAG); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "mb serial driver failure, uart_driver_install() returned (0x%x).", xErr); + // Set timeout for TOUT interrupt (T3.5 modbus time) + xErr = uart_set_rx_timeout(ucUartNumber, MB_SERIAL_TOUT); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "mb serial set rx timeout failure, uart_set_rx_timeout() returned (0x%x).", xErr); + + // Set always timeout flag to trigger timeout interrupt even after rx fifo full + uart_set_always_rx_timeout(ucUartNumber, true); + + // Create a task to handle UART events + BaseType_t xStatus = xTaskCreate(vUartTask, "uart_queue_task", MB_SERIAL_TASK_STACK_SIZE, + NULL, MB_SERIAL_TASK_PRIO, &xMbTaskHandle); + if (xStatus != pdPASS) { + vTaskDelete(xMbTaskHandle); + // Force exit from function with failure + MB_PORT_CHECK(FALSE, FALSE, + "mb stack serial task creation error. xTaskCreate() returned (0x%x).", + xStatus); + } else { + vTaskSuspend(xMbTaskHandle); // Suspend serial task while stack is not started + } + ESP_LOGD(MB_PORT_TAG,"%s Init serial.", __func__); + return TRUE; +} + +void vMBMasterPortSerialClose(void) +{ + (void)vTaskDelete(xMbTaskHandle); + ESP_ERROR_CHECK(uart_driver_delete(ucUartNumber)); +} + +BOOL xMBMasterPortSerialPutByte(CHAR ucByte) +{ + // Send one byte to UART transmission buffer + // This function is called by Modbus stack + UCHAR ucLength = uart_write_bytes(ucUartNumber, &ucByte, 1); + return (ucLength == 1); +} + +// Get one byte from intermediate RX buffer +BOOL xMBMasterPortSerialGetByte(CHAR* pucByte) +{ + assert(pucByte != NULL); + USHORT usLength = uart_read_bytes(ucUartNumber, (uint8_t*)pucByte, 1, MB_SERIAL_RX_TOUT_TICKS); + return (usLength == 1); +} diff --git a/components/freemodbus/port/porttimer.c b/components/freemodbus/port/porttimer.c new file mode 100644 index 00000000..35371ad2 --- /dev/null +++ b/components/freemodbus/port/porttimer.c @@ -0,0 +1,154 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * FreeModbus Libary: ESP32 Port Demo Application + * Copyright (C) 2010 Christian Walter + * + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * IF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: portother.c,v 1.1 2010/06/06 13:07:20 wolti Exp $ + */ +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "sdkconfig.h" +#include "mb.h" +#include "mbport.h" +#include "driver/timer.h" +#include "port_serial_slave.h" +#include "sdkconfig.h" + +#if CONFIG_FMB_TIMER_PORT_ENABLED + +#define MB_US50_FREQ (20000) // 20kHz 1/20000 = 50mks +#define MB_DISCR_TIME_US (50) // 50uS = one discreet for timer + +#define MB_TIMER_PRESCALLER ((TIMER_BASE_CLK / MB_US50_FREQ) - 1); +#define MB_TIMER_SCALE (TIMER_BASE_CLK / TIMER_DIVIDER) // convert counter value to seconds +#define MB_TIMER_DIVIDER ((TIMER_BASE_CLK / 1000000UL) * MB_DISCR_TIME_US - 1) // divider for 50uS +#define MB_TIMER_WITH_RELOAD (1) + +static const USHORT usTimerIndex = CONFIG_FMB_TIMER_INDEX; // Modbus Timer index used by stack +static const USHORT usTimerGroupIndex = CONFIG_FMB_TIMER_GROUP; // Modbus Timer group index used by stack +static timer_isr_handle_t xTimerIntHandle; // Timer interrupt handle + +/* ----------------------- Start implementation -----------------------------*/ +static void IRAM_ATTR vTimerGroupIsr(void *param) +{ + assert((int)param == usTimerIndex); + // Retrieve the counter value from the timer that reported the interrupt + timer_group_clr_intr_status_in_isr(usTimerGroupIndex, usTimerIndex); + (void)pxMBPortCBTimerExpired(); // Timer callback function + // Enable alarm + timer_group_enable_alarm_in_isr(usTimerGroupIndex, usTimerIndex); +} +#endif + +BOOL xMBPortTimersInit(USHORT usTim1Timerout50us) +{ +#if CONFIG_FMB_TIMER_PORT_ENABLED + MB_PORT_CHECK((usTim1Timerout50us > 0), FALSE, + "Modbus timeout discreet is incorrect."); + esp_err_t xErr; + timer_config_t config; + config.alarm_en = TIMER_ALARM_EN; + config.auto_reload = MB_TIMER_WITH_RELOAD; + config.counter_dir = TIMER_COUNT_UP; + config.divider = MB_TIMER_PRESCALLER; + config.intr_type = TIMER_INTR_LEVEL; + config.counter_en = TIMER_PAUSE; + // Configure timer + xErr = timer_init(usTimerGroupIndex, usTimerIndex, &config); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "timer init failure, timer_init() returned (0x%x).", xErr); + // Stop timer counter + xErr = timer_pause(usTimerGroupIndex, usTimerIndex); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "stop timer failure, timer_pause() returned (0x%x).", xErr); + // Reset counter value + xErr = timer_set_counter_value(usTimerGroupIndex, usTimerIndex, 0x00000000ULL); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "timer set value failure, timer_set_counter_value() returned (0x%x).", xErr); + // wait3T5_us = 35 * 11 * 100000 / baud; // the 3.5T symbol time for baudrate + // Set alarm value for usTim1Timerout50us * 50uS + xErr = timer_set_alarm_value(usTimerGroupIndex, usTimerIndex, (uint32_t)(usTim1Timerout50us)); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "failure to set alarm failure, timer_set_alarm_value() returned (0x%x).", + (uint32_t)xErr); + // Register ISR for timer + xErr = timer_isr_register(usTimerGroupIndex, usTimerIndex, vTimerGroupIsr, + (void*)(uint32_t)usTimerIndex, MB_PORT_TIMER_ISR_FLAG, &xTimerIntHandle); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "timer set value failure, timer_isr_register() returned (0x%x).", + (uint32_t)xErr); +#endif + return TRUE; +} + +void vMBPortTimersEnable(void) +{ +#if CONFIG_FMB_TIMER_PORT_ENABLED + ESP_ERROR_CHECK(timer_pause(usTimerGroupIndex, usTimerIndex)); + ESP_ERROR_CHECK(timer_set_counter_value(usTimerGroupIndex, usTimerIndex, 0ULL)); + ESP_ERROR_CHECK(timer_enable_intr(usTimerGroupIndex, usTimerIndex)); + ESP_ERROR_CHECK(timer_start(usTimerGroupIndex, usTimerIndex)); +#endif +} + +void MB_PORT_ISR_ATTR +vMBPortTimersDisable(void) +{ +#if CONFIG_FMB_TIMER_PORT_ENABLED + if( (BOOL)xPortInIsrContext() ) { + timer_group_set_counter_enable_in_isr(usTimerGroupIndex, usTimerIndex, TIMER_PAUSE); + } else { + ESP_ERROR_CHECK(timer_pause(usTimerGroupIndex, usTimerIndex)); + ESP_ERROR_CHECK(timer_set_counter_value(usTimerGroupIndex, usTimerIndex, 0ULL)); + // Disable timer interrupt + ESP_ERROR_CHECK(timer_disable_intr(usTimerGroupIndex, usTimerIndex)); + } +#endif +} + +void vMBPortTimerClose(void) +{ +#ifdef CONFIG_FMB_TIMER_PORT_ENABLED + ESP_ERROR_CHECK(timer_pause(usTimerGroupIndex, usTimerIndex)); + ESP_ERROR_CHECK(timer_disable_intr(usTimerGroupIndex, usTimerIndex)); + ESP_ERROR_CHECK(esp_intr_free(xTimerIntHandle)); +#endif +} diff --git a/components/freemodbus/port/porttimer_m.c b/components/freemodbus/port/porttimer_m.c new file mode 100644 index 00000000..9d703363 --- /dev/null +++ b/components/freemodbus/port/porttimer_m.c @@ -0,0 +1,199 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * FreeModbus Libary: ESP32 Port Demo Application + * Copyright (C) 2013 Armink + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * File: $Id: porttimer_m.c,v 1.60 2013/08/13 15:07:05 Armink add Master Functions$ + */ + +/* ----------------------- Platform includes --------------------------------*/ +#include "port.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb_m.h" +#include "mbport.h" +#include "port_serial_master.h" +#include "sdkconfig.h" + +#define MB_US50_FREQ (20000) // 20kHz 1/20000 = 50mks +#define MB_TICK_TIME_US (50) // 50uS = one tick for timer + +#define MB_TIMER_PRESCALLER ((TIMER_BASE_CLK / MB_US50_FREQ) - 1); +#define MB_TIMER_SCALE (TIMER_BASE_CLK / TIMER_DIVIDER) +#define MB_TIMER_DIVIDER ((TIMER_BASE_CLK / 1000000UL) * MB_TICK_TIME_US - 1) // divider for 50uS +#define MB_TIMER_WITH_RELOAD (1) + +// Timer group and timer number to measure time (configurable in KConfig) +#define MB_TIMER_INDEX (CONFIG_FMB_TIMER_INDEX) +#define MB_TIMER_GROUP (CONFIG_FMB_TIMER_GROUP) + +/* ----------------------- Variables ----------------------------------------*/ +static USHORT usT35TimeOut50us; + +static const USHORT usTimerIndex = MB_TIMER_INDEX; // Initialize Modbus Timer index used by stack, +static const USHORT usTimerGroupIndex = MB_TIMER_GROUP; // Timer group index used by stack +static timer_isr_handle_t xTimerIntHandle; // Timer interrupt handle + +/* ----------------------- static functions ---------------------------------*/ +static void IRAM_ATTR vTimerGroupIsr(void *param) +{ + assert((int)param == usTimerIndex); + // Retrieve the the counter value from the timer that reported the interrupt + timer_group_clr_intr_status_in_isr(usTimerGroupIndex, usTimerIndex); + (void)pxMBMasterPortCBTimerExpired(); // Timer expired callback function + // Enable alarm + timer_group_enable_alarm_in_isr(usTimerGroupIndex, usTimerIndex); +} + +/* ----------------------- Start implementation -----------------------------*/ +BOOL xMBMasterPortTimersInit(USHORT usTimeOut50us) +{ + MB_PORT_CHECK((usTimeOut50us > 0), FALSE, + "Modbus timeout discreet is incorrect."); + // Save timer reload value for Modbus T35 period + usT35TimeOut50us = usTimeOut50us; + esp_err_t xErr; + timer_config_t config; + config.alarm_en = TIMER_ALARM_EN; + config.auto_reload = MB_TIMER_WITH_RELOAD; + config.counter_dir = TIMER_COUNT_UP; + config.divider = MB_TIMER_PRESCALLER; + config.intr_type = TIMER_INTR_LEVEL; + config.counter_en = TIMER_PAUSE; + // Configure timer + xErr = timer_init(usTimerGroupIndex, usTimerIndex, &config); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "timer init failure, timer_init() returned (0x%x).", (uint32_t)xErr); + // Stop timer counter + xErr = timer_pause(usTimerGroupIndex, usTimerIndex); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "stop timer failure, timer_pause() returned (0x%x).", (uint32_t)xErr); + // Reset counter value + xErr = timer_set_counter_value(usTimerGroupIndex, usTimerIndex, 0x00000000ULL); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "timer set value failure, timer_set_counter_value() returned (0x%x).", + (uint32_t)xErr); + // wait3T5_us = 35 * 11 * 100000 / baud; // the 3.5T symbol time for baudrate + // Set alarm value for usTimeOut50us * 50uS + xErr = timer_set_alarm_value(usTimerGroupIndex, usTimerIndex, (uint32_t)(usTimeOut50us)); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "failure to set alarm failure, timer_set_alarm_value() returned (0x%x).", + (uint32_t)xErr); + // Register ISR for timer + xErr = timer_isr_register(usTimerGroupIndex, usTimerIndex, + vTimerGroupIsr, (void*)(uint32_t)usTimerIndex, MB_PORT_TIMER_ISR_FLAG, &xTimerIntHandle); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "timer set value failure, timer_isr_register() returned (0x%x).", + (uint32_t)xErr); + return TRUE; +} + +// Set alarm value for usTimerTimeOut50us * 50uS +static BOOL xMBMasterPortTimersEnable(USHORT usTimerTics50us) +{ + MB_PORT_CHECK((usTimerTics50us > 0), FALSE, + "incorrect tick value for timer = (0x%x).", + (uint32_t)usTimerTics50us); + esp_err_t xErr; + xErr = timer_pause(usTimerGroupIndex, usTimerIndex); // stop timer + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "timer pause failure, timer_pause() returned (0x%x).", + (uint32_t)xErr); + xErr = timer_set_counter_value(usTimerGroupIndex, usTimerIndex, 0ULL); // reset timer + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "timer set counter failure, timer_set_counter_value() returned (0x%x).", + (uint32_t)xErr); + // Set alarm value to number of 50uS ticks + xErr = timer_set_alarm_value(usTimerGroupIndex, usTimerIndex, + (uint32_t)(usTimerTics50us)); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "timer set alarm failure, timer_set_alarm_value() returned (0x%x).", + (uint32_t)xErr); + xErr = timer_enable_intr(usTimerGroupIndex, usTimerIndex); + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "timer enable interrupt failure, timer_enable_intr() returned (0x%x).", + (uint32_t)xErr); + xErr = timer_start(usTimerGroupIndex, usTimerIndex); // start timer + MB_PORT_CHECK((xErr == ESP_OK), FALSE, + "timer start failure, timer_start() returned (0x%x).", + (uint32_t)xErr); + return TRUE; +} + +void vMBMasterPortTimersT35Enable(void) +{ + USHORT usTimerTicks = usT35TimeOut50us; + + // Set current timer mode, don't change it. + vMBMasterSetCurTimerMode(MB_TMODE_T35); + // Set timer period + (void)xMBMasterPortTimersEnable(usTimerTicks); +} + +void vMBMasterPortTimersConvertDelayEnable(void) +{ + // Covert time in milliseconds into ticks + USHORT usTimerTicks = ((MB_MASTER_DELAY_MS_CONVERT * 1000) / MB_TICK_TIME_US); + + // Set current timer mode + vMBMasterSetCurTimerMode(MB_TMODE_CONVERT_DELAY); + ESP_LOGD(MB_PORT_TAG,"%s Convert delay enable.", __func__); + (void)xMBMasterPortTimersEnable(usTimerTicks); +} + +void vMBMasterPortTimersRespondTimeoutEnable(void) +{ + USHORT usTimerTicks = (MB_MASTER_TIMEOUT_MS_RESPOND * 1000 / MB_TICK_TIME_US); + + vMBMasterSetCurTimerMode(MB_TMODE_RESPOND_TIMEOUT); + ESP_LOGD(MB_PORT_TAG,"%s Respond enable timeout.", __func__); + (void)xMBMasterPortTimersEnable(usTimerTicks); +} + +void MB_PORT_ISR_ATTR +vMBMasterPortTimersDisable() +{ + if( (BOOL)xPortInIsrContext() ) { + timer_group_set_counter_enable_in_isr(usTimerGroupIndex, usTimerIndex, TIMER_PAUSE); + } else { + // Stop timer and then reload timer counter value + ESP_ERROR_CHECK(timer_pause(usTimerGroupIndex, usTimerIndex)); + ESP_ERROR_CHECK(timer_set_counter_value(usTimerGroupIndex, usTimerIndex, 0ULL)); + // Disable timer interrupt + ESP_ERROR_CHECK(timer_disable_intr(usTimerGroupIndex, usTimerIndex)); + } +} + +void vMBMasterPortTimerClose(void) +{ + ESP_ERROR_CHECK(timer_pause(usTimerGroupIndex, usTimerIndex)); + ESP_ERROR_CHECK(timer_disable_intr(usTimerGroupIndex, usTimerIndex)); + ESP_ERROR_CHECK(esp_intr_free(xTimerIntHandle)); +} diff --git a/components/freemodbus/sdkconfig.rename b/components/freemodbus/sdkconfig.rename new file mode 100644 index 00000000..89c1c237 --- /dev/null +++ b/components/freemodbus/sdkconfig.rename @@ -0,0 +1,18 @@ +# sdkconfig replacement configurations for deprecated options formatted as +# CONFIG_DEPRECATED_OPTION CONFIG_NEW_OPTION + +CONFIG_MB_MASTER_TIMEOUT_MS_RESPOND CONFIG_FMB_MASTER_TIMEOUT_MS_RESPOND +CONFIG_MB_MASTER_DELAY_MS_CONVERT CONFIG_FMB_MASTER_DELAY_MS_CONVERT +CONFIG_MB_QUEUE_LENGTH CONFIG_FMB_QUEUE_LENGTH +CONFIG_MB_SERIAL_TASK_STACK_SIZE CONFIG_FMB_PORT_TASK_STACK_SIZE +CONFIG_MB_SERIAL_BUF_SIZE CONFIG_FMB_SERIAL_BUF_SIZE +CONFIG_MB_SERIAL_TASK_PRIO CONFIG_FMB_PORT_TASK_PRIO +CONFIG_MB_CONTROLLER_SLAVE_ID_SUPPORT CONFIG_FMB_CONTROLLER_SLAVE_ID_SUPPORT +CONFIG_MB_CONTROLLER_SLAVE_ID CONFIG_FMB_CONTROLLER_SLAVE_ID +CONFIG_MB_CONTROLLER_NOTIFY_TIMEOUT CONFIG_FMB_CONTROLLER_NOTIFY_TIMEOUT +CONFIG_MB_CONTROLLER_NOTIFY_QUEUE_SIZE CONFIG_FMB_CONTROLLER_NOTIFY_QUEUE_SIZE +CONFIG_MB_CONTROLLER_STACK_SIZE CONFIG_FMB_CONTROLLER_STACK_SIZE +CONFIG_MB_EVENT_QUEUE_TIMEOUT CONFIG_FMB_EVENT_QUEUE_TIMEOUT +CONFIG_MB_TIMER_PORT_ENABLED CONFIG_FMB_TIMER_PORT_ENABLED +CONFIG_MB_TIMER_GROUP CONFIG_FMB_TIMER_GROUP +CONFIG_MB_TIMER_INDEX CONFIG_FMB_TIMER_INDEX diff --git a/components/freemodbus/serial_master/modbus_controller/mbc_serial_master.c b/components/freemodbus/serial_master/modbus_controller/mbc_serial_master.c new file mode 100644 index 00000000..93ac3137 --- /dev/null +++ b/components/freemodbus/serial_master/modbus_controller/mbc_serial_master.c @@ -0,0 +1,705 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// mbc_serial_master.c +// Serial master implementation of the Modbus controller + +#include // for calculation of time stamp in milliseconds +#include "esp_log.h" // for log_write +#include // for memcpy +#include "freertos/FreeRTOS.h" // for task creation and queue access +#include "freertos/task.h" // for task api access +#include "freertos/event_groups.h" // for event groups +#include "freertos/queue.h" // for queue api access +#include "mb_m.h" // for modbus stack master types definition +#include "port.h" // for port callback functions +#include "mbutils.h" // for mbutils functions definition for stack callback +#include "sdkconfig.h" // for KConfig values +#include "esp_modbus_common.h" // for common types +#include "esp_modbus_master.h" // for public master types +#include "mbc_master.h" // for private master types +#include "mbc_serial_master.h" // for serial master create function and types + +// The Modbus Transmit Poll function defined in port +extern BOOL xMBMasterPortSerialTxPoll(void); + +/*-----------------------Master mode use these variables----------------------*/ +#define MB_RESPONSE_TICS pdMS_TO_TICKS(CONFIG_FMB_MASTER_TIMEOUT_MS_RESPOND + 10) + + +static mb_master_interface_t* mbm_interface_ptr = NULL; //&default_interface_inst; + +// Modbus event processing task +static void modbus_master_task(void *pvParameters) +{ + // The interface must be initialized before start of state machine + MB_MASTER_ASSERT(mbm_interface_ptr != NULL); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + // Main Modbus stack processing cycle + for (;;) { + // Wait for poll events + BaseType_t status = xEventGroupWaitBits(mbm_opts->mbm_event_group, + (BaseType_t)(MB_EVENT_STACK_STARTED), + pdFALSE, // do not clear bits + pdFALSE, + portMAX_DELAY); + // Check if stack started then poll for data + if (status & MB_EVENT_STACK_STARTED) { + (void)eMBMasterPoll(); // Allow stack to process data + // Send response buffer if ready to be sent + BOOL xSentState = xMBMasterPortSerialTxPoll(); + if (xSentState) { + // Let state machine know that response was transmitted out + (void)xMBMasterPortEventPost(EV_MASTER_FRAME_SENT); + } + } + } +} + +// Setup Modbus controller parameters +static esp_err_t mbc_serial_master_setup(void* comm_info) +{ + MB_MASTER_CHECK((mbm_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface uninitialized."); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + + const mb_master_comm_info_t* comm_info_ptr = (mb_master_comm_info_t*)comm_info; + // Check communication options + MB_MASTER_CHECK(((comm_info_ptr->mode == MB_MODE_RTU) || (comm_info_ptr->mode == MB_MODE_ASCII)), + ESP_ERR_INVALID_ARG, "mb incorrect mode = (0x%x).", + (uint32_t)comm_info_ptr->mode); + MB_MASTER_CHECK((comm_info_ptr->port <= UART_NUM_MAX), ESP_ERR_INVALID_ARG, + "mb wrong port to set = (0x%x).", (uint32_t)comm_info_ptr->port); + MB_MASTER_CHECK((comm_info_ptr->parity <= UART_PARITY_EVEN), ESP_ERR_INVALID_ARG, + "mb wrong parity option = (0x%x).", (uint32_t)comm_info_ptr->parity); + // Save the communication options + mbm_opts->mbm_comm = *(mb_communication_info_t*)comm_info_ptr; + return ESP_OK; +} + +// Modbus controller stack start function +static esp_err_t mbc_serial_master_start(void) +{ + MB_MASTER_CHECK((mbm_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface uninitialized."); + eMBErrorCode status = MB_EIO; + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + const mb_communication_info_t* comm_info = (mb_communication_info_t*)&mbm_opts->mbm_comm; + + // Initialize Modbus stack using mbcontroller parameters + status = eMBMasterSerialInit((eMBMode)comm_info->mode, (UCHAR)comm_info->port, + (ULONG)comm_info->baudrate, (eMBParity)comm_info->parity); + MB_MASTER_CHECK((status == MB_ENOERR), ESP_ERR_INVALID_STATE, + "mb stack initialization failure, eMBInit() returns (0x%x).", status); + status = eMBMasterEnable(); + MB_MASTER_CHECK((status == MB_ENOERR), ESP_ERR_INVALID_STATE, + "mb stack set slave ID failure, eMBEnable() returned (0x%x).", (uint32_t)status); + // Set the mbcontroller start flag + EventBits_t flag = xEventGroupSetBits(mbm_opts->mbm_event_group, + (EventBits_t)MB_EVENT_STACK_STARTED); + MB_MASTER_CHECK((flag & MB_EVENT_STACK_STARTED), + ESP_ERR_INVALID_STATE, "mb stack start event set error."); + return ESP_OK; +} + +// Modbus controller destroy function +static esp_err_t mbc_serial_master_destroy(void) +{ + MB_MASTER_CHECK((mbm_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface uninitialized."); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + eMBErrorCode mb_error = MB_ENOERR; + // Stop polling by clearing correspondent bit in the event group + EventBits_t flag = xEventGroupClearBits(mbm_opts->mbm_event_group, + (EventBits_t)MB_EVENT_STACK_STARTED); + MB_MASTER_CHECK((flag & MB_EVENT_STACK_STARTED), + ESP_ERR_INVALID_STATE, "mb stack stop event failure."); + // Desable and then destroy the Modbus stack + mb_error = eMBMasterDisable(); + MB_MASTER_CHECK((mb_error == MB_ENOERR), ESP_ERR_INVALID_STATE, "mb stack disable failure."); + (void)vTaskDelete(mbm_opts->mbm_task_handle); + (void)vEventGroupDelete(mbm_opts->mbm_event_group); + mb_error = eMBMasterClose(); + MB_MASTER_CHECK((mb_error == MB_ENOERR), ESP_ERR_INVALID_STATE, + "mb stack close failure returned (0x%x).", (uint32_t)mb_error); + free(mbm_interface_ptr); // free the memory allocated for options + vMBPortSetMode((UCHAR)MB_PORT_INACTIVE); + mbm_interface_ptr = NULL; + return ESP_OK; +} + +// Set Modbus parameter description table +static esp_err_t mbc_serial_master_set_descriptor(const mb_parameter_descriptor_t* descriptor, const uint16_t num_elements) +{ + MB_MASTER_CHECK((descriptor != NULL), + ESP_ERR_INVALID_ARG, "mb incorrect descriptor."); + MB_MASTER_CHECK((num_elements >= 1), + ESP_ERR_INVALID_ARG, "mb table size is incorrect."); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + const mb_parameter_descriptor_t *reg_ptr = descriptor; + // Go through all items in the table to check all Modbus registers + for (uint16_t counter = 0; counter < (num_elements); counter++, reg_ptr++) + { + // Below is the code to check consistency of the table format and required fields. + MB_MASTER_CHECK((reg_ptr->cid == counter), + ESP_ERR_INVALID_ARG, "mb descriptor cid field is incorrect."); + MB_MASTER_CHECK((reg_ptr->param_key != NULL), + ESP_ERR_INVALID_ARG, "mb descriptor param key is incorrect."); + MB_MASTER_CHECK((reg_ptr->mb_size > 0), + ESP_ERR_INVALID_ARG, "mb descriptor param size is incorrect."); + } + mbm_opts->mbm_param_descriptor_table = descriptor; + mbm_opts->mbm_param_descriptor_size = num_elements; + return ESP_OK; +} + +// Send custom Modbus request defined as mb_param_request_t structure +static esp_err_t mbc_serial_master_send_request(mb_param_request_t* request, void* data_ptr) +{ + MB_MASTER_CHECK((mbm_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface uninitialized."); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + MB_MASTER_CHECK((request != NULL), + ESP_ERR_INVALID_ARG, "mb request structure."); + MB_MASTER_CHECK((data_ptr != NULL), + ESP_ERR_INVALID_ARG, "mb incorrect data pointer."); + + eMBMasterReqErrCode mb_error = MB_MRE_NO_REG; + esp_err_t error = ESP_FAIL; + + uint8_t mb_slave_addr = request->slave_addr; + uint8_t mb_command = request->command; + uint16_t mb_offset = request->reg_start; + uint16_t mb_size = request->reg_size; + + // Set the buffer for callback function processing of received data + mbm_opts->mbm_reg_buffer_ptr = (uint8_t*)data_ptr; + mbm_opts->mbm_reg_buffer_size = mb_size; + + // Calls appropriate request function to send request and waits response + switch(mb_command) + { + case MB_FUNC_READ_COILS: + mb_error = eMBMasterReqReadCoils((UCHAR)mb_slave_addr, (USHORT)mb_offset, + (USHORT)mb_size , (LONG)MB_RESPONSE_TICS ); + break; + case MB_FUNC_WRITE_SINGLE_COIL: + mb_error = eMBMasterReqWriteCoil((UCHAR)mb_slave_addr, (USHORT)mb_offset, + *(USHORT*)data_ptr, (LONG)MB_RESPONSE_TICS ); + break; + case MB_FUNC_WRITE_MULTIPLE_COILS: + mb_error = eMBMasterReqWriteMultipleCoils((UCHAR)mb_slave_addr, (USHORT)mb_offset, + (USHORT)mb_size, (UCHAR*)data_ptr, (LONG)MB_RESPONSE_TICS); + break; + case MB_FUNC_READ_DISCRETE_INPUTS: + mb_error = eMBMasterReqReadDiscreteInputs((UCHAR)mb_slave_addr, (USHORT)mb_offset, + (USHORT)mb_size, (LONG)MB_RESPONSE_TICS ); + break; + case MB_FUNC_READ_HOLDING_REGISTER: + mb_error = eMBMasterReqReadHoldingRegister((UCHAR)mb_slave_addr, (USHORT)mb_offset, + (USHORT)mb_size, (LONG)MB_RESPONSE_TICS ); + break; + case MB_FUNC_WRITE_REGISTER: + mb_error = eMBMasterReqWriteHoldingRegister( (UCHAR)mb_slave_addr, (USHORT)mb_offset, + *(USHORT*)data_ptr, (LONG)MB_RESPONSE_TICS ); + break; + + case MB_FUNC_WRITE_MULTIPLE_REGISTERS: + mb_error = eMBMasterReqWriteMultipleHoldingRegister( (UCHAR)mb_slave_addr, + (USHORT)mb_offset, (USHORT)mb_size, + (USHORT*)data_ptr, (LONG)MB_RESPONSE_TICS ); + break; + case MB_FUNC_READWRITE_MULTIPLE_REGISTERS: + mb_error = eMBMasterReqReadWriteMultipleHoldingRegister( (UCHAR)mb_slave_addr, (USHORT)mb_offset, + (USHORT)mb_size, (USHORT*)data_ptr, + (USHORT)mb_offset, (USHORT)mb_size, + (LONG)MB_RESPONSE_TICS ); + break; + case MB_FUNC_READ_INPUT_REGISTER: + mb_error = eMBMasterReqReadInputRegister( (UCHAR)mb_slave_addr, (USHORT)mb_offset, + (USHORT)mb_size, (LONG) MB_RESPONSE_TICS ); + break; + default: + ESP_LOGE(MB_MASTER_TAG, "%s: Incorrect function in request (%u) ", + __FUNCTION__, mb_command); + mb_error = MB_MRE_NO_REG; + break; + } + + // Propagate the Modbus errors to higher level + switch(mb_error) + { + case MB_MRE_NO_ERR: + error = ESP_OK; + break; + + case MB_MRE_NO_REG: + error = ESP_ERR_NOT_SUPPORTED; // Invalid register request + break; + + case MB_MRE_TIMEDOUT: + error = ESP_ERR_TIMEOUT; // Slave did not send response + break; + + case MB_MRE_EXE_FUN: + case MB_MRE_REV_DATA: + error = ESP_ERR_INVALID_RESPONSE; // Invalid response from slave + break; + + case MB_MRE_MASTER_BUSY: + error = ESP_ERR_INVALID_STATE; // Master is busy (previous request is pending) + break; + + default: + ESP_LOGE(MB_MASTER_TAG, "%s: Incorrect return code (%x) ", + __FUNCTION__, mb_error); + error = ESP_FAIL; + break; + } + + return error; +} + +static esp_err_t mbc_serial_master_get_cid_info(uint16_t cid, const mb_parameter_descriptor_t** param_buffer) +{ + MB_MASTER_CHECK((mbm_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface uninitialized."); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + + MB_MASTER_CHECK((param_buffer != NULL), + ESP_ERR_INVALID_ARG, "mb incorrect data buffer pointer."); + MB_MASTER_CHECK((mbm_opts->mbm_param_descriptor_table != NULL), + ESP_ERR_INVALID_ARG, "mb incorrect descriptor table or not set."); + MB_MASTER_CHECK((cid < mbm_opts->mbm_param_descriptor_size), + ESP_ERR_NOT_FOUND, "mb incorrect cid of characteristic."); + + // It is assumed that characteristics cid increased in the table + const mb_parameter_descriptor_t* reg_info = &mbm_opts->mbm_param_descriptor_table[cid]; + + MB_MASTER_CHECK((reg_info->param_key != NULL), + ESP_ERR_INVALID_ARG, "mb incorrect characteristic key."); + *param_buffer = reg_info; + return ESP_OK; +} + +// Helper function to get modbus command for each type of Modbus register area +static uint8_t mbc_serial_master_get_command(mb_param_type_t param_type, mb_param_mode_t mode) +{ + uint8_t command = 0; + switch(param_type) + { // + case MB_PARAM_HOLDING: + command = (mode == MB_PARAM_WRITE) ? + MB_FUNC_WRITE_MULTIPLE_REGISTERS : + MB_FUNC_READ_HOLDING_REGISTER; + break; + case MB_PARAM_INPUT: + command = MB_FUNC_READ_INPUT_REGISTER; + break; + case MB_PARAM_COIL: + command = (mode == MB_PARAM_WRITE) ? + MB_FUNC_WRITE_MULTIPLE_COILS : + MB_FUNC_READ_COILS; + break; + case MB_PARAM_DISCRETE: + if (mode != MB_PARAM_WRITE) { + command = MB_FUNC_READ_DISCRETE_INPUTS; + } else { + ESP_LOGE(MB_MASTER_TAG, "%s: Incorrect mode (%u)", + __FUNCTION__, (uint8_t)mode); + } + break; + default: + ESP_LOGE(MB_MASTER_TAG, "%s: Incorrect param type (%u)", + __FUNCTION__, param_type); + break; + } + return command; +} + +// Helper to search parameter by name in the parameter description table +// and fills Modbus request fields accordingly +static esp_err_t mbc_serial_master_set_request(char* name, mb_param_mode_t mode, + mb_param_request_t* request, + mb_parameter_descriptor_t* reg_data) +{ + MB_MASTER_CHECK((mbm_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Master interface uninitialized."); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + esp_err_t error = ESP_ERR_NOT_FOUND; + MB_MASTER_CHECK((name != NULL), + ESP_ERR_INVALID_ARG, "mb incorrect parameter name."); + MB_MASTER_CHECK((request != NULL), + ESP_ERR_INVALID_ARG, "mb incorrect request parameter."); + MB_MASTER_CHECK((mode <= MB_PARAM_WRITE), + ESP_ERR_INVALID_ARG, "mb incorrect mode."); + MB_MASTER_ASSERT(mbm_opts->mbm_param_descriptor_table != NULL); + const mb_parameter_descriptor_t* reg_ptr = mbm_opts->mbm_param_descriptor_table; + for (uint16_t counter = 0; counter < (mbm_opts->mbm_param_descriptor_size); counter++, reg_ptr++) + { + // Check the cid of the parameter is equal to record number in the table + // Check the length of name and parameter key strings from table + size_t param_key_len = strlen((const char*)reg_ptr->param_key); + if (param_key_len != strlen((const char*)name)) { + continue; // The length of strings is different then check next record in the table + } + // Compare the name of parameter with parameter key from table + int comp_result = memcmp((const void*)name, (const void*)reg_ptr->param_key, (size_t)param_key_len); + if (comp_result == 0) { + // The correct line is found in the table and reg_ptr points to the found parameter description + request->slave_addr = reg_ptr->mb_slave_addr; + request->reg_start = reg_ptr->mb_reg_start; + request->reg_size = reg_ptr->mb_size; + request->command = mbc_serial_master_get_command(reg_ptr->mb_param_type, mode); + MB_MASTER_CHECK((request->command > 0), + ESP_ERR_INVALID_ARG, + "mb incorrect command or parameter type."); + if (reg_data != NULL) { + *reg_data = *reg_ptr; // Set the cid registered parameter data + } + error = ESP_OK; + break; + } + } + return error; +} + +// Get parameter data for corresponding characteristic +static esp_err_t mbc_serial_master_get_parameter(uint16_t cid, char* name, + uint8_t* value_ptr, uint8_t *type) +{ + MB_MASTER_CHECK((name != NULL), + ESP_ERR_INVALID_ARG, "mb incorrect descriptor."); + MB_MASTER_CHECK((type != NULL), + ESP_ERR_INVALID_ARG, "type pointer is incorrect."); + esp_err_t error = ESP_ERR_INVALID_RESPONSE; + mb_param_request_t request ; + mb_parameter_descriptor_t reg_info = { 0 }; + + error = mbc_serial_master_set_request(name, MB_PARAM_READ, &request, ®_info); + if ((error == ESP_OK) && (cid == reg_info.cid)) { + // Send request to read characteristic data + error = mbc_serial_master_send_request(&request, value_ptr); + if (error == ESP_OK) { + ESP_LOGD(MB_MASTER_TAG, "%s: Good response for get cid(%u) = %s", + __FUNCTION__, (int)reg_info.cid, (char*)esp_err_to_name(error)); + } else { + ESP_LOGD(MB_MASTER_TAG, "%s: Bad response to get cid(%u) = %s", + __FUNCTION__, reg_info.cid, (char*)esp_err_to_name(error)); + } + // Set the type of parameter found in the table + *type = reg_info.param_type; + } else { + ESP_LOGD(MB_MASTER_TAG, "%s: The cid(%u) not found in the data dictionary.", + __FUNCTION__, reg_info.cid); + } + return error; +} + +// Set parameter value for characteristic selected by name and cid +static esp_err_t mbc_serial_master_set_parameter(uint16_t cid, char* name, + uint8_t* value_ptr, uint8_t *type) +{ + MB_MASTER_CHECK((name != NULL), + ESP_ERR_INVALID_ARG, "mb incorrect descriptor."); + MB_MASTER_CHECK((value_ptr != NULL), + ESP_ERR_INVALID_ARG, "value pointer is incorrect."); + MB_MASTER_CHECK((type != NULL), + ESP_ERR_INVALID_ARG, "type pointer is incorrect."); + esp_err_t error = ESP_ERR_INVALID_RESPONSE; + mb_param_request_t request ; + mb_parameter_descriptor_t reg_info = { 0 }; + + error = mbc_serial_master_set_request(name, MB_PARAM_WRITE, &request, ®_info); + if ((error == ESP_OK) && (cid == reg_info.cid)) { + // Send request to write characteristic data + error = mbc_serial_master_send_request(&request, value_ptr); + if (error == ESP_OK) { + ESP_LOGD(MB_MASTER_TAG, "%s: Good response for set cid(%u) = %s", + __FUNCTION__, (int)reg_info.cid, (char*)esp_err_to_name(error)); + } else { + ESP_LOGD(MB_MASTER_TAG, "%s: Bad response to set cid(%u) = %s", + __FUNCTION__, reg_info.cid, (char*)esp_err_to_name(error)); + } + // Set the type of parameter found in the table + *type = reg_info.param_type; + } else { + ESP_LOGE(MB_MASTER_TAG, "%s: The requested cid(%u) not found in the data dictionary.", + __FUNCTION__, reg_info.cid); + } + return error; +} + +/* ----------------------- Callback functions for Modbus stack ---------------------------------*/ +// These are executed by modbus stack to read appropriate type of registers. + +/** + * Modbus master input register callback function. + * + * @param pucRegBuffer input register buffer + * @param usAddress input register address + * @param usNRegs input register number + * + * @return result + */ +// Callback function for reading of MB Input Registers +eMBErrorCode eMBRegInputCBSerialMaster(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs) +{ + MB_MASTER_CHECK((mbm_interface_ptr != NULL), + MB_EILLSTATE, + "Master interface uninitialized."); + MB_MASTER_CHECK((pucRegBuffer != NULL), MB_EINVAL, + "Master stack processing error."); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + // Number of input registers to be transferred + USHORT usRegInputNregs = (USHORT)mbm_opts->mbm_reg_buffer_size; + UCHAR* pucInputBuffer = (UCHAR*)mbm_opts->mbm_reg_buffer_ptr; // Get instance address + USHORT usRegs = usNRegs; + eMBErrorCode eStatus = MB_ENOERR; + // If input or configuration parameters are incorrect then return an error to stack layer + if ((pucInputBuffer != NULL) + && (usNRegs >= 1) + && (usRegInputNregs == usRegs)) { + while (usRegs > 0) { + _XFER_2_RD(pucInputBuffer, pucRegBuffer); + usRegs -= 1; + } + } else { + eStatus = MB_ENOREG; + } + return eStatus; +} + +/** + * Modbus master holding register callback function. + * + * @param pucRegBuffer holding register buffer + * @param usAddress holding register address + * @param usNRegs holding register number + * @param eMode read or write + * + * @return result + */ +// Callback function for reading of MB Holding Registers +// Executed by stack when request to read/write holding registers is received +eMBErrorCode eMBRegHoldingCBSerialMaster(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs, eMBRegisterMode eMode) +{ + MB_MASTER_CHECK((mbm_interface_ptr != NULL), + MB_EILLSTATE, + "Master interface uninitialized."); + MB_MASTER_CHECK((pucRegBuffer != NULL), MB_EINVAL, + "Master stack processing error."); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + USHORT usRegHoldingNregs = (USHORT)mbm_opts->mbm_reg_buffer_size; + UCHAR* pucHoldingBuffer = (UCHAR*)mbm_opts->mbm_reg_buffer_ptr; + eMBErrorCode eStatus = MB_ENOERR; + USHORT usRegs = usNRegs; + // Check input and configuration parameters for correctness + if ((pucHoldingBuffer != NULL) + && (usRegHoldingNregs == usNRegs) + && (usNRegs >= 1)) { + switch (eMode) { + case MB_REG_WRITE: + while (usRegs > 0) { + _XFER_2_RD(pucRegBuffer, pucHoldingBuffer); + usRegs -= 1; + }; + break; + case MB_REG_READ: + while (usRegs > 0) { + _XFER_2_WR(pucHoldingBuffer, pucRegBuffer); + pucHoldingBuffer += 2; + usRegs -= 1; + }; + break; + } + } else { + eStatus = MB_ENOREG; + } + return eStatus; +} + +/** + * Modbus master coils callback function. + * + * @param pucRegBuffer coils buffer + * @param usAddress coils address + * @param usNCoils coils number + * @param eMode read or write + * + * @return result + */ +// Callback function for reading of MB Coils Registers +eMBErrorCode eMBRegCoilsCBSerialMaster(UCHAR* pucRegBuffer, USHORT usAddress, + USHORT usNCoils, eMBRegisterMode eMode) +{ + MB_MASTER_CHECK((mbm_interface_ptr != NULL), + MB_EILLSTATE, "Master interface uninitialized."); + MB_MASTER_CHECK((pucRegBuffer != NULL), + MB_EINVAL, "Master stack processing error."); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + USHORT usRegCoilNregs = (USHORT)mbm_opts->mbm_reg_buffer_size; + UCHAR* pucRegCoilsBuf = (UCHAR*)mbm_opts->mbm_reg_buffer_ptr; + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegIndex; + USHORT usCoils = usNCoils; + usAddress--; // The address is already + 1 + if ((usRegCoilNregs >= 1) + && (pucRegCoilsBuf != NULL) + && (usNCoils == usRegCoilNregs)) { + iRegIndex = (usAddress % 8); + switch (eMode) { + case MB_REG_WRITE: + while (usCoils > 0) { + UCHAR ucResult = xMBUtilGetBits((UCHAR*)pucRegCoilsBuf, iRegIndex, 1); + xMBUtilSetBits(pucRegBuffer, iRegIndex - (usAddress % 8) , 1, ucResult); + iRegIndex++; + usCoils--; + } + break; + case MB_REG_READ: + while (usCoils > 0) { + UCHAR ucResult = xMBUtilGetBits(pucRegBuffer, iRegIndex - (usAddress % 8), 1); + xMBUtilSetBits((uint8_t*)pucRegCoilsBuf, iRegIndex, 1, ucResult); + iRegIndex++; + usCoils--; + } + break; + } // switch ( eMode ) + } else { + // If the configuration or input parameters are incorrect then return error to stack + eStatus = MB_ENOREG; + } + return eStatus; +} + +/** + * Modbus master discrete callback function. + * + * @param pucRegBuffer discrete buffer + * @param usAddress discrete address + * @param usNDiscrete discrete number + * + * @return result + */ +// Callback function for reading of MB Discrete Input Registers +eMBErrorCode eMBRegDiscreteCBSerialMaster(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNDiscrete) +{ + MB_MASTER_CHECK((mbm_interface_ptr != NULL), + MB_EILLSTATE, "Master interface uninitialized."); + MB_MASTER_CHECK((pucRegBuffer != NULL), + MB_EINVAL, "Master stack processing error."); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + USHORT usRegDiscreteNregs = (USHORT)mbm_opts->mbm_reg_buffer_size; + UCHAR* pucRegDiscreteBuf = (UCHAR*)mbm_opts->mbm_reg_buffer_ptr; + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegBitIndex, iNReg; + UCHAR* pucDiscreteInputBuf; + iNReg = usNDiscrete / 8 + 1; + pucDiscreteInputBuf = (UCHAR*) pucRegDiscreteBuf; + // It is already plus one in Modbus function method. + usAddress--; + if ((usRegDiscreteNregs >= 1) + && (pucRegDiscreteBuf != NULL) + && (usNDiscrete >= 1)) { + iRegBitIndex = (USHORT)(usAddress) % 8; // Get bit index + while (iNReg > 1) + { + xMBUtilSetBits(pucDiscreteInputBuf++, iRegBitIndex, 8, *pucRegBuffer++); + iNReg--; + } + // last discrete + usNDiscrete = usNDiscrete % 8; + // xMBUtilSetBits has bug when ucNBits is zero + if (usNDiscrete != 0) + { + xMBUtilSetBits(pucDiscreteInputBuf, iRegBitIndex, usNDiscrete, *pucRegBuffer++); + } + } else { + eStatus = MB_ENOREG; + } + return eStatus; +} + +// Initialization of resources for Modbus serial master controller +esp_err_t mbc_serial_master_create(void** handler) +{ + // Allocate space for master interface structure + if (mbm_interface_ptr == NULL) { + mbm_interface_ptr = malloc(sizeof(mb_master_interface_t)); + } + MB_MASTER_ASSERT(mbm_interface_ptr != NULL); + + // Initialize interface properties + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + mbm_opts->port_type = MB_PORT_SERIAL_MASTER; + + vMBPortSetMode((UCHAR)MB_PORT_SERIAL_MASTER); + + mbm_opts->mbm_comm.mode = MB_MODE_RTU; + mbm_opts->mbm_comm.port = MB_UART_PORT; + mbm_opts->mbm_comm.baudrate = MB_DEVICE_SPEED; + mbm_opts->mbm_comm.parity = MB_PARITY_NONE; + + // Initialization of active context of the modbus controller + BaseType_t status = 0; + // Parameter change notification queue + mbm_opts->mbm_event_group = xEventGroupCreate(); + MB_MASTER_CHECK((mbm_opts->mbm_event_group != NULL), + ESP_ERR_NO_MEM, "mb event group error."); + // Create modbus controller task + status = xTaskCreate((void*)&modbus_master_task, + "modbus_matask", + MB_CONTROLLER_STACK_SIZE, + NULL, // No parameters + MB_CONTROLLER_PRIORITY, + &mbm_opts->mbm_task_handle); + if (status != pdPASS) { + vTaskDelete(mbm_opts->mbm_task_handle); + MB_MASTER_CHECK((status == pdPASS), ESP_ERR_NO_MEM, + "mb controller task creation error, xTaskCreate() returns (0x%x).", + (uint32_t)status); + } + MB_MASTER_ASSERT(mbm_opts->mbm_task_handle != NULL); // The task is created but handle is incorrect + + // Initialize public interface methods of the interface + mbm_interface_ptr->init = mbc_serial_master_create; + mbm_interface_ptr->destroy = mbc_serial_master_destroy; + mbm_interface_ptr->setup = mbc_serial_master_setup; + mbm_interface_ptr->start = mbc_serial_master_start; + mbm_interface_ptr->get_cid_info = mbc_serial_master_get_cid_info; + mbm_interface_ptr->get_parameter = mbc_serial_master_get_parameter; + mbm_interface_ptr->send_request = mbc_serial_master_send_request; + mbm_interface_ptr->set_descriptor = mbc_serial_master_set_descriptor; + mbm_interface_ptr->set_parameter = mbc_serial_master_set_parameter; + + mbm_interface_ptr->master_reg_cb_discrete = eMBRegDiscreteCBSerialMaster; + mbm_interface_ptr->master_reg_cb_input = eMBRegInputCBSerialMaster; + mbm_interface_ptr->master_reg_cb_holding = eMBRegHoldingCBSerialMaster; + mbm_interface_ptr->master_reg_cb_coils = eMBRegCoilsCBSerialMaster; + + *handler = mbm_interface_ptr; + + return ESP_OK; +} diff --git a/components/freemodbus/serial_master/modbus_controller/mbc_serial_master.h b/components/freemodbus/serial_master/modbus_controller/mbc_serial_master.h new file mode 100644 index 00000000..ab9f46a6 --- /dev/null +++ b/components/freemodbus/serial_master/modbus_controller/mbc_serial_master.h @@ -0,0 +1,38 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// mbc_serial_master.h Modbus controller serial master implementation header file + +#ifndef _MODBUS_SERIAL_CONTROLLER_MASTER +#define _MODBUS_SERIAL_CONTROLLER_MASTER + +#include // for standard int types definition +#include // for NULL and std defines +#include "soc/soc.h" // for BITN definitions +#include "esp_err.h" // for esp_err_t +#include "esp_modbus_common.h" // for common defines + +/** + * @brief Initialize Modbus controller and stack + * + * @param[out] handler handler(pointer) to master data structure + * @return + * - ESP_OK Success + * - ESP_ERR_NO_MEM Parameter error + */ +esp_err_t mbc_serial_master_create(void** handler); + +#endif // _MODBUS_SERIAL_CONTROLLER_MASTER + diff --git a/components/freemodbus/serial_master/port/port_serial_master.h b/components/freemodbus/serial_master/port/port_serial_master.h new file mode 100644 index 00000000..c639743a --- /dev/null +++ b/components/freemodbus/serial_master/port/port_serial_master.h @@ -0,0 +1,65 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * FreeModbus Libary: ESP32 Port Demo Application + * Copyright (C) 2010 Christian Walter + * + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * IF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: portother.c,v 1.1 2010/06/06 13:07:20 wolti Exp $ + */ +#ifndef _PORT_SERIAL_MASTER_H +#define _PORT_SERIAL_MASTER_H + +/* ----------------------- Platform includes --------------------------------*/ +#include "driver/uart.h" +#include "driver/timer.h" +#include "esp_log.h" // for ESP_LOGE macro +#include "mb_m.h" +#include "port.h" + +/* ----------------------- Defines ------------------------------------------*/ +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif /* __cplusplus */ + +void vMBPortSetMode( UCHAR ucMode ); + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif /* __cplusplus */ + +#endif diff --git a/components/freemodbus/serial_slave/modbus_controller/mbc_serial_slave.c b/components/freemodbus/serial_slave/modbus_controller/mbc_serial_slave.c new file mode 100644 index 00000000..9221279a --- /dev/null +++ b/components/freemodbus/serial_slave/modbus_controller/mbc_serial_slave.c @@ -0,0 +1,521 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// mbc_serial_slave.c +// Implementation of the Modbus controller serial slave + +#include // for calculation of time stamp in milliseconds +#include "esp_log.h" // for log_write +#include "mb.h" // for mb types definition +#include "mbutils.h" // for mbutils functions definition for stack callback +#include "sdkconfig.h" // for KConfig values +#include "esp_modbus_common.h" // for common defines +#include "esp_modbus_slave.h" // for public slave interface types +#include "mbc_slave.h" // for private slave interface types +#include "mbc_serial_slave.h" // for serial slave implementation definitions +#include "port_serial_slave.h" + +// Shared pointer to interface structure +static mb_slave_interface_t* mbs_interface_ptr = NULL; + +// Modbus task function +static void modbus_slave_task(void *pvParameters) +{ + // Modbus interface must be initialized before start + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + + MB_SLAVE_ASSERT(mbs_opts != NULL); + // Main Modbus stack processing cycle + for (;;) { + BaseType_t status = xEventGroupWaitBits(mbs_opts->mbs_event_group, + (BaseType_t)(MB_EVENT_STACK_STARTED), + pdFALSE, // do not clear bits + pdFALSE, + portMAX_DELAY); + // Check if stack started then poll for data + if (status & MB_EVENT_STACK_STARTED) { + (void)eMBPoll(); // allow stack to process data + // Send response buffer + BOOL xSentState = xMBPortSerialTxPoll(); + if (xSentState) { + (void)xMBPortEventPost( EV_FRAME_SENT ); + } + } + } +} + +// Setup Modbus controller parameters +static esp_err_t mbc_serial_slave_setup(void* comm_info) +{ + MB_SLAVE_CHECK((mbs_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + MB_SLAVE_CHECK((comm_info != NULL), ESP_ERR_INVALID_ARG, + "mb wrong communication settings."); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + mb_slave_comm_info_t* comm_settings = (mb_slave_comm_info_t*)comm_info; + MB_SLAVE_CHECK(((comm_settings->mode == MB_MODE_RTU) || (comm_settings->mode == MB_MODE_ASCII)), + ESP_ERR_INVALID_ARG, "mb incorrect mode = (0x%x).", + (uint32_t)comm_settings->mode); + MB_SLAVE_CHECK((comm_settings->slave_addr <= MB_ADDRESS_MAX), + ESP_ERR_INVALID_ARG, "mb wrong slave address = (0x%x).", + (uint32_t)comm_settings->slave_addr); + MB_SLAVE_CHECK((comm_settings->port < UART_NUM_MAX), ESP_ERR_INVALID_ARG, + "mb wrong port to set = (0x%x).", (uint32_t)comm_settings->port); + MB_SLAVE_CHECK((comm_settings->parity <= UART_PARITY_EVEN), ESP_ERR_INVALID_ARG, + "mb wrong parity option = (0x%x).", (uint32_t)comm_settings->parity); + + // Set communication options of the controller + mbs_opts->mbs_comm = *(mb_communication_info_t*)comm_settings; + return ESP_OK; +} + +// Start Modbus controller start function +static esp_err_t mbc_serial_slave_start(void) +{ + MB_SLAVE_CHECK((mbs_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + eMBErrorCode status = MB_EIO; + // Initialize Modbus stack using mbcontroller parameters + status = eMBInit((eMBMode)mbs_opts->mbs_comm.mode, + (UCHAR)mbs_opts->mbs_comm.slave_addr, + (UCHAR)mbs_opts->mbs_comm.port, + (ULONG)mbs_opts->mbs_comm.baudrate, + (eMBParity)mbs_opts->mbs_comm.parity); + MB_SLAVE_CHECK((status == MB_ENOERR), ESP_ERR_INVALID_STATE, + "mb stack initialization failure, eMBInit() returns (0x%x).", status); + status = eMBEnable(); + MB_SLAVE_CHECK((status == MB_ENOERR), ESP_ERR_INVALID_STATE, + "mb stack set slave ID failure, eMBEnable() returned (0x%x).", (uint32_t)status); + // Set the mbcontroller start flag + EventBits_t flag = xEventGroupSetBits(mbs_opts->mbs_event_group, + (EventBits_t)MB_EVENT_STACK_STARTED); + MB_SLAVE_CHECK((flag & MB_EVENT_STACK_STARTED), + ESP_ERR_INVALID_STATE, "mb stack start event set error."); + return ESP_OK; +} + +// Modbus controller destroy function +static esp_err_t mbc_serial_slave_destroy(void) +{ + MB_SLAVE_CHECK((mbs_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + eMBErrorCode mb_error = MB_ENOERR; + // Stop polling by clearing correspondent bit in the event group + EventBits_t flag = xEventGroupClearBits(mbs_opts->mbs_event_group, + (EventBits_t)MB_EVENT_STACK_STARTED); + MB_SLAVE_CHECK((flag & MB_EVENT_STACK_STARTED), + ESP_ERR_INVALID_STATE, "mb stack stop event failure."); + // Disable and then destroy the Modbus stack + mb_error = eMBDisable(); + MB_SLAVE_CHECK((mb_error == MB_ENOERR), ESP_ERR_INVALID_STATE, "mb stack disable failure."); + (void)vTaskDelete(mbs_opts->mbs_task_handle); + (void)vQueueDelete(mbs_opts->mbs_notification_queue_handle); + (void)vEventGroupDelete(mbs_opts->mbs_event_group); + mb_error = eMBClose(); + MB_SLAVE_CHECK((mb_error == MB_ENOERR), ESP_ERR_INVALID_STATE, + "mb stack close failure returned (0x%x).", (uint32_t)mb_error); + free(mbs_interface_ptr); + vMBPortSetMode((UCHAR)MB_PORT_INACTIVE); + mbs_interface_ptr = NULL; + return ESP_OK; +} + +esp_err_t mbc_serial_slave_set_descriptor(const mb_register_area_descriptor_t descr_info) +{ + MB_SLAVE_CHECK((mbs_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + MB_SLAVE_CHECK(((descr_info.type < MB_PARAM_COUNT) && (descr_info.type >= MB_PARAM_HOLDING)), + ESP_ERR_INVALID_ARG, "mb incorrect modbus instance type = (0x%x).", + (uint32_t)descr_info.type); + MB_SLAVE_CHECK((descr_info.address != NULL), + ESP_ERR_INVALID_ARG, "mb instance pointer is NULL."); + MB_SLAVE_CHECK((descr_info.size >= MB_INST_MIN_SIZE) && (descr_info.size < (MB_INST_MAX_SIZE)), + ESP_ERR_INVALID_ARG, "mb instance size is incorrect = (0x%x).", + (uint32_t)descr_info.size); + mbs_opts->mbs_area_descriptors[descr_info.type] = descr_info; + return ESP_OK; +} + +// The helper function to get time stamp in microseconds +static uint64_t get_time_stamp(void) +{ + uint64_t time_stamp = esp_timer_get_time(); + return time_stamp; +} + +// Helper function to send parameter information to application task +static esp_err_t send_param_info(mb_event_group_t par_type, uint16_t mb_offset, + uint8_t* par_address, uint16_t par_size) +{ + MB_SLAVE_CHECK((mbs_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + esp_err_t error = ESP_FAIL; + mb_param_info_t par_info; + // Check if queue is not full the send parameter information + par_info.type = par_type; + par_info.size = par_size; + par_info.address = par_address; + par_info.time_stamp = get_time_stamp(); + par_info.mb_offset = mb_offset; + BaseType_t status = xQueueSend(mbs_opts->mbs_notification_queue_handle, + &par_info, MB_PAR_INFO_TOUT); + if (pdTRUE == status) { + ESP_LOGD(MB_SLAVE_TAG, "Queue send parameter info (type, address, size): %d, 0x%.4x, %d", + par_type, (uint32_t)par_address, par_size); + error = ESP_OK; + } else if (errQUEUE_FULL == status) { + ESP_LOGD(MB_SLAVE_TAG, "Parameter queue is overflowed."); + } + return error; +} + +// Helper function to send notification +static esp_err_t send_param_access_notification(mb_event_group_t event) +{ + MB_SLAVE_CHECK((mbs_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + esp_err_t err = ESP_FAIL; + mb_event_group_t bits = (mb_event_group_t)xEventGroupSetBits(mbs_opts->mbs_event_group, + (EventBits_t)event); + if (bits & event) { + ESP_LOGD(MB_SLAVE_TAG, "The MB_REG_CHANGE_EVENT = 0x%.2x is set.", (uint8_t)event); + err = ESP_OK; + } + return err; +} + +// Blocking function to get event on parameter group change for application task +static mb_event_group_t mbc_serial_slave_check_event(mb_event_group_t group) +{ + MB_SLAVE_CHECK((mbs_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + MB_SLAVE_ASSERT(mbs_opts->mbs_event_group != NULL); + BaseType_t status = xEventGroupWaitBits(mbs_opts->mbs_event_group, (BaseType_t)group, + pdTRUE , pdFALSE, portMAX_DELAY); + return (mb_event_group_t)status; +} + +// Function to get notification about parameter change from application task +static esp_err_t mbc_serial_slave_get_param_info(mb_param_info_t* reg_info, uint32_t timeout) +{ + MB_SLAVE_CHECK((mbs_interface_ptr != NULL), + ESP_ERR_INVALID_STATE, + "Slave interface is not correctly initialized."); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + esp_err_t err = ESP_ERR_TIMEOUT; + MB_SLAVE_CHECK((mbs_opts->mbs_notification_queue_handle != NULL), + ESP_ERR_INVALID_ARG, "mb queue handle is invalid."); + MB_SLAVE_CHECK((reg_info != NULL), ESP_ERR_INVALID_ARG, "mb register information is invalid."); + BaseType_t status = xQueueReceive(mbs_opts->mbs_notification_queue_handle, + reg_info, pdMS_TO_TICKS(timeout)); + if (status == pdTRUE) { + err = ESP_OK; + } + return err; +} + +/* ----------------------- Callback functions for Modbus stack ---------------------------------*/ +// These are executed by modbus stack to read appropriate type of registers. + +// This is required to suppress warning when register start address is zero +#pragma GCC diagnostic ignored "-Wtype-limits" + +// Callback function for reading of MB Input Registers +eMBErrorCode eMBRegInputCBSerialSlave(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs) +{ + MB_SLAVE_CHECK((mbs_interface_ptr != NULL), + MB_EILLSTATE, "Slave stack uninitialized."); + MB_SLAVE_CHECK((pucRegBuffer != NULL), + MB_EINVAL, "Slave stack call failed."); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + USHORT usRegInputNregs = (USHORT)(mbs_opts->mbs_area_descriptors[MB_PARAM_INPUT].size >> 1); // Number of input registers + USHORT usInputRegStart = (USHORT)mbs_opts->mbs_area_descriptors[MB_PARAM_INPUT].start_offset; // Get Modbus start address + UCHAR* pucInputBuffer = (UCHAR*)mbs_opts->mbs_area_descriptors[MB_PARAM_INPUT].address; // Get instance address + USHORT usRegs = usNRegs; + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegIndex; + // If input or configuration parameters are incorrect then return an error to stack layer + if ((usAddress >= usInputRegStart) + && (pucInputBuffer != NULL) + && (usNRegs >= 1) + && ((usAddress + usRegs) <= (usInputRegStart + usRegInputNregs + 1)) + && (usRegInputNregs >= 1)) { + iRegIndex = (USHORT)(usAddress - usInputRegStart - 1); + iRegIndex <<= 1; // register Address to byte address + pucInputBuffer += iRegIndex; + UCHAR* pucBufferStart = pucInputBuffer; + while (usRegs > 0) { + _XFER_2_RD(pucRegBuffer, pucInputBuffer); + iRegIndex += 2; + usRegs -= 1; + } + // Send access notification + (void)send_param_access_notification(MB_EVENT_INPUT_REG_RD); + // Send parameter info to application task + (void)send_param_info(MB_EVENT_INPUT_REG_RD, (uint16_t)usAddress, + (uint8_t*)pucBufferStart, (uint16_t)usNRegs); + } else { + eStatus = MB_ENOREG; + } + return eStatus; +} + +// Callback function for reading of MB Holding Registers +// Executed by stack when request to read/write holding registers is received +eMBErrorCode eMBRegHoldingCBSerialSlave(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs, eMBRegisterMode eMode) +{ + MB_SLAVE_CHECK((mbs_interface_ptr != NULL), + MB_EILLSTATE, "Slave stack uninitialized."); + MB_SLAVE_CHECK((pucRegBuffer != NULL), + MB_EINVAL, "Slave stack call failed."); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + USHORT usRegHoldingNregs = (USHORT)(mbs_opts->mbs_area_descriptors[MB_PARAM_HOLDING].size >> 1); + USHORT usRegHoldingStart = (USHORT)mbs_opts->mbs_area_descriptors[MB_PARAM_HOLDING].start_offset; + UCHAR* pucHoldingBuffer = (UCHAR*)mbs_opts->mbs_area_descriptors[MB_PARAM_HOLDING].address; + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegIndex; + USHORT usRegs = usNRegs; + // Check input and configuration parameters for correctness + if ((usAddress >= usRegHoldingStart) + && (pucHoldingBuffer != NULL) + && ((usAddress + usRegs) <= (usRegHoldingStart + usRegHoldingNregs + 1)) + && (usRegHoldingNregs >= 1) + && (usNRegs >= 1)) { + iRegIndex = (USHORT) (usAddress - usRegHoldingStart - 1); + iRegIndex <<= 1; // register Address to byte address + pucHoldingBuffer += iRegIndex; + UCHAR* pucBufferStart = pucHoldingBuffer; + switch (eMode) { + case MB_REG_READ: + while (usRegs > 0) { + _XFER_2_RD(pucRegBuffer, pucHoldingBuffer); + iRegIndex += 2; + usRegs -= 1; + }; + // Send access notification + (void)send_param_access_notification(MB_EVENT_HOLDING_REG_RD); + // Send parameter info + (void)send_param_info(MB_EVENT_HOLDING_REG_RD, (uint16_t)usAddress, + (uint8_t*)pucBufferStart, (uint16_t)usNRegs); + break; + case MB_REG_WRITE: + while (usRegs > 0) { + _XFER_2_WR(pucHoldingBuffer, pucRegBuffer); + pucHoldingBuffer += 2; + iRegIndex += 2; + usRegs -= 1; + }; + // Send access notification + (void)send_param_access_notification(MB_EVENT_HOLDING_REG_WR); + // Send parameter info + (void)send_param_info(MB_EVENT_HOLDING_REG_WR, (uint16_t)usAddress, + (uint8_t*)pucBufferStart, (uint16_t)usNRegs); + break; + } + } else { + eStatus = MB_ENOREG; + } + return eStatus; +} + +// Callback function for reading of MB Coils Registers +eMBErrorCode eMBRegCoilsCBSerialSlave(UCHAR* pucRegBuffer, USHORT usAddress, + USHORT usNCoils, eMBRegisterMode eMode) +{ + MB_SLAVE_CHECK((mbs_interface_ptr != NULL), + MB_EILLSTATE, "Slave stack uninitialized."); + MB_SLAVE_CHECK((pucRegBuffer != NULL), + MB_EINVAL, "Slave stack call failed."); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + USHORT usRegCoilNregs = (USHORT)(mbs_opts->mbs_area_descriptors[MB_PARAM_COIL].size >> 1); // number of registers in storage area + USHORT usRegCoilsStart = (USHORT)mbs_opts->mbs_area_descriptors[MB_PARAM_COIL].start_offset; // MB offset of coils registers + UCHAR* pucRegCoilsBuf = (UCHAR*)mbs_opts->mbs_area_descriptors[MB_PARAM_COIL].address; + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegIndex; + USHORT usCoils = usNCoils; + usAddress--; // The address is already +1 + if ((usAddress >= usRegCoilsStart) + && (usRegCoilNregs >= 1) + && ((usAddress + usCoils) <= (usRegCoilsStart + (usRegCoilNregs << 4) + 1)) + && (pucRegCoilsBuf != NULL) + && (usNCoils >= 1)) { + iRegIndex = (USHORT) (usAddress - usRegCoilsStart); + CHAR* pucCoilsDataBuf = (CHAR*)(pucRegCoilsBuf + (iRegIndex >> 3)); + switch (eMode) { + case MB_REG_READ: + while (usCoils > 0) { + UCHAR ucResult = xMBUtilGetBits((UCHAR*)pucRegCoilsBuf, iRegIndex, 1); + xMBUtilSetBits(pucRegBuffer, iRegIndex - (usAddress - usRegCoilsStart), 1, ucResult); + iRegIndex++; + usCoils--; + } + // Send an event to notify application task about event + (void)send_param_access_notification(MB_EVENT_COILS_RD); + (void)send_param_info(MB_EVENT_COILS_RD, (uint16_t)usAddress, + (uint8_t*)(pucCoilsDataBuf), (uint16_t)usNCoils); + break; + case MB_REG_WRITE: + while (usCoils > 0) { + UCHAR ucResult = xMBUtilGetBits(pucRegBuffer, + iRegIndex - (usAddress - usRegCoilsStart), 1); + xMBUtilSetBits((uint8_t*)pucRegCoilsBuf, iRegIndex, 1, ucResult); + iRegIndex++; + usCoils--; + } + // Send an event to notify application task about event + (void)send_param_access_notification(MB_EVENT_COILS_WR); + (void)send_param_info(MB_EVENT_COILS_WR, (uint16_t)usAddress, + (uint8_t*)pucCoilsDataBuf, (uint16_t)usNCoils); + break; + } // switch ( eMode ) + } else { + // If the configuration or input parameters are incorrect then return error to stack + eStatus = MB_ENOREG; + } + return eStatus; +} + +// Callback function for reading of MB Discrete Input Registers +eMBErrorCode eMBRegDiscreteCBSerialSlave(UCHAR* pucRegBuffer, USHORT usAddress, + USHORT usNDiscrete) +{ + MB_SLAVE_CHECK((mbs_interface_ptr != NULL), + MB_EILLSTATE, "Slave stack uninitialized."); + MB_SLAVE_CHECK((pucRegBuffer != NULL), + MB_EINVAL, "Slave stack call failed."); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + USHORT usRegDiscreteNregs = (USHORT)(mbs_opts->mbs_area_descriptors[MB_PARAM_DISCRETE].size >> 1); // number of registers in storage area + USHORT usRegDiscreteStart = (USHORT)mbs_opts->mbs_area_descriptors[MB_PARAM_DISCRETE].start_offset; // MB offset of registers + UCHAR* pucRegDiscreteBuf = (UCHAR*)mbs_opts->mbs_area_descriptors[MB_PARAM_DISCRETE].address; // the storage address + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegIndex, iRegBitIndex, iNReg; + UCHAR* pucDiscreteInputBuf; + iNReg = usNDiscrete / 8 + 1; + pucDiscreteInputBuf = (UCHAR*) pucRegDiscreteBuf; + // It already plus one in modbus function method. + usAddress--; + if ((usAddress >= usRegDiscreteStart) + && (usRegDiscreteNregs >= 1) + && (pucRegDiscreteBuf != NULL) + && ((usAddress + usNDiscrete) <= (usRegDiscreteStart + (usRegDiscreteNregs * 16))) + && (usNDiscrete >= 1)) { + iRegIndex = (USHORT) (usAddress - usRegDiscreteStart) / 8; // Get register index in the buffer for bit number + iRegBitIndex = (USHORT)(usAddress - usRegDiscreteStart) % 8; // Get bit index + UCHAR* pucTempBuf = &pucDiscreteInputBuf[iRegIndex]; + while (iNReg > 0) { + *pucRegBuffer++ = xMBUtilGetBits(&pucDiscreteInputBuf[iRegIndex++], iRegBitIndex, 8); + iNReg--; + } + pucRegBuffer--; + // Last discrete + usNDiscrete = usNDiscrete % 8; + // Filling zero to high bit + *pucRegBuffer = *pucRegBuffer << (8 - usNDiscrete); + *pucRegBuffer = *pucRegBuffer >> (8 - usNDiscrete); + // Send an event to notify application task about event + (void)send_param_access_notification(MB_EVENT_DISCRETE_RD); + (void)send_param_info(MB_EVENT_DISCRETE_RD, (uint16_t)usAddress, + (uint8_t*)pucTempBuf, (uint16_t)usNDiscrete); + } else { + eStatus = MB_ENOREG; + } + return eStatus; +} +#pragma GCC diagnostic pop // require GCC + +// Initialization of Modbus controller +esp_err_t mbc_serial_slave_create(void** handler) +{ + // Allocate space for options + if (mbs_interface_ptr == NULL) { + mbs_interface_ptr = malloc(sizeof(mb_slave_interface_t)); + } + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + + vMBPortSetMode((UCHAR)MB_PORT_SERIAL_SLAVE); + + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + mbs_opts->port_type = MB_PORT_SERIAL_SLAVE; // set interface port type + + // Set default values of communication options + mbs_opts->mbs_comm.mode = MB_MODE_RTU; + mbs_opts->mbs_comm.slave_addr = MB_DEVICE_ADDRESS; + mbs_opts->mbs_comm.port = MB_UART_PORT; + mbs_opts->mbs_comm.baudrate = MB_DEVICE_SPEED; + mbs_opts->mbs_comm.parity = MB_PARITY_NONE; + + // Initialization of active context of the Modbus controller + BaseType_t status = 0; + // Parameter change notification queue + mbs_opts->mbs_event_group = xEventGroupCreate(); + MB_SLAVE_CHECK((mbs_opts->mbs_event_group != NULL), + ESP_ERR_NO_MEM, "mb event group error."); + // Parameter change notification queue + mbs_opts->mbs_notification_queue_handle = xQueueCreate( + MB_CONTROLLER_NOTIFY_QUEUE_SIZE, + sizeof(mb_param_info_t)); + MB_SLAVE_CHECK((mbs_opts->mbs_notification_queue_handle != NULL), + ESP_ERR_NO_MEM, "mb notify queue creation error."); + // Create Modbus controller task + status = xTaskCreate((void*)&modbus_slave_task, + "modbus_slave_task", + MB_CONTROLLER_STACK_SIZE, + NULL, + MB_CONTROLLER_PRIORITY, + &mbs_opts->mbs_task_handle); + if (status != pdPASS) { + vTaskDelete(mbs_opts->mbs_task_handle); + MB_SLAVE_CHECK((status == pdPASS), ESP_ERR_NO_MEM, + "mb controller task creation error, xTaskCreate() returns (0x%x).", + (uint32_t)status); + } + MB_SLAVE_ASSERT(mbs_opts->mbs_task_handle != NULL); // The task is created but handle is incorrect + + // Initialize interface function pointers + mbs_interface_ptr->check_event = mbc_serial_slave_check_event; + mbs_interface_ptr->destroy = mbc_serial_slave_destroy; + mbs_interface_ptr->get_param_info = mbc_serial_slave_get_param_info; + mbs_interface_ptr->init = mbc_serial_slave_create; + mbs_interface_ptr->set_descriptor = mbc_serial_slave_set_descriptor; + mbs_interface_ptr->setup = mbc_serial_slave_setup; + mbs_interface_ptr->start = mbc_serial_slave_start; + + // Initialize stack callback function pointers + mbs_interface_ptr->slave_reg_cb_discrete = eMBRegDiscreteCBSerialSlave; + mbs_interface_ptr->slave_reg_cb_input = eMBRegInputCBSerialSlave; + mbs_interface_ptr->slave_reg_cb_holding = eMBRegHoldingCBSerialSlave; + mbs_interface_ptr->slave_reg_cb_coils = eMBRegCoilsCBSerialSlave; + + *handler = (void*)mbs_interface_ptr; + + return ESP_OK; +} + diff --git a/components/freemodbus/serial_slave/modbus_controller/mbc_serial_slave.h b/components/freemodbus/serial_slave/modbus_controller/mbc_serial_slave.h new file mode 100644 index 00000000..85558e96 --- /dev/null +++ b/components/freemodbus/serial_slave/modbus_controller/mbc_serial_slave.h @@ -0,0 +1,40 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// mbc_serial_slave.h Modbus controller serial slave implementation header file + +#ifndef _MODBUS_SERIAL_CONTROLLER_SLAVE +#define _MODBUS_SERIAL_CONTROLLER_SLAVE + +#include // for standard int types definition +#include // for NULL and std defines +#include "esp_modbus_common.h" // for common defines + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_CONTROLLER_NOTIFY_QUEUE_SIZE (CONFIG_FMB_CONTROLLER_NOTIFY_QUEUE_SIZE) // Number of messages in parameter notification queue +#define MB_CONTROLLER_NOTIFY_TIMEOUT (pdMS_TO_TICKS(CONFIG_FMB_CONTROLLER_NOTIFY_TIMEOUT)) // notification timeout + +/* + * @brief Initialize Modbus controller and stack + * + * @param[out] handler handler(pointer) to master data structure + * @return + * - ESP_OK Success + * - ESP_ERR_NO_MEM Parameter error + */ +esp_err_t mbc_serial_slave_create(void** handler); + +#endif // _MODBUS_SERIAL_CONTROLLER_SLAVE + diff --git a/components/freemodbus/serial_slave/port/port_serial_slave.h b/components/freemodbus/serial_slave/port/port_serial_slave.h new file mode 100644 index 00000000..16d299cb --- /dev/null +++ b/components/freemodbus/serial_slave/port/port_serial_slave.h @@ -0,0 +1,67 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * FreeModbus Libary: ESP32 Port Demo Application + * Copyright (C) 2010 Christian Walter + * + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * IF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * File: $Id: portother.c,v 1.1 2010/06/06 13:07:20 wolti Exp $ + */ +#ifndef _PORT_SERIAL_SLAVE_H +#define _PORT_SERIAL_SLAVE_H + +/* ----------------------- Platform includes --------------------------------*/ + +#include "driver/uart.h" +#include "driver/timer.h" +#include "esp_log.h" +#include "port.h" + +/* ----------------------- Defines ------------------------------------------*/ +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif /* __cplusplus */ + +BOOL xMBPortSerialTxPoll( void ); + +void vMBPortSetMode( UCHAR ucMode ); + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif /* __cplusplus */ + +#endif diff --git a/components/freemodbus/tcp_master/modbus_controller/mbc_tcp_master.c b/components/freemodbus/tcp_master/modbus_controller/mbc_tcp_master.c new file mode 100644 index 00000000..5b5bb325 --- /dev/null +++ b/components/freemodbus/tcp_master/modbus_controller/mbc_tcp_master.c @@ -0,0 +1,716 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// mbc_tcp_master.c +// TCP master implementation of the Modbus controller + +#include // for calculation of time stamp in milliseconds +#include "esp_log.h" // for log_write +#include // for memcpy +#include "freertos/FreeRTOS.h" // for task creation and queue access +#include "freertos/task.h" // for task api access +#include "freertos/event_groups.h" // for event groups +#include "freertos/queue.h" // for queue api access +#include "mb_m.h" // for modbus stack master types definition +#include "port.h" // for port callback functions and defines +#include "mbutils.h" // for mbutils functions definition for stack callback +#include "sdkconfig.h" // for KConfig values +#include "esp_modbus_common.h" // for common types +#include "esp_modbus_master.h" // for public master types +#include "mbc_master.h" // for private master types +#include "mbc_tcp_master.h" // for tcp master create function and types +#include "port_tcp_master.h" // for tcp master port defines and types + +/*-----------------------Master mode use these variables----------------------*/ + +// The response time is average processing time + data transmission +#define MB_RESPONSE_TIMEOUT pdMS_TO_TICKS(CONFIG_FMB_MASTER_TIMEOUT_MS_RESPOND) + +static mb_master_interface_t* mbm_interface_ptr = NULL; + +// Modbus event processing task +static void modbus_tcp_master_task(void *pvParameters) +{ + MB_MASTER_ASSERT(mbm_interface_ptr != NULL); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + MB_MASTER_ASSERT(mbm_opts != NULL); + + // Main Modbus stack processing cycle + for (;;) { + // Wait for poll events + BaseType_t status = xEventGroupWaitBits(mbm_opts->mbm_event_group, + (BaseType_t)(MB_EVENT_STACK_STARTED), + pdFALSE, // do not clear bits + pdFALSE, + portMAX_DELAY); + // Check if stack started then poll for data + if (status & MB_EVENT_STACK_STARTED) { + (void)eMBMasterPoll(); // Allow stack to process data + } + } +} + +// Setup Modbus controller parameters +static esp_err_t mbc_tcp_master_setup(void* comm_info) +{ + MB_MASTER_ASSERT(mbm_interface_ptr != NULL); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + MB_MASTER_CHECK((mbm_opts != NULL), ESP_ERR_INVALID_ARG, "mb incorrect options pointer."); + + const mb_communication_info_t* comm_info_ptr = (mb_communication_info_t*)comm_info; + // Check communication options + MB_MASTER_CHECK((comm_info_ptr->ip_mode == MB_MODE_TCP), + ESP_ERR_INVALID_ARG, "mb incorrect mode = (0x%x).", + (uint32_t)comm_info_ptr->ip_mode); + MB_MASTER_CHECK((comm_info_ptr->ip_addr != NULL), + ESP_ERR_INVALID_ARG, "mb wrong slave ip address table."); + MB_MASTER_CHECK(((comm_info_ptr->ip_addr_type == MB_IPV4) || (comm_info_ptr->ip_addr_type == MB_IPV6)), + ESP_ERR_INVALID_ARG, "mb incorrect addr type = (0x%x).", (uint8_t)comm_info_ptr->ip_addr_type); + MB_MASTER_CHECK((comm_info_ptr->ip_netif_ptr != NULL), + ESP_ERR_INVALID_ARG, "mb incorrect iface address."); + // Save the communication options + mbm_opts->mbm_comm = *(mb_communication_info_t*)comm_info_ptr; + return ESP_OK; +} + +// Modbus controller stack start function +static esp_err_t mbc_tcp_master_start(void) +{ + MB_MASTER_ASSERT(mbm_interface_ptr != NULL); + eMBErrorCode status = MB_EIO; + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + MB_MASTER_CHECK((mbm_opts != NULL), ESP_ERR_INVALID_ARG, "mb incorrect options pointer."); + const mb_communication_info_t* comm_info = (mb_communication_info_t*)&mbm_opts->mbm_comm; + + // Initialize Modbus stack using mbcontroller parameters + status = eMBMasterTCPInit((USHORT)comm_info->ip_port); + MB_MASTER_CHECK((status == MB_ENOERR), ESP_ERR_INVALID_STATE, + "mb stack initialization failure, eMBMasterInit() returns (0x%x).", status); + + MB_MASTER_CHECK((mbm_opts->mbm_param_descriptor_size >= 1), ESP_ERR_INVALID_ARG, "mb table size is incorrect."); + + bool result = false; + const char** comm_ip_table = (const char**)comm_info->ip_addr; + MB_MASTER_CHECK((comm_ip_table != NULL), ESP_ERR_INVALID_ARG, "mb ip table address is incorrect."); + + eMBPortProto proto = (comm_info->ip_mode == MB_MODE_TCP) ? MB_PROTO_TCP : MB_PROTO_UDP; + eMBPortIpVer ip_ver = (comm_info->ip_addr_type == MB_IPV4) ? MB_PORT_IPV4 : MB_PORT_IPV6; + vMBTCPPortMasterSetNetOpt(comm_info->ip_netif_ptr, ip_ver, proto); + vMBTCPPortMasterTaskStart(); + + // Add slave IP address for each slave to initialise connection + for (int idx = 0; *comm_ip_table != NULL; idx++, comm_ip_table++) + { + result = (BOOL)xMBTCPPortMasterAddSlaveIp(*comm_ip_table); + MB_MASTER_CHECK(result, ESP_ERR_INVALID_STATE, "mb stack add slave IP failed: %s.", *comm_ip_table); + } + // Add end of list condition + (void)xMBTCPPortMasterAddSlaveIp(NULL); + + status = eMBMasterEnable(); + MB_MASTER_CHECK((status == MB_ENOERR), ESP_ERR_INVALID_STATE, + "mb stack set slave ID failure, eMBMasterEnable() returned (0x%x).", (uint32_t)status); + + bool start = (bool)xMBTCPPortMasterWaitEvent(mbm_opts->mbm_event_group, (EventBits_t)MB_EVENT_STACK_STARTED); + MB_MASTER_CHECK((start), ESP_ERR_INVALID_STATE, "mb stack start failed."); + return ESP_OK; +} + +// Modbus controller destroy function +static esp_err_t mbc_tcp_master_destroy(void) +{ + MB_MASTER_ASSERT(mbm_interface_ptr != NULL); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + MB_MASTER_CHECK((mbm_opts != NULL), ESP_ERR_INVALID_ARG, "mb incorrect options pointer."); + eMBErrorCode mb_error = MB_ENOERR; + + // Stop polling by clearing correspondent bit in the event group + xEventGroupClearBits(mbm_opts->mbm_event_group, + (EventBits_t)MB_EVENT_STACK_STARTED); + // Disable and then destroy the Modbus stack + mb_error = eMBMasterDisable(); + MB_MASTER_CHECK((mb_error == MB_ENOERR), ESP_ERR_INVALID_STATE, "mb stack disable failure."); + (void)vTaskDelete(mbm_opts->mbm_task_handle); + (void)vEventGroupDelete(mbm_opts->mbm_event_group); + mb_error = eMBMasterClose(); + MB_MASTER_CHECK((mb_error == MB_ENOERR), ESP_ERR_INVALID_STATE, + "mb stack close failure returned (0x%x).", (uint32_t)mb_error); + free(mbm_interface_ptr); // free the memory allocated for options + vMBPortSetMode((UCHAR)MB_PORT_INACTIVE); + mbm_interface_ptr = NULL; + return ESP_OK; +} + +// Set Modbus parameter description table +static esp_err_t mbc_tcp_master_set_descriptor(const mb_parameter_descriptor_t* descriptor, const uint16_t num_elements) +{ + MB_MASTER_ASSERT(mbm_interface_ptr != NULL); + MB_MASTER_CHECK((descriptor != NULL), ESP_ERR_INVALID_ARG, "mb incorrect descriptor."); + MB_MASTER_CHECK((num_elements >= 1), ESP_ERR_INVALID_ARG, "mb table size is incorrect."); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + MB_MASTER_CHECK((mbm_opts != NULL), ESP_ERR_INVALID_ARG, "mb options."); + + const char** comm_ip_table = (const char**)mbm_opts->mbm_comm.ip_addr; + MB_MASTER_CHECK((comm_ip_table != NULL), ESP_ERR_INVALID_ARG, "mb ip table address is incorrect."); + + const mb_parameter_descriptor_t *reg_ptr = descriptor; + // Go through all items in the table to check all Modbus registers + for (uint16_t counter = 0; counter < (num_elements); counter++, reg_ptr++) + { + MB_MASTER_CHECK((comm_ip_table[reg_ptr->mb_slave_addr - 1] != NULL), ESP_ERR_INVALID_ARG, "mb ip table address is incorrect."); + // Below is the code to check consistency of the table format and required fields. + MB_MASTER_CHECK((reg_ptr->cid == counter), ESP_ERR_INVALID_ARG, "mb descriptor cid field is incorrect."); + MB_MASTER_CHECK((reg_ptr->param_key != NULL), ESP_ERR_INVALID_ARG, "mb descriptor param key is incorrect."); + MB_MASTER_CHECK((reg_ptr->mb_size > 0), ESP_ERR_INVALID_ARG, "mb descriptor param size is incorrect."); + } + mbm_opts->mbm_param_descriptor_table = descriptor; + mbm_opts->mbm_param_descriptor_size = num_elements; + return ESP_OK; +} + +// Send custom Modbus request defined as mb_param_request_t structure +static esp_err_t mbc_tcp_master_send_request(mb_param_request_t* request, void* data_ptr) +{ + MB_MASTER_ASSERT(mbm_interface_ptr != NULL); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + MB_MASTER_CHECK((request != NULL), ESP_ERR_INVALID_ARG, "mb request structure."); + MB_MASTER_CHECK((data_ptr != NULL), ESP_ERR_INVALID_ARG, "mb incorrect data pointer."); + + eMBMasterReqErrCode mb_error = MB_MRE_NO_REG; + esp_err_t error = ESP_FAIL; + + uint8_t mb_slave_addr = request->slave_addr; + uint8_t mb_command = request->command; + uint16_t mb_offset = request->reg_start; + uint16_t mb_size = request->reg_size; + + // Set the buffer for callback function processing of received data + mbm_opts->mbm_reg_buffer_ptr = (uint8_t*)data_ptr; + mbm_opts->mbm_reg_buffer_size = mb_size; + + // Calls appropriate request function to send request and waits response + switch(mb_command) + { + case MB_FUNC_READ_COILS: + mb_error = eMBMasterReqReadCoils((UCHAR)mb_slave_addr, (USHORT)mb_offset, + (USHORT)mb_size , (LONG)MB_RESPONSE_TIMEOUT ); + break; + case MB_FUNC_WRITE_SINGLE_COIL: + mb_error = eMBMasterReqWriteCoil((UCHAR)mb_slave_addr, (USHORT)mb_offset, + *(USHORT*)data_ptr, (LONG)MB_RESPONSE_TIMEOUT ); + break; + case MB_FUNC_WRITE_MULTIPLE_COILS: + mb_error = eMBMasterReqWriteMultipleCoils((UCHAR)mb_slave_addr, (USHORT)mb_offset, + (USHORT)mb_size, (UCHAR*)data_ptr, + (LONG)MB_RESPONSE_TIMEOUT); + break; + case MB_FUNC_READ_DISCRETE_INPUTS: + mb_error = eMBMasterReqReadDiscreteInputs((UCHAR)mb_slave_addr, (USHORT)mb_offset, + (USHORT)mb_size, (LONG)MB_RESPONSE_TIMEOUT ); + break; + case MB_FUNC_READ_HOLDING_REGISTER: + mb_error = eMBMasterReqReadHoldingRegister((UCHAR)mb_slave_addr, (USHORT)mb_offset, + (USHORT)mb_size, (LONG)MB_RESPONSE_TIMEOUT ); + break; + case MB_FUNC_WRITE_REGISTER: + mb_error = eMBMasterReqWriteHoldingRegister( (UCHAR)mb_slave_addr, (USHORT)mb_offset, + *(USHORT*)data_ptr, (LONG)MB_RESPONSE_TIMEOUT ); + break; + + case MB_FUNC_WRITE_MULTIPLE_REGISTERS: + mb_error = eMBMasterReqWriteMultipleHoldingRegister( (UCHAR)mb_slave_addr, + (USHORT)mb_offset, (USHORT)mb_size, + (USHORT*)data_ptr, (LONG)MB_RESPONSE_TIMEOUT ); + break; + case MB_FUNC_READWRITE_MULTIPLE_REGISTERS: + mb_error = eMBMasterReqReadWriteMultipleHoldingRegister( (UCHAR)mb_slave_addr, (USHORT)mb_offset, + (USHORT)mb_size, (USHORT*)data_ptr, + (USHORT)mb_offset, (USHORT)mb_size, + (LONG)MB_RESPONSE_TIMEOUT ); + break; + case MB_FUNC_READ_INPUT_REGISTER: + mb_error = eMBMasterReqReadInputRegister( (UCHAR)mb_slave_addr, (USHORT)mb_offset, + (USHORT)mb_size, (LONG) MB_RESPONSE_TIMEOUT ); + break; + default: + ESP_LOGE(MB_MASTER_TAG, "%s: Incorrect function in request (%u) ", + __FUNCTION__, mb_command); + mb_error = MB_MRE_NO_REG; + break; + } + + // Propagate the Modbus errors to higher level + switch(mb_error) + { + case MB_MRE_NO_ERR: + error = ESP_OK; + break; + + case MB_MRE_NO_REG: + error = ESP_ERR_NOT_SUPPORTED; // Invalid register request + break; + + case MB_MRE_TIMEDOUT: + error = ESP_ERR_TIMEOUT; // Slave did not send response + break; + + case MB_MRE_EXE_FUN: + case MB_MRE_REV_DATA: + error = ESP_ERR_INVALID_RESPONSE; // Invalid response from slave + break; + + case MB_MRE_MASTER_BUSY: + error = ESP_ERR_INVALID_STATE; // Master is busy (previous request is pending) + break; + + default: + ESP_LOGE(MB_MASTER_TAG, "%s: Incorrect return code (%x) ", __FUNCTION__, mb_error); + error = ESP_FAIL; + break; + } + + return error; +} + +static esp_err_t mbc_tcp_master_get_cid_info(uint16_t cid, const mb_parameter_descriptor_t** param_buffer) +{ + MB_MASTER_ASSERT(mbm_interface_ptr != NULL); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + + MB_MASTER_CHECK((param_buffer != NULL), ESP_ERR_INVALID_ARG, "mb incorrect data buffer pointer."); + MB_MASTER_CHECK((mbm_opts->mbm_param_descriptor_table != NULL), ESP_ERR_INVALID_ARG, "mb incorrect descriptor table or not set."); + MB_MASTER_CHECK((cid < mbm_opts->mbm_param_descriptor_size), ESP_ERR_NOT_FOUND, "mb incorrect cid of characteristic."); + + // It is assumed that characteristics cid increased in the table + const mb_parameter_descriptor_t* reg_info = &mbm_opts->mbm_param_descriptor_table[cid]; + + MB_MASTER_CHECK((reg_info->param_key != NULL), ESP_ERR_INVALID_ARG, "mb incorrect characteristic key."); + *param_buffer = reg_info; + return ESP_OK; +} + +// Helper function to get modbus command for each type of Modbus register area +static uint8_t mbc_tcp_master_get_command(mb_param_type_t param_type, mb_param_mode_t mode) +{ + uint8_t command = 0; + switch(param_type) + { // + case MB_PARAM_HOLDING: + command = (mode == MB_PARAM_WRITE) ? MB_FUNC_WRITE_MULTIPLE_REGISTERS : MB_FUNC_READ_HOLDING_REGISTER; + break; + case MB_PARAM_INPUT: + command = MB_FUNC_READ_INPUT_REGISTER; + break; + case MB_PARAM_COIL: + command = (mode == MB_PARAM_WRITE) ? MB_FUNC_WRITE_MULTIPLE_COILS : MB_FUNC_READ_COILS; + break; + case MB_PARAM_DISCRETE: + if (mode != MB_PARAM_WRITE) { + command = MB_FUNC_READ_DISCRETE_INPUTS; + } else { + ESP_LOGE(MB_MASTER_TAG, "%s: Incorrect mode (%u)", __FUNCTION__, (uint8_t)mode); + } + break; + default: + ESP_LOGE(MB_MASTER_TAG, "%s: Incorrect param type (%u)", __FUNCTION__, param_type); + break; + } + return command; +} + +// Helper function to set parameter buffer according to its type +static esp_err_t mbc_tcp_master_set_param_data(void* dest, void* src, mb_descr_type_t param_type, size_t param_size) +{ + esp_err_t err = ESP_OK; + MB_MASTER_CHECK((dest != NULL), ESP_ERR_INVALID_ARG, "incorrect parameter pointer."); + MB_MASTER_CHECK((src != NULL), ESP_ERR_INVALID_ARG, "incorrect parameter pointer."); + // Transfer parameter data into value of characteristic + switch(param_type) + { + case PARAM_TYPE_U8: + *((uint8_t*)dest) = *((uint8_t*)src); + break; + case PARAM_TYPE_U16: + *((uint16_t*)dest) = *((uint16_t*)src); + break; + case PARAM_TYPE_U32: + *((uint32_t*)dest) = *((uint32_t*)src); + break; + case PARAM_TYPE_FLOAT: + *((float*)dest) = *(float*)src; + break; + case PARAM_TYPE_ASCII: + memcpy((void*)dest, (void*)src, (size_t)param_size); + break; + default: + ESP_LOGE(MB_MASTER_TAG, "%s: Incorrect param type (%u).", + __FUNCTION__, (uint16_t)param_type); + err = ESP_ERR_NOT_SUPPORTED; + break; + } + return err; +} + +// Helper to search parameter by name in the parameter description table and fills Modbus request fields accordingly +static esp_err_t mbc_tcp_master_set_request(char* name, mb_param_mode_t mode, mb_param_request_t* request, + mb_parameter_descriptor_t* reg_data) +{ + MB_MASTER_ASSERT(mbm_interface_ptr != NULL); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + esp_err_t error = ESP_ERR_NOT_FOUND; + MB_MASTER_CHECK((name != NULL), ESP_ERR_INVALID_ARG, "mb incorrect parameter name."); + MB_MASTER_CHECK((request != NULL), ESP_ERR_INVALID_ARG, "mb incorrect request parameter."); + MB_MASTER_CHECK((mode <= MB_PARAM_WRITE), ESP_ERR_INVALID_ARG, "mb incorrect mode."); + MB_MASTER_ASSERT(mbm_opts->mbm_param_descriptor_table != NULL); + const mb_parameter_descriptor_t* reg_ptr = mbm_opts->mbm_param_descriptor_table; + for (uint16_t counter = 0; counter < (mbm_opts->mbm_param_descriptor_size); counter++, reg_ptr++) + { + // Check the cid of the parameter is equal to record number in the table + // Check the length of name and parameter key strings from table + size_t param_key_len = strlen((const char*)reg_ptr->param_key); + if (param_key_len != strlen((const char*)name)) { + continue; // The length of strings is different then check next record in the table + } + // Compare the name of parameter with parameter key from table + uint8_t comp_result = memcmp((const char*)name, (const char*)reg_ptr->param_key, (size_t)param_key_len); + if (comp_result == 0) { + // The correct line is found in the table and reg_ptr points to the found parameter description + request->slave_addr = reg_ptr->mb_slave_addr; + request->reg_start = reg_ptr->mb_reg_start; + request->reg_size = reg_ptr->mb_size; + request->command = mbc_tcp_master_get_command(reg_ptr->mb_param_type, mode); + MB_MASTER_CHECK((request->command > 0), ESP_ERR_INVALID_ARG, "mb incorrect command or parameter type."); + if (reg_data != NULL) { + *reg_data = *reg_ptr; // Set the cid registered parameter data + } + error = ESP_OK; + break; + } + } + return error; +} + +// Get parameter data for corresponding characteristic +static esp_err_t mbc_tcp_master_get_parameter(uint16_t cid, char* name, uint8_t* value, uint8_t *type) +{ + MB_MASTER_CHECK((name != NULL), ESP_ERR_INVALID_ARG, "mb incorrect descriptor."); + MB_MASTER_CHECK((type != NULL), ESP_ERR_INVALID_ARG, "type pointer is incorrect."); + esp_err_t error = ESP_ERR_INVALID_RESPONSE; + mb_param_request_t request ; + mb_parameter_descriptor_t reg_info = { 0 }; + uint8_t param_buffer[PARAM_MAX_SIZE] = { 0 }; + + error = mbc_tcp_master_set_request(name, MB_PARAM_READ, &request, ®_info); + if ((error == ESP_OK) && (cid == reg_info.cid)) { + error = mbc_tcp_master_send_request(&request, ¶m_buffer[0]); + if (error == ESP_OK) { + // If data pointer is NULL then we don't need to set value (it is still in the cache of cid) + if (value != NULL) { + error = mbc_tcp_master_set_param_data((void*)value, (void*)¶m_buffer[0], + reg_info.param_type, reg_info.param_size); + MB_MASTER_CHECK((error == ESP_OK), ESP_ERR_INVALID_STATE, "fail to set parameter data."); + } + ESP_LOGD(MB_MASTER_TAG, "%s: Good response for get cid(%u) = %s", + __FUNCTION__, (int)reg_info.cid, (char*)esp_err_to_name(error)); + } else { + ESP_LOGD(MB_MASTER_TAG, "%s: Bad response to get cid(%u) = %s", + __FUNCTION__, reg_info.cid, (char*)esp_err_to_name(error)); + } + // Set the type of parameter found in the table + *type = reg_info.param_type; + } else { + ESP_LOGD(MB_MASTER_TAG, "%s: The cid(%u) not found in the data dictionary.", + __FUNCTION__, reg_info.cid); + } + return error; +} + +// Set parameter value for characteristic selected by name and cid +static esp_err_t mbc_tcp_master_set_parameter(uint16_t cid, char* name, uint8_t* value, uint8_t *type) +{ + MB_MASTER_CHECK((name != NULL), ESP_ERR_INVALID_ARG, "mb incorrect descriptor."); + MB_MASTER_CHECK((value != NULL), ESP_ERR_INVALID_ARG, "value pointer is incorrect."); + MB_MASTER_CHECK((type != NULL), ESP_ERR_INVALID_ARG, "type pointer is incorrect."); + + esp_err_t error = ESP_ERR_INVALID_RESPONSE; + mb_param_request_t request ; + mb_parameter_descriptor_t reg_info = { 0 }; + uint8_t param_buffer[PARAM_MAX_SIZE] = { 0 }; + + error = mbc_tcp_master_set_request(name, MB_PARAM_WRITE, &request, ®_info); + if ((error == ESP_OK) && (cid == reg_info.cid)) { + // Transfer value of characteristic into parameter buffer + error = mbc_tcp_master_set_param_data((void*)¶m_buffer[0], (void*)value, + reg_info.param_type, reg_info.param_size); + MB_MASTER_CHECK((error == ESP_OK), ESP_ERR_INVALID_STATE, "failure to set parameter data."); + // Send request to write characteristic data + error = mbc_tcp_master_send_request(&request, ¶m_buffer[0]); + if (error == ESP_OK) { + ESP_LOGD(MB_MASTER_TAG, "%s: Good response for set cid(%u) = %s", + __FUNCTION__, (int)reg_info.cid, (char*)esp_err_to_name(error)); + } else { + ESP_LOGD(MB_MASTER_TAG, "%s: Bad response to set cid(%u) = %s", + __FUNCTION__, reg_info.cid, (char*)esp_err_to_name(error)); + } + // Set the type of parameter found in the table + *type = reg_info.param_type; + } else { + ESP_LOGE(MB_MASTER_TAG, "%s: The requested cid(%u) not found in the data dictionary.", + __FUNCTION__, reg_info.cid); + } + return error; +} + +/* ----------------------- Callback functions for Modbus stack ---------------------------------*/ +// These are executed by modbus stack to read appropriate type of registers. + +/** + * Modbus master input register callback function. + * + * @param pucRegBuffer input register buffer + * @param usAddress input register address + * @param usNRegs input register number + * + * @return result + */ +// Callback function for reading of MB Input Registers +eMBErrorCode eMBRegInputCBTcpMaster(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs) +{ + MB_MASTER_ASSERT(mbm_interface_ptr != NULL); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + MB_MASTER_ASSERT(pucRegBuffer != NULL); + USHORT usRegInputNregs = (USHORT)mbm_opts->mbm_reg_buffer_size; // Number of input registers to be transferred + UCHAR* pucInputBuffer = (UCHAR*)mbm_opts->mbm_reg_buffer_ptr; // Get instance address + USHORT usRegs = usNRegs; + eMBErrorCode eStatus = MB_ENOERR; + // If input or configuration parameters are incorrect then return an error to stack layer + if ((pucInputBuffer != NULL) + && (usNRegs >= 1) + && (usRegInputNregs == usRegs)) { + while (usRegs > 0) { + _XFER_2_RD(pucInputBuffer, pucRegBuffer); + usRegs -= 1; + } + } else { + eStatus = MB_ENOREG; + } + return eStatus; +} + +/** + * Modbus master holding register callback function. + * + * @param pucRegBuffer holding register buffer + * @param usAddress holding register address + * @param usNRegs holding register number + * @param eMode read or write + * + * @return result + */ +// Callback function for reading of MB Holding Registers +// Executed by stack when request to read/write holding registers is received +eMBErrorCode eMBRegHoldingCBTcpMaster(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs, eMBRegisterMode eMode) +{ + MB_MASTER_ASSERT(mbm_interface_ptr != NULL); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + MB_MASTER_ASSERT(pucRegBuffer != NULL); + USHORT usRegHoldingNregs = (USHORT)mbm_opts->mbm_reg_buffer_size; + UCHAR* pucHoldingBuffer = (UCHAR*)mbm_opts->mbm_reg_buffer_ptr; + eMBErrorCode eStatus = MB_ENOERR; + USHORT usRegs = usNRegs; + // Check input and configuration parameters for correctness + if ((pucHoldingBuffer != NULL) + && (usRegHoldingNregs == usNRegs) + && (usNRegs >= 1)) { + switch (eMode) { + case MB_REG_WRITE: + while (usRegs > 0) { + _XFER_2_RD(pucRegBuffer, pucHoldingBuffer); + usRegs -= 1; + }; + break; + case MB_REG_READ: + while (usRegs > 0) { + _XFER_2_WR(pucHoldingBuffer, pucRegBuffer); + pucHoldingBuffer += 2; + usRegs -= 1; + }; + break; + } + } else { + eStatus = MB_ENOREG; + } + return eStatus; +} + +/** + * Modbus master coils callback function. + * + * @param pucRegBuffer coils buffer + * @param usAddress coils address + * @param usNCoils coils number + * @param eMode read or write + * + * @return result + */ +// Callback function for reading of MB Coils Registers +eMBErrorCode eMBRegCoilsCBTcpMaster(UCHAR* pucRegBuffer, USHORT usAddress, + USHORT usNCoils, eMBRegisterMode eMode) +{ + MB_MASTER_ASSERT(mbm_interface_ptr != NULL); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + MB_MASTER_ASSERT(NULL != pucRegBuffer); + USHORT usRegCoilNregs = (USHORT)mbm_opts->mbm_reg_buffer_size; + UCHAR* pucRegCoilsBuf = (UCHAR*)mbm_opts->mbm_reg_buffer_ptr; + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegIndex; + USHORT usCoils = usNCoils; + usAddress--; // The address is already + 1 + if ((usRegCoilNregs >= 1) + && (pucRegCoilsBuf != NULL) + && (usNCoils == usRegCoilNregs)) { + iRegIndex = (usAddress % 8); + switch (eMode) { + case MB_REG_WRITE: + while (usCoils > 0) { + UCHAR ucResult = xMBUtilGetBits((UCHAR*)pucRegCoilsBuf, iRegIndex, 1); + xMBUtilSetBits(pucRegBuffer, iRegIndex - (usAddress % 8) , 1, ucResult); + iRegIndex++; + usCoils--; + } + break; + case MB_REG_READ: + while (usCoils > 0) { + UCHAR ucResult = xMBUtilGetBits(pucRegBuffer, iRegIndex - (usAddress % 8), 1); + xMBUtilSetBits((uint8_t*)pucRegCoilsBuf, iRegIndex, 1, ucResult); + iRegIndex++; + usCoils--; + } + break; + } // switch ( eMode ) + } else { + // If the configuration or input parameters are incorrect then return error to stack + eStatus = MB_ENOREG; + } + return eStatus; +} + +/** + * Modbus master discrete callback function. + * + * @param pucRegBuffer discrete buffer + * @param usAddress discrete address + * @param usNDiscrete discrete number + * + * @return result + */ +// Callback function for reading of MB Discrete Input Registers +eMBErrorCode eMBRegDiscreteCBTcpMaster(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNDiscrete) +{ + MB_MASTER_ASSERT(mbm_interface_ptr != NULL); + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + MB_MASTER_ASSERT(pucRegBuffer != NULL); + USHORT usRegDiscreteNregs = (USHORT)mbm_opts->mbm_reg_buffer_size; + UCHAR* pucRegDiscreteBuf = (UCHAR*)mbm_opts->mbm_reg_buffer_ptr; + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegBitIndex, iNReg; + UCHAR* pucDiscreteInputBuf; + iNReg = usNDiscrete / 8 + 1; + pucDiscreteInputBuf = (UCHAR*) pucRegDiscreteBuf; + // It is already plus one in Modbus function method. + usAddress--; + if ((usRegDiscreteNregs >= 1) + && (pucRegDiscreteBuf != NULL) + && (usNDiscrete >= 1)) { + iRegBitIndex = (USHORT)(usAddress) % 8; // Get bit index + while (iNReg > 1) + { + xMBUtilSetBits(pucDiscreteInputBuf++, iRegBitIndex, 8, *pucRegBuffer++); + iNReg--; + } + // last discrete + usNDiscrete = usNDiscrete % 8; + // xMBUtilSetBits has bug when ucNBits is zero + if (usNDiscrete != 0) + { + xMBUtilSetBits(pucDiscreteInputBuf, iRegBitIndex, usNDiscrete, *pucRegBuffer++); + } + } else { + eStatus = MB_ENOREG; + } + return eStatus; +} + +// Initialization of resources for Modbus TCP master controller +esp_err_t mbc_tcp_master_create(void** handler) +{ + // Allocate space for master interface structure + if (mbm_interface_ptr == NULL) { + mbm_interface_ptr = malloc(sizeof(mb_master_interface_t)); + } + MB_MASTER_ASSERT(mbm_interface_ptr != NULL); + + // Initialize interface properties + mb_master_options_t* mbm_opts = &mbm_interface_ptr->opts; + mbm_opts->port_type = MB_PORT_TCP_MASTER; + + vMBPortSetMode((UCHAR)MB_PORT_TCP_MASTER); + + mbm_opts->mbm_comm.ip_mode = MB_MODE_TCP; + mbm_opts->mbm_comm.ip_port = MB_TCP_DEFAULT_PORT; + + // Initialization of active context of the modbus controller + BaseType_t status = 0; + // Parameter change notification queue + mbm_opts->mbm_event_group = xEventGroupCreate(); + MB_MASTER_CHECK((mbm_opts->mbm_event_group != NULL), ESP_ERR_NO_MEM, "mb event group error."); + // Create modbus controller task + status = xTaskCreate((void*)&modbus_tcp_master_task, + "modbus_tcp_master_task", + MB_CONTROLLER_STACK_SIZE, + NULL, // No parameters + MB_CONTROLLER_PRIORITY, + &mbm_opts->mbm_task_handle); + if (status != pdPASS) { + vTaskDelete(mbm_opts->mbm_task_handle); + MB_MASTER_CHECK((status == pdPASS), ESP_ERR_NO_MEM, + "mb controller task creation error, xTaskCreate() returns (0x%x).", + (uint32_t)status); + } + MB_MASTER_ASSERT(mbm_opts->mbm_task_handle != NULL); // The task is created but handle is incorrect + + // Initialize public interface methods of the interface + mbm_interface_ptr->init = mbc_tcp_master_create; + mbm_interface_ptr->destroy = mbc_tcp_master_destroy; + mbm_interface_ptr->setup = mbc_tcp_master_setup; + mbm_interface_ptr->start = mbc_tcp_master_start; + mbm_interface_ptr->get_cid_info = mbc_tcp_master_get_cid_info; + mbm_interface_ptr->get_parameter = mbc_tcp_master_get_parameter; + mbm_interface_ptr->send_request = mbc_tcp_master_send_request; + mbm_interface_ptr->set_descriptor = mbc_tcp_master_set_descriptor; + mbm_interface_ptr->set_parameter = mbc_tcp_master_set_parameter; + + mbm_interface_ptr->master_reg_cb_discrete = eMBRegDiscreteCBTcpMaster; + mbm_interface_ptr->master_reg_cb_input = eMBRegInputCBTcpMaster; + mbm_interface_ptr->master_reg_cb_holding = eMBRegHoldingCBTcpMaster; + mbm_interface_ptr->master_reg_cb_coils = eMBRegCoilsCBTcpMaster; + + *handler = mbm_interface_ptr; + + return ESP_OK; +} diff --git a/components/freemodbus/tcp_master/modbus_controller/mbc_tcp_master.h b/components/freemodbus/tcp_master/modbus_controller/mbc_tcp_master.h new file mode 100644 index 00000000..612f8a1c --- /dev/null +++ b/components/freemodbus/tcp_master/modbus_controller/mbc_tcp_master.h @@ -0,0 +1,43 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +// mbc_tcp_master.h Modbus controller TCP master implementation header file + +#ifndef _MODBUS_TCP_CONTROLLER_MASTER +#define _MODBUS_TCP_CONTROLLER_MASTER + +#include // for standard int types definition +#include // for NULL and std defines +#include "esp_modbus_common.h" // for common defines + +/* ----------------------- Defines ------------------------------------------*/ +#define MB_INST_MIN_SIZE (2) // The minimal size of Modbus registers area in bytes +#define MB_INST_MAX_SIZE (CONFIG_MB_INST_MAX_SIZE) // The maximum size of Modbus area in bytes + +#define MB_CONTROLLER_NOTIFY_QUEUE_SIZE (CONFIG_MB_CONTROLLER_NOTIFY_QUEUE_SIZE) // Number of messages in parameter notification queue +#define MB_CONTROLLER_NOTIFY_TIMEOUT (pdMS_TO_TICKS(CONFIG_MB_CONTROLLER_NOTIFY_TIMEOUT)) // notification timeout + +/** + * @brief Create Modbus Master controller and stack for TCP port + * + * @param[out] handler handler(pointer) to master data structure + * @return + * - ESP_OK Success + * - ESP_ERR_NO_MEM Parameter error + */ +esp_err_t mbc_tcp_master_create(void** handler); + +#endif // _MODBUS_TCP_CONTROLLER_SLAVE + diff --git a/components/freemodbus/tcp_master/port/port_tcp_master.c b/components/freemodbus/tcp_master/port/port_tcp_master.c new file mode 100644 index 00000000..0bd76ea2 --- /dev/null +++ b/components/freemodbus/tcp_master/port/port_tcp_master.c @@ -0,0 +1,941 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ +/* + * FreeModbus Libary: ESP32 TCP Port + * Copyright (C) 2006 Christian Walter + * Parts of crt0.S Copyright (c) 1995, 1996, 1998 Cygnus Support + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * File: $Id: port.h,v 1.2 2006/09/04 14:39:20 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include +#include +#include "esp_err.h" + +/* ----------------------- lwIP includes ------------------------------------*/ +#include "lwip/err.h" +#include "lwip/sockets.h" +#include "lwip/netdb.h" +#include "esp_netif.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb_m.h" +#include "port.h" +#include "mbport.h" +#include "mbframe.h" +#include "port_tcp_master.h" + +/* ----------------------- Defines -----------------------------------------*/ +#define MB_TCP_CONNECTION_TIMEOUT_MS ( 20 ) // Connection timeout in mS +#define MB_TCP_RECONNECT_TIMEOUT ( 5000000 ) // Connection timeout in uS + +#define MB_TCP_MASTER_PORT_TAG "MB_TCP_MASTER_PORT" +#define MB_EVENT_REQ_DONE_MASK ( EV_MASTER_PROCESS_SUCCESS | \ + EV_MASTER_ERROR_RESPOND_TIMEOUT | \ + EV_MASTER_ERROR_RECEIVE_DATA | \ + EV_MASTER_ERROR_EXECUTE_FUNCTION ) + +#define MB_EVENT_REQ_ERR_MASK ( EV_MASTER_PROCESS_SUCCESS ) + +#define MB_EVENT_WAIT_TOUT_MS ( 2000 ) + +#define MB_TCP_READ_TICK_MS ( 1 ) +#define MB_TCP_READ_BUF_RETRY_CNT ( 4 ) +#define MB_SLAVE_FMT(fmt) "Slave #%d, Socket(#%d)(%s)"fmt + +/* ----------------------- Types & Prototypes --------------------------------*/ +void vMBPortEventClose( void ); + +/* ----------------------- Static variables ---------------------------------*/ +static MbPortConfig_t xMbPortConfig; +static EventGroupHandle_t xMasterEventHandle = NULL; +static EventBits_t xMasterEvent = 0; + +/* ----------------------- Static functions ---------------------------------*/ +static void vMBTCPPortMasterTask(void *pvParameters); + +/* ----------------------- Begin implementation -----------------------------*/ + +// Waits for stack start event to start Modbus event processing +BOOL xMBTCPPortMasterWaitEvent(EventGroupHandle_t xEventHandle, EventBits_t xEvent) +{ + xMasterEventHandle = xEventHandle; + xMasterEvent = xEvent; + BaseType_t status = xEventGroupWaitBits(xMasterEventHandle, + (BaseType_t)(xEvent), + pdFALSE, // do not clear start bit + pdFALSE, + portMAX_DELAY); + return (BOOL)(status & xEvent); +} + +BOOL +xMBMasterTCPPortInit( USHORT usTCPPort ) +{ + BOOL bOkay = FALSE; + + xMbPortConfig.pxMbSlaveInfo = calloc(MB_TCP_PORT_MAX_CONN, sizeof(MbSlaveInfo_t*)); + if (!xMbPortConfig.pxMbSlaveInfo) { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "TCP slave info alloc failure."); + return FALSE; + } + for(int idx = 0; idx < MB_TCP_PORT_MAX_CONN; xMbPortConfig.pxMbSlaveInfo[idx] = NULL, idx++); + + xMbPortConfig.xConnectQueue = NULL; + xMbPortConfig.usPort = usTCPPort; + xMbPortConfig.usMbSlaveInfoCount = 0; + xMbPortConfig.ucCurSlaveIndex = 1; + + xMbPortConfig.xConnectQueue = xQueueCreate(2, sizeof(CHAR*)); + if (xMbPortConfig.xConnectQueue == 0) + { + // Queue was not created and must not be used. + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "TCP master queue creation failure."); + return FALSE; + } + + // Create task for packet processing + BaseType_t xErr = xTaskCreate(vMBTCPPortMasterTask, + "tcp_master_task", + MB_TCP_STACK_SIZE, + NULL, + MB_TCP_TASK_PRIO, + &xMbPortConfig.xMbTcpTaskHandle); + if (xErr != pdTRUE) + { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "TCP master task creation failure."); + (void)vTaskDelete(xMbPortConfig.xMbTcpTaskHandle); + } else { + ESP_LOGI(MB_TCP_MASTER_PORT_TAG, "TCP master stack initialized."); + bOkay = TRUE; + } + + vTaskSuspend(xMbPortConfig.xMbTcpTaskHandle); + return bOkay; +} + +static MbSlaveInfo_t* vMBTCPPortMasterGetCurrInfo(void) +{ + return xMbPortConfig.pxMbSlaveInfo[xMbPortConfig.ucCurSlaveIndex - 1]; +} + +// Start Modbus event state machine +static void vMBTCPPortMasterStartPoll(void) +{ + if (xMasterEventHandle) { + // Set the mbcontroller start flag + EventBits_t xFlags = xEventGroupSetBits(xMasterEventHandle, + (EventBits_t)xMasterEvent); + if (!(xFlags & xMasterEvent)) { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "Fail to start TCP stack."); + } + } +} + +// Stop Modbus event state machine +static void vMBTCPPortMasterStopPoll(void) +{ + if (xMasterEventHandle) { + // Set the mbcontroller start flag + EventBits_t xFlags = xEventGroupClearBits(xMasterEventHandle, + (EventBits_t)xMasterEvent); + if (!(xFlags & xMasterEvent)) { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "Fail to stop polling."); + } + } +} + +// The helper function to get time stamp in microseconds +static int64_t xMBTCPGetTimeStamp(void) +{ + int64_t xTimeStamp = esp_timer_get_time(); + return xTimeStamp; +} + +static void vMBTCPPortMasterMStoTimeVal(USHORT usTimeoutMs, struct timeval *tv) +{ + tv->tv_sec = usTimeoutMs / 1000; + tv->tv_usec = (usTimeoutMs - (tv->tv_sec * 1000)) * 1000; +} + +static BOOL xMBTCPPortMasterCloseConnection(MbSlaveInfo_t* pxInfo) +{ + if (!pxInfo) { + return FALSE; + } + if (pxInfo->xSockId == -1) { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "Wrong socket info or disconnected socket: %d, skip.", pxInfo->xSockId); + return FALSE; + } + if (shutdown(pxInfo->xSockId, SHUT_RDWR) == -1) { + ESP_LOGV(MB_TCP_MASTER_PORT_TAG, "Shutdown failed sock %d, errno=%d", pxInfo->xSockId, errno); + } + close(pxInfo->xSockId); + pxInfo->xSockId = -1; + return TRUE; +} + +void vMBTCPPortMasterSetNetOpt(void* pvNetIf, eMBPortIpVer xIpVersion, eMBPortProto xProto) +{ + xMbPortConfig.pvNetIface = pvNetIf; + xMbPortConfig.eMbProto = xProto; + xMbPortConfig.eMbIpVer = xIpVersion; +} + +void vMBTCPPortMasterTaskStart(void) +{ + vTaskResume(xMbPortConfig.xMbTcpTaskHandle); +} + +// Function returns time left for response processing according to response timeout +static int64_t xMBTCPPortMasterGetRespTimeLeft(MbSlaveInfo_t* pxInfo) +{ + if (!pxInfo) { + return 0; + } + int64_t xTimeStamp = xMBTCPGetTimeStamp() - pxInfo->xSendTimeStamp; + return (xTimeStamp > (1000 * MB_MASTER_TIMEOUT_MS_RESPOND)) ? 0 : + (MB_MASTER_TIMEOUT_MS_RESPOND - (xTimeStamp / 1000) - 1); +} + +// Wait socket ready to read state +static int vMBTCPPortMasterRxCheck(int xSd, fd_set* pxFdSet, int xTimeMs) +{ + fd_set xReadSet = *pxFdSet; + fd_set xErrorSet = *pxFdSet; + int xRes = 0; + struct timeval xTimeout; + + vMBTCPPortMasterMStoTimeVal(xTimeMs, &xTimeout); + xRes = select(xSd + 1, &xReadSet, NULL, &xErrorSet, &xTimeout); + if (xRes == 0) { + // No respond from slave during timeout + xRes = ERR_TIMEOUT; + } else if ((xRes < 0) || FD_ISSET(xSd, &xErrorSet)) { + xRes = -1; + } + + *pxFdSet = xReadSet; + return xRes; +} + +static int xMBTCPPortMasterGetBuf(MbSlaveInfo_t* pxInfo, UCHAR* pucDstBuf, USHORT usLength) +{ + int xLength = 0; + UCHAR* pucBuf = pucDstBuf; + USHORT usBytesLeft = usLength; + + MB_PORT_CHECK((pxInfo && pxInfo->xSockId > -1), -1, "Try to read incorrect socket = #%d.", pxInfo->xSockId); + + // Receive data from connected client + while (usBytesLeft > 0) { + // none blocking read from socket with timeout + xLength = recv(pxInfo->xSockId, pucBuf, usBytesLeft, MSG_DONTWAIT); + if (xLength < 0) { + if (errno == EAGAIN) { + // Read timeout occurred, continue reading + continue; + } else if (errno == ENOTCONN) { + // Socket connection closed + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "Socket(#%d)(%s) connection closed.", + pxInfo->xSockId, pxInfo->pcIpAddr); + return ERR_CONN; + } else { + // Other error occurred during receiving + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "Socket(#%d)(%s) receive error, length=%d, errno=%d", + pxInfo->xSockId, pxInfo->pcIpAddr, xLength, errno); + return -1; + } + } else if (xLength) { + pucBuf += xLength; + usBytesLeft -= xLength; + } + if (xMBTCPPortMasterGetRespTimeLeft(pxInfo) == 0) { + return ERR_TIMEOUT; + } + vTaskDelay(1); + } + return usLength; +} + +static int vMBTCPPortMasterReadPacket(MbSlaveInfo_t* pxInfo) +{ + int xLength = 0; + int xRet = 0; + USHORT usTidRcv = 0; + + // Receive data from connected client + if (pxInfo) { + MB_PORT_CHECK((pxInfo->xSockId > 0), -1, "Try to read incorrect socket = #%d.", pxInfo->xSockId); + // Read packet header + xRet = xMBTCPPortMasterGetBuf(pxInfo, &pxInfo->pucRcvBuf[0], MB_TCP_UID); + if (xRet < 0) { + pxInfo->xRcvErr = xRet; + return xRet; + } else if (xRet != MB_TCP_UID) { + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, "Socket (#%d)(%s), Fail to read modbus header. ret=%d", + pxInfo->xSockId, pxInfo->pcIpAddr, xRet); + pxInfo->xRcvErr = ERR_VAL; + return ERR_VAL; + } + // If we have received the MBAP header we can analyze it and calculate + // the number of bytes left to complete the current request. + xLength = (int)MB_TCP_GET_FIELD(pxInfo->pucRcvBuf, MB_TCP_LEN); + xRet = xMBTCPPortMasterGetBuf(pxInfo, &pxInfo->pucRcvBuf[MB_TCP_UID], xLength); + if (xRet < 0) { + pxInfo->xRcvErr = xRet; + return xRet; + } else if (xRet != xLength) { + // Received incorrect or fragmented packet. + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, "Socket(#%d)(%s) incorrect packet, length=%d, TID=0x%02x, errno=%d(%s)", + pxInfo->xSockId, pxInfo->pcIpAddr, pxInfo->usRcvPos, + usTidRcv, errno, strerror(errno)); + pxInfo->xRcvErr = ERR_VAL; + return ERR_VAL; + } + usTidRcv = MB_TCP_GET_FIELD(pxInfo->pucRcvBuf, MB_TCP_TID); + + // Check transaction identifier field in the incoming packet. + if ((pxInfo->usTidCnt - 1) != usTidRcv) { + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, "Socket (#%d)(%s), incorrect TID(0x%02x)!=(0x%02x) received, discard data.", + pxInfo->xSockId, pxInfo->pcIpAddr, usTidRcv, (pxInfo->usTidCnt - 1)); + pxInfo->xRcvErr = ERR_BUF; + return ERR_BUF; + } + pxInfo->usRcvPos += xRet + MB_TCP_UID; + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, "Socket(#%d)(%s) get data, length=%d, TID=0x%02x, errno=%d(%s)", + pxInfo->xSockId, pxInfo->pcIpAddr, pxInfo->usRcvPos, + usTidRcv, errno, strerror(errno)); + pxInfo->xRcvErr = ERR_OK; + return pxInfo->usRcvPos; + } + return -1; +} + +static err_t xMBTCPPortMasterSetNonBlocking(MbSlaveInfo_t* pxInfo) +{ + // Set non blocking attribute for socket + ULONG ulFlags = fcntl(pxInfo->xSockId, F_GETFL); + if (fcntl(pxInfo->xSockId, F_SETFL, ulFlags | O_NONBLOCK) == -1) { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "Socket(#%d)(%s), fcntl() call error=%d", + pxInfo->xSockId, pxInfo->pcIpAddr, errno); + return ERR_WOULDBLOCK; + } + return ERR_OK; +} + +static void vMBTCPPortSetKeepAlive(MbSlaveInfo_t* pxInfo) +{ + int optval = 1; + setsockopt(pxInfo->xSockId, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval)); +} + +// Check connection for timeout helper +static err_t xMBTCPPortMasterCheckAlive(MbSlaveInfo_t* pxInfo, ULONG xTimeoutMs) +{ + fd_set xWriteSet; + fd_set xErrorSet; + err_t xErr = -1; + struct timeval xTimeVal; + + if (pxInfo && pxInfo->xSockId != -1) { + FD_ZERO(&xWriteSet); + FD_ZERO(&xErrorSet); + FD_SET(pxInfo->xSockId, &xWriteSet); + FD_SET(pxInfo->xSockId, &xErrorSet); + vMBTCPPortMasterMStoTimeVal(xTimeoutMs, &xTimeVal); + // Check if the socket is writable + xErr = select(pxInfo->xSockId + 1, NULL, &xWriteSet, &xErrorSet, &xTimeVal); + if ((xErr < 0) || FD_ISSET(pxInfo->xSockId, &xErrorSet)) { + if (errno == EINPROGRESS) { + xErr = ERR_INPROGRESS; + } else { + ESP_LOGV(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(" connection, select write err(errno) = %d(%d)."), + pxInfo->xIndex, pxInfo->xSockId, pxInfo->pcIpAddr, xErr, errno); + xErr = ERR_CONN; + } + } else if (xErr == 0) { + ESP_LOGV(MB_TCP_MASTER_PORT_TAG, "Socket(#%d)(%s), connection timeout occurred, err(errno) = %d(%d).", + pxInfo->xSockId, pxInfo->pcIpAddr, xErr, errno); + return ERR_INPROGRESS; + } else { + int xOptErr = 0; + ULONG ulOptLen = sizeof(xOptErr); + // Check socket error + xErr = getsockopt(pxInfo->xSockId, SOL_SOCKET, SO_ERROR, (void*)&xOptErr, (socklen_t*)&ulOptLen); + if (xOptErr != 0) { + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, "Socket(#%d)(%s), sock error occurred (%d).", + pxInfo->xSockId, pxInfo->pcIpAddr, xOptErr); + return ERR_CONN; + } + ESP_LOGV(MB_TCP_MASTER_PORT_TAG, "Socket(#%d)(%s), is alive.", + pxInfo->xSockId, pxInfo->pcIpAddr); + return ERR_OK; + } + } else { + xErr = ERR_CONN; + } + return xErr; +} + +// Resolve host name and/or fill the IP address structure +static BOOL xMBTCPPortMasterCheckHost(const CHAR* pcHostStr, ip_addr_t* pxHostAddr) +{ + MB_PORT_CHECK((pcHostStr), FALSE, "Wrong host name or IP."); + CHAR cStr[45]; + CHAR* pcStr = &cStr[0]; + ip_addr_t xTargetAddr; + struct addrinfo xHint; + struct addrinfo* pxAddrList; + memset(&xHint, 0, sizeof(xHint)); + // Do name resolution for both protocols + xHint.ai_family = AF_UNSPEC; + xHint.ai_flags = AI_ADDRCONFIG; // get IPV6 address if supported, otherwise IPV4 + memset(&xTargetAddr, 0, sizeof(xTargetAddr)); + + // convert domain name to IP address + // Todo: check EAI_FAIL error when resolve host name + int xRet = getaddrinfo(pcHostStr, NULL, &xHint, &pxAddrList); + + if (xRet != 0) { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "Incorrect host name or IP: %s", pcHostStr); + return FALSE; + } + if (pxAddrList->ai_family == AF_INET) { + struct in_addr addr4 = ((struct sockaddr_in *) (pxAddrList->ai_addr))->sin_addr; + inet_addr_to_ip4addr(ip_2_ip4(&xTargetAddr), &addr4); + pcStr = ip4addr_ntoa_r(ip_2_ip4(&xTargetAddr), cStr, sizeof(cStr)); + } else { + struct in6_addr addr6 = ((struct sockaddr_in6 *) (pxAddrList->ai_addr))->sin6_addr; + inet6_addr_to_ip6addr(ip_2_ip6(&xTargetAddr), &addr6); + pcStr = ip6addr_ntoa_r(ip_2_ip6(&xTargetAddr), cStr, sizeof(cStr)); + } + if (pxHostAddr) { + *pxHostAddr = xTargetAddr; + } + ESP_LOGI(MB_TCP_MASTER_PORT_TAG, "Host[IP]: \"%s\"[%s]", pxAddrList->ai_canonname, pcStr); + freeaddrinfo(pxAddrList); + return TRUE; +} + +BOOL xMBTCPPortMasterAddSlaveIp(const CHAR* pcIpStr) +{ + BOOL xRes = FALSE; + MB_PORT_CHECK(xMbPortConfig.xConnectQueue != NULL, FALSE, "Wrong slave IP address to add."); + if (pcIpStr) { + xRes = xMBTCPPortMasterCheckHost(pcIpStr, NULL); + } + if (xRes || !pcIpStr) { + BaseType_t xStatus = xQueueSend(xMbPortConfig.xConnectQueue, (const void*)&pcIpStr, 100); + MB_PORT_CHECK((xStatus == pdTRUE), FALSE, "FAIL to add slave IP address: [%s].", pcIpStr); + } + return xRes; +} + +// Unblocking connect function +static err_t xMBTCPPortMasterConnect(MbSlaveInfo_t* pxInfo) +{ + err_t xErr = ERR_OK; + CHAR cStr[128]; + CHAR* pcStr = NULL; + ip_addr_t xTargetAddr; + struct addrinfo xHint; + struct addrinfo* pxAddrList; + struct addrinfo* pxCurAddr; + + memset(&xHint, 0, sizeof(xHint)); + // Do name resolution for both protocols + //xHint.ai_family = AF_UNSPEC; Todo: Find a reason why AF_UNSPEC does not work + xHint.ai_flags = AI_ADDRCONFIG; // get IPV6 address if supported, otherwise IPV4 + xHint.ai_family = (xMbPortConfig.eMbIpVer == MB_PORT_IPV4) ? AF_INET : AF_INET6; + xHint.ai_socktype = (pxInfo->xMbProto == MB_PROTO_UDP) ? SOCK_DGRAM : SOCK_STREAM; + xHint.ai_protocol = (pxInfo->xMbProto == MB_PROTO_UDP) ? IPPROTO_UDP : IPPROTO_TCP; + memset(&xTargetAddr, 0, sizeof(xTargetAddr)); + + if (asprintf(&pcStr, "%u", xMbPortConfig.usPort) == -1) { + abort(); + } + + // convert domain name to IP address + int xRet = getaddrinfo(pxInfo->pcIpAddr, pcStr, &xHint, &pxAddrList); + free(pcStr); + if (xRet != 0) { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "Cannot resolve host: %s", pxInfo->pcIpAddr); + return ERR_CONN; + } + + for (pxCurAddr = pxAddrList; pxCurAddr != NULL; pxCurAddr = pxCurAddr->ai_next) { + if (pxCurAddr->ai_family == AF_INET) { + struct in_addr addr4 = ((struct sockaddr_in *) (pxCurAddr->ai_addr))->sin_addr; + inet_addr_to_ip4addr(ip_2_ip4(&xTargetAddr), &addr4); + pcStr = ip4addr_ntoa_r(ip_2_ip4(&xTargetAddr), cStr, sizeof(cStr)); + } else if (pxCurAddr->ai_family == AF_INET6) { + struct in6_addr addr6 = ((struct sockaddr_in6 *) (pxCurAddr->ai_addr))->sin6_addr; + inet6_addr_to_ip6addr(ip_2_ip6(&xTargetAddr), &addr6); + pcStr = ip6addr_ntoa_r(ip_2_ip6(&xTargetAddr), cStr, sizeof(cStr)); + // Set scope id to fix routing issues with local address + ((struct sockaddr_in6 *) (pxCurAddr->ai_addr))->sin6_scope_id = + esp_netif_get_netif_impl_index(xMbPortConfig.pvNetIface); + } + + if (pxInfo->xSockId <= 0) { + pxInfo->xSockId = socket(pxCurAddr->ai_family, pxCurAddr->ai_socktype, pxCurAddr->ai_protocol); + if (pxInfo->xSockId < 0) { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "Unable to create socket: #%d, errno %d", pxInfo->xSockId, errno); + xErr = ERR_IF; + continue; + } + } else { + ESP_LOGV(MB_TCP_MASTER_PORT_TAG, "Socket (#%d)(%s) created.", pxInfo->xSockId, cStr); + } + + // Set non blocking attribute for socket + xMBTCPPortMasterSetNonBlocking(pxInfo); + + // Can return EINPROGRESS as an error which means + // that connection is in progress and should be checked later + xErr = connect(pxInfo->xSockId, (struct sockaddr*)pxCurAddr->ai_addr, pxCurAddr->ai_addrlen); + if ((xErr < 0) && (errno == EINPROGRESS || errno == EALREADY)) { + // The unblocking connect is pending (check status later) or already connected + ESP_LOGV(MB_TCP_MASTER_PORT_TAG, "Socket(#%d)(%s) connection is pending, errno %d (%s).", + pxInfo->xSockId, cStr, errno, strerror(errno)); + + // Set keep alive flag in socket options + vMBTCPPortSetKeepAlive(pxInfo); + xErr = xMBTCPPortMasterCheckAlive(pxInfo, MB_TCP_CONNECTION_TIMEOUT_MS); + continue; + } else if ((xErr < 0) && (errno == EISCONN)) { + // Socket already connected + xErr = ERR_OK; + continue; + } else if (xErr != ERR_OK) { + // Other error occurred during connection + ESP_LOGV(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(" unable to connect, error=%d, errno %d (%s)"), + pxInfo->xIndex, pxInfo->xSockId, cStr, xErr, errno, strerror(errno)); + xMBTCPPortMasterCloseConnection(pxInfo); + xErr = ERR_CONN; + } else { + ESP_LOGI(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", successfully connected."), + pxInfo->xIndex, pxInfo->xSockId, cStr); + continue; + } + } + freeaddrinfo(pxAddrList); + return xErr; +} + +// Find the first slave info whose descriptor is set in xFdSet +static MbSlaveInfo_t* xMBTCPPortMasterGetSlaveReady(fd_set* pxFdSet) +{ + MbSlaveInfo_t* pxInfo = NULL; + + // Slave connection loop + for (int xIndex = 0; (xIndex < MB_TCP_PORT_MAX_CONN); xIndex++) { + pxInfo = xMbPortConfig.pxMbSlaveInfo[xIndex]; + if (pxInfo) { + // Is this response for current processing slave + if (FD_ISSET(pxInfo->xSockId, pxFdSet)) { + FD_CLR(pxInfo->xSockId, pxFdSet); + return pxInfo; + } + } + } + return (MbSlaveInfo_t*)NULL; +} + +static int xMBTCPPortMasterCheckConnState(fd_set* pxFdSet) +{ + fd_set xConnSetCheck = *pxFdSet; + MbSlaveInfo_t* pxInfo = NULL; + int64_t xTime = 0; + int xErr = 0; + int xCount = 0; + do { + xTime = xMBTCPGetTimeStamp(); + pxInfo = xMBTCPPortMasterGetSlaveReady(&xConnSetCheck); + if (pxInfo) { + xErr = xMBTCPPortMasterCheckAlive(pxInfo, 0); + if ((xErr < 0) && (((xTime - pxInfo->xRecvTimeStamp) > MB_TCP_RECONNECT_TIMEOUT) || + ((xTime - pxInfo->xSendTimeStamp) > MB_TCP_RECONNECT_TIMEOUT))) { + ESP_LOGI(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", slave is down, off_time[r][w](us) = [%ju][%ju]."), + pxInfo->xIndex, + pxInfo->xSockId, + pxInfo->pcIpAddr, + (int64_t)(xTime - pxInfo->xRecvTimeStamp), + (int64_t)(xTime - pxInfo->xSendTimeStamp)); + xCount++; + } + } + } while (pxInfo && (xCount < MB_TCP_PORT_MAX_CONN)); + return xCount; +} + +static void xMBTCPPortMasterFsmSetError(eMBMasterErrorEventType xErrType, eMBMasterEventType xPostEvent) +{ + vMBMasterPortTimersDisable(); + vMBMasterSetErrorType(xErrType); + xMBMasterPortEventPost(xPostEvent); +} + +static void vMBTCPPortMasterTask(void *pvParameters) +{ + CHAR* pcAddrStr = NULL; + MbSlaveInfo_t* pxInfo; + MbSlaveInfo_t* pxCurrInfo; + fd_set xConnSet; + fd_set xReadSet; + int xMaxSd = 0; + err_t xErr = ERR_ABRT; + USHORT usSlaveConnCnt = 0; + int64_t xTime = 0; + + // Register each slave in the connection info structure + while (1) { + BaseType_t xStatus = xQueueReceive(xMbPortConfig.xConnectQueue, (void*)&pcAddrStr, portMAX_DELAY); + if (xStatus != pdTRUE) { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "Fail to register slave IP."); + } else { + if (pcAddrStr == NULL && xMbPortConfig.usMbSlaveInfoCount) { + break; + } + if (xMbPortConfig.usMbSlaveInfoCount > MB_TCP_PORT_MAX_CONN) { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "Exceeds maximum connections limit=%d.", MB_TCP_PORT_MAX_CONN); + break; + } + pxInfo = calloc(1, sizeof(MbSlaveInfo_t)); + if (!pxInfo) { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "Slave(#%d), info structure allocation fail.", + xMbPortConfig.usMbSlaveInfoCount); + free(pxInfo); + break; + } + pxInfo->pucRcvBuf = calloc(MB_TCP_BUF_SIZE, sizeof(UCHAR)); + if (!pxInfo->pucRcvBuf) { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "Slave(#%d), receive buffer allocation fail.", + xMbPortConfig.usMbSlaveInfoCount); + free(pxInfo->pucRcvBuf); + break; + } + pxInfo->usRcvPos = 0; + pxInfo->pcIpAddr = pcAddrStr; + pxInfo->xSockId = -1; + pxInfo->xError = -1; + pxInfo->xRecvTimeStamp = xMBTCPGetTimeStamp(); + pxInfo->xSendTimeStamp = xMBTCPGetTimeStamp(); + pxInfo->xMbProto = MB_PROTO_TCP; + pxInfo->xIndex = xMbPortConfig.usMbSlaveInfoCount; + pxInfo->usTidCnt = (USHORT)(xMbPortConfig.usMbSlaveInfoCount << 8U); + // Register slave + xMbPortConfig.pxMbSlaveInfo[xMbPortConfig.usMbSlaveInfoCount++] = pxInfo; + ESP_LOGI(MB_TCP_MASTER_PORT_TAG, "Add slave IP: %s", pcAddrStr); + } + } + + // Main connection cycle + while (1) + { + ESP_LOGI(MB_TCP_MASTER_PORT_TAG, "Connecting to slaves..."); + xTime = xMBTCPGetTimeStamp(); + usSlaveConnCnt = 0; + CHAR ucDot = '.'; + while(usSlaveConnCnt < xMbPortConfig.usMbSlaveInfoCount) { + usSlaveConnCnt = 0; + FD_ZERO(&xConnSet); + ucDot ^= 0x03; + // Slave connection loop + for (UCHAR ucCnt = 0; (ucCnt < MB_TCP_PORT_MAX_CONN); ucCnt++) { + pxInfo = xMbPortConfig.pxMbSlaveInfo[ucCnt]; + // if slave descriptor is NULL then it is end of list or connection closed. + if (!pxInfo) { + ESP_LOGV(MB_TCP_MASTER_PORT_TAG, "Index: %d is not initialized, skip.", ucCnt); + if (xMbPortConfig.usMbSlaveInfoCount) { + continue; + } + break; + } + putchar(ucDot); + xErr = xMBTCPPortMasterConnect(pxInfo); + switch(xErr) + { + case ERR_CONN: + case ERR_INPROGRESS: + // In case of connection errors remove the socket from set + if (FD_ISSET(pxInfo->xSockId, &xConnSet)) { + FD_CLR(pxInfo->xSockId, &xConnSet); + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(" connect failed, error = %d."), + pxInfo->xIndex, pxInfo->xSockId, + (char*)pxInfo->pcIpAddr, xErr); + if (usSlaveConnCnt) { + usSlaveConnCnt--; + } + } + break; + case ERR_OK: + // if connection is successful, add the descriptor into set + if (!FD_ISSET(pxInfo->xSockId, &xConnSet)) { + FD_SET(pxInfo->xSockId, &xConnSet); + usSlaveConnCnt++; + xMaxSd = (pxInfo->xSockId > xMaxSd) ? pxInfo->xSockId : xMaxSd; + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", connected %d slave(s), error = %d."), + pxInfo->xIndex, pxInfo->xSockId, + pxInfo->pcIpAddr, + usSlaveConnCnt, xErr); + // Update time stamp for connected slaves + pxInfo->xRecvTimeStamp = xMBTCPGetTimeStamp(); + pxInfo->xSendTimeStamp = xMBTCPGetTimeStamp(); + } + break; + default: + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", unexpected error = %d."), + pxInfo->xIndex, + pxInfo->xSockId, + pxInfo->pcIpAddr, xErr); + break; + } + pxInfo->xError = xErr; + } + } + ESP_LOGI(MB_TCP_MASTER_PORT_TAG, "Connected %d slaves, start polling...", usSlaveConnCnt); + vMBTCPPortMasterStartPoll(); // Send event to start stack + + // Slave receive data loop + while(usSlaveConnCnt) { + xReadSet = xConnSet; + // Check transmission event to clear appropriate bit. + xMBMasterPortFsmWaitConfirmation(EV_MASTER_FRAME_TRANSMIT, pdMS_TO_TICKS(MB_EVENT_WAIT_TOUT_MS)); + // Synchronize state machine with send packet event + if (xMBMasterPortFsmWaitConfirmation(EV_MASTER_FRAME_SENT, pdMS_TO_TICKS(MB_EVENT_WAIT_TOUT_MS))) { + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, "FSM Synchronized with sent event."); + } + // Get slave info for the current slave. + pxCurrInfo = vMBTCPPortMasterGetCurrInfo(); + if (!pxCurrInfo) { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, "Incorrect connection options for slave index: %d.", + xMbPortConfig.ucCurSlaveIndex); + vMBTCPPortMasterStopPoll(); + break; // incorrect slave descriptor, reconnect. + } + xTime = xMBTCPPortMasterGetRespTimeLeft(pxCurrInfo); + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, "Set select timeout, left time: %ju ms.", + xMBTCPPortMasterGetRespTimeLeft(pxCurrInfo)); + // Wait respond from current slave during respond timeout + int xRes = vMBTCPPortMasterRxCheck(pxCurrInfo->xSockId, &xReadSet, xTime); + if (xRes == ERR_TIMEOUT) { + // No respond from current slave, process timeout. + // Need to drop response later if it is received after timeout. + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, "Select timeout, left time: %ju ms.", + xMBTCPPortMasterGetRespTimeLeft(pxCurrInfo)); + xTime = xMBTCPPortMasterGetRespTimeLeft(pxCurrInfo); + // Wait completion of last transaction + xMBMasterPortFsmWaitConfirmation(MB_EVENT_REQ_DONE_MASK, pdMS_TO_TICKS(xTime + 1)); + continue; + } else if (xRes < 0) { + // Select error (slave connection or r/w failure). + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", socket select error. Slave disconnected?"), + pxCurrInfo->xIndex, pxCurrInfo->xSockId, pxCurrInfo->pcIpAddr); + xTime = xMBTCPPortMasterGetRespTimeLeft(pxCurrInfo); + // Wait completion of last transaction + xMBMasterPortFsmWaitConfirmation(MB_EVENT_REQ_DONE_MASK, pdMS_TO_TICKS(xTime)); + // Stop polling process + vMBTCPPortMasterStopPoll(); + // Check disconnected slaves, do not need a result just to print information. + xMBTCPPortMasterCheckConnState(&xConnSet); + break; + } else { + // Check to make sure that active slave data is ready + if (FD_ISSET(pxCurrInfo->xSockId, &xReadSet)) { + xErr = ERR_BUF; + for (int retry = 0; (xErr == ERR_BUF) && (retry < MB_TCP_READ_BUF_RETRY_CNT); retry++) { + xErr = vMBTCPPortMasterReadPacket(pxCurrInfo); + // The error ERR_BUF means received response to previous request + // (due to timeout) with the same socket ID and incorrect TID, + // then ignore it and try to get next response buffer. + } + if (xErr > 0) { + // Response received correctly, send an event to stack + xMBTCPPortMasterFsmSetError(EV_ERROR_INIT, EV_MASTER_FRAME_RECEIVED); + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", frame received."), + pxCurrInfo->xIndex, pxCurrInfo->xSockId, pxCurrInfo->pcIpAddr); + } else if ((xErr == ERR_TIMEOUT) || (xMBTCPPortMasterGetRespTimeLeft(pxCurrInfo) == 0)) { + // Timeout occurred when receiving frame, process respond timeout + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", frame read timeout."), + pxCurrInfo->xIndex, pxCurrInfo->xSockId, pxCurrInfo->pcIpAddr); + } else if (xErr == ERR_BUF) { + // After retries a response with incorrect TID received, process failure. + xMBTCPPortMasterFsmSetError(EV_ERROR_RECEIVE_DATA, EV_MASTER_ERROR_PROCESS); + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", frame error."), + pxCurrInfo->xIndex, pxCurrInfo->xSockId, pxCurrInfo->pcIpAddr); + } else { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", critical error=%d."), + pxCurrInfo->xIndex, pxCurrInfo->xSockId, pxCurrInfo->pcIpAddr, xErr); + // Stop polling process + vMBTCPPortMasterStopPoll(); + // Check disconnected slaves, do not need a result just to print information. + xMBTCPPortMasterCheckConnState(&xConnSet); + break; + } + xTime = xMBTCPPortMasterGetRespTimeLeft(pxCurrInfo); + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, "Slave #%d, data processing left time %ju [ms].", pxCurrInfo->xIndex, xTime); + // Wait completion of Modbus frame processing before start of new transaction. + if (xMBMasterPortFsmWaitConfirmation(MB_EVENT_REQ_DONE_MASK, pdMS_TO_TICKS(xTime))) { + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", data processing completed."), + pxCurrInfo->xIndex, pxCurrInfo->xSockId, pxCurrInfo->pcIpAddr); + } + xTime = xMBTCPGetTimeStamp() - pxCurrInfo->xSendTimeStamp; + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", processing time[us] = %ju."), + pxCurrInfo->xIndex, pxCurrInfo->xSockId, pxCurrInfo->pcIpAddr, xTime); + } + } + } // while(usMbSlaveInfoCount) + } // while (1) + vTaskDelete(NULL); +} + +extern void vMBMasterPortEventClose(void); +extern void vMBMasterPortTimerClose(void); + +void +vMBMasterTCPPortClose(void) +{ + (void)vTaskDelete(xMbPortConfig.xMbTcpTaskHandle); + (void)vMBMasterTCPPortDisable(); + free(xMbPortConfig.pxMbSlaveInfo); + vQueueDelete(xMbPortConfig.xConnectQueue); + vMBMasterPortTimerClose(); + // Release resources for the event queue. + vMBMasterPortEventClose(); +} + +void +vMBMasterTCPPortDisable(void) +{ + for (USHORT ucCnt = 0; ucCnt < MB_TCP_PORT_MAX_CONN; ucCnt++) { + MbSlaveInfo_t* pxInfo = xMbPortConfig.pxMbSlaveInfo[ucCnt]; + if (pxInfo) { + xMBTCPPortMasterCloseConnection(pxInfo); + if (pxInfo->pucRcvBuf) { + free(pxInfo->pucRcvBuf); + } + free(pxInfo); + xMbPortConfig.pxMbSlaveInfo[ucCnt] = NULL; + } + } +} + +BOOL +xMBMasterTCPPortGetRequest( UCHAR ** ppucMBTCPFrame, USHORT * usTCPLength ) +{ + MbSlaveInfo_t* pxInfo = vMBTCPPortMasterGetCurrInfo(); + *ppucMBTCPFrame = pxInfo->pucRcvBuf; + *usTCPLength = pxInfo->usRcvPos; + + // Reset the buffer. + pxInfo->usRcvPos = 0; + // Save slave receive timestamp + if (pxInfo->xRcvErr == ERR_OK && *usTCPLength > 0) { + pxInfo->xRecvTimeStamp = xMBTCPGetTimeStamp(); + return TRUE; + } + return FALSE; +} + +int xMBMasterTCPPortWritePoll(MbSlaveInfo_t* pxInfo, const UCHAR * pucMBTCPFrame, USHORT usTCPLength, ULONG xTimeout) +{ + // Check if the socket is alive (writable and SO_ERROR == 0) + int xRes = (int)xMBTCPPortMasterCheckAlive(pxInfo, xTimeout); + if ((xRes < 0) && (xRes != ERR_INPROGRESS)) + { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", is not writable, error: %d, errno %d"), + pxInfo->xIndex, pxInfo->xSockId, pxInfo->pcIpAddr, xRes, errno); + return xRes; + } + xRes = send(pxInfo->xSockId, pucMBTCPFrame, usTCPLength, TCP_NODELAY); + if (xRes < 0) { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", send data error: %d, errno %d"), + pxInfo->xIndex, pxInfo->xSockId, pxInfo->pcIpAddr, xRes, errno); + } + return xRes; +} + +BOOL +xMBMasterTCPPortSendResponse( UCHAR * pucMBTCPFrame, USHORT usTCPLength ) +{ + BOOL bFrameSent = FALSE; + xMbPortConfig.ucCurSlaveIndex = ucMBMasterGetDestAddress(); + MbSlaveInfo_t* pxInfo = vMBTCPPortMasterGetCurrInfo(); + + // If socket active then send data + if (pxInfo->xSockId > -1) { + // Apply TID field to the frame before send + pucMBTCPFrame[MB_TCP_TID] = (UCHAR)(pxInfo->usTidCnt >> 8U); + pucMBTCPFrame[MB_TCP_TID + 1] = (UCHAR)(pxInfo->usTidCnt & 0xFF); + int xRes = xMBMasterTCPPortWritePoll(pxInfo, pucMBTCPFrame, usTCPLength, MB_TCP_SEND_TIMEOUT_MS); + if (xRes < 0) { + ESP_LOGE(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", send data failure, err(errno) = %d(%d)."), + pxInfo->xIndex, pxInfo->xSockId, pxInfo->pcIpAddr, xRes, errno); + bFrameSent = FALSE; + pxInfo->xError = xRes; + } else { + bFrameSent = TRUE; + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", send data successful: TID=0x%02x, %d (bytes), errno %d"), + pxInfo->xIndex, pxInfo->xSockId, pxInfo->pcIpAddr, pxInfo->usTidCnt, xRes, errno); + pxInfo->xError = 0; + pxInfo->usRcvPos = 0; + if (pxInfo->usTidCnt < (USHRT_MAX - 1)) { + pxInfo->usTidCnt++; + } else { + pxInfo->usTidCnt = (USHORT)(pxInfo->xIndex << 8U); + } + } + pxInfo->xSendTimeStamp = xMBTCPGetTimeStamp(); + } else { + ESP_LOGD(MB_TCP_MASTER_PORT_TAG, MB_SLAVE_FMT(", send to died slave, error = %d"), + pxInfo->xIndex, pxInfo->xSockId, pxInfo->pcIpAddr, pxInfo->xError); + } + vMBMasterPortTimersRespondTimeoutEnable(); + xMBMasterPortEventPost(EV_MASTER_FRAME_SENT); + return bFrameSent; +} + +// Timer handler to check timeout of socket response +BOOL MB_PORT_ISR_ATTR +xMBMasterTCPTimerExpired(void) +{ + BOOL xNeedPoll = FALSE; + + vMBMasterPortTimersDisable(); + // If timer mode is respond timeout, the master event then turns EV_MASTER_EXECUTE status. + if (xMBMasterGetCurTimerMode() == MB_TMODE_RESPOND_TIMEOUT) { + vMBMasterSetErrorType(EV_ERROR_RESPOND_TIMEOUT); + xNeedPoll = xMBMasterPortEventPost(EV_MASTER_ERROR_PROCESS); + } + + return xNeedPoll; +} diff --git a/components/freemodbus/tcp_master/port/port_tcp_master.h b/components/freemodbus/tcp_master/port/port_tcp_master.h new file mode 100644 index 00000000..c1b0b816 --- /dev/null +++ b/components/freemodbus/tcp_master/port/port_tcp_master.h @@ -0,0 +1,133 @@ + /* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + /* + * FreeModbus Libary: ESP32 TCP Port + * Copyright (C) 2006 Christian Walter + * Parts of crt0.S Copyright (c) 1995, 1996, 1998 Cygnus Support + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * File: $Id: port.h,v 1.2 2006/09/04 14:39:20 wolti Exp $ + */ + +#ifndef _PORT_TCP_SLAVE_H +#define _PORT_TCP_SLAVE_H + +/* ----------------------- Platform includes --------------------------------*/ +#include "esp_log.h" + +#include "lwip/sys.h" +#include "freertos/event_groups.h" +#include "port.h" + +/* ----------------------- Defines ------------------------------------------*/ + +#ifndef TRUE +#define TRUE 1 +#endif + +#ifndef FALSE +#define FALSE 0 +#endif + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +/* ----------------------- Type definitions ---------------------------------*/ + +typedef struct { + int xIndex; /*!< Slave information index */ + int xSockId; /*!< Socket ID of slave */ + int xError; /*!< Socket error */ + int xRcvErr; /*!< Socket receive error */ + const char* pcIpAddr; /*!< TCP/UDP IP address */ + UCHAR* pucRcvBuf; /*!< Receive buffer pointer */ + USHORT usRcvPos; /*!< Receive buffer position */ + int pcPort; /*!< TCP/UDP port number */ + eMBPortProto xMbProto; /*!< Protocol type */ + int64_t xSendTimeStamp; /*!< Send request time stamp */ + int64_t xRecvTimeStamp; /*!< Receive response time stamp */ + uint16_t usTidCnt; /*!< Transaction identifier (TID) for slave */ +} MbSlaveInfo_t; + +typedef struct { + TaskHandle_t xMbTcpTaskHandle; /*!< Master TCP/UDP handling task handle */ + QueueHandle_t xConnectQueue; /*!< Master connection queue */ + USHORT usPort; /*!< Master TCP/UDP port number */ + USHORT usMbSlaveInfoCount; /*!< Master count of connected slaves */ + USHORT ucCurSlaveIndex; /*!< Master current processing slave index */ + eMBPortIpVer eMbIpVer; /*!< Master IP version */ + eMBPortProto eMbProto; /*!< Master protocol type */ + void* pvNetIface; /*!< Master netif interface pointer */ + MbSlaveInfo_t** pxMbSlaveInfo; /*!< Master information structure for each connected slave */ +} MbPortConfig_t; + +/* ----------------------- Function prototypes ------------------------------*/ + +// The functions below are used by Modbus controller interface to configure Modbus port. +/** + * Registers slave IP address + * + * @param pcIpStr IP address to register + * + * @return TRUE if address registered successfully, else FALSE + */ +BOOL xMBTCPPortMasterAddSlaveIp(const CHAR* pcIpStr); + +/** + * Keeps FSM event handle and mask then wait for Master stack to start + * + * @param xEventHandle Master event handle + * @param xEvent event mask to start Modbus stack FSM + * + * @return TRUE if stack started, else FALSE + */ +BOOL xMBTCPPortMasterWaitEvent(EventGroupHandle_t xEventHandle, EventBits_t xEvent); + +/** + * Set network options for Master port + * + * @param pvNetIf netif interface pointer + * @param xIpVersion IP version option for the Master port + * @param xProto Protocol version option for the Master port + * + * @return None + */ +void vMBTCPPortMasterSetNetOpt(void* pvNetIf, eMBPortIpVer xIpVersion, eMBPortProto xProto); + +/** + * Resume TCP/UDP Master processing task + * + * @return None + */ +void vMBTCPPortMasterTaskStart(void); + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/components/freemodbus/tcp_slave/modbus_controller/mbc_tcp_slave.c b/components/freemodbus/tcp_slave/modbus_controller/mbc_tcp_slave.c new file mode 100644 index 00000000..6104a032 --- /dev/null +++ b/components/freemodbus/tcp_slave/modbus_controller/mbc_tcp_slave.c @@ -0,0 +1,484 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +// mbc_tcp_slave.c +// Implementation of the Modbus controller TCP slave + +#include // for calculation of time stamp in milliseconds +#include "esp_log.h" // for log_write +#include "mb.h" // for mb types definition +#include "mbutils.h" // for mbutils functions definition for stack callback +#include "port.h" // for port callback functions and defines +#include "sdkconfig.h" // for KConfig values +#include "esp_modbus_common.h" // for common defines +#include "esp_modbus_slave.h" // for public slave interface types +#include "mbc_slave.h" // for private slave interface types +#include "mbc_tcp_slave.h" // for tcp slave mb controller defines +#include "port_tcp_slave.h" // for tcp slave port defines + +// Shared pointer to interface structure +static mb_slave_interface_t* mbs_interface_ptr = NULL; + +// The helper function to get time stamp in microseconds +static uint64_t get_time_stamp(void) +{ + uint64_t time_stamp = esp_timer_get_time(); + return time_stamp; +} + +// Modbus task function +static void modbus_tcp_slave_task(void *pvParameters) +{ + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + + // Main Modbus stack processing cycle + for (;;) { + BaseType_t status = xEventGroupWaitBits(mbs_opts->mbs_event_group, + (BaseType_t)(MB_EVENT_STACK_STARTED), + pdFALSE, // do not clear bits + pdFALSE, + portMAX_DELAY); + // Check if stack started then poll for data + if (status & MB_EVENT_STACK_STARTED) { + (void)eMBPoll(); // allow stack to process data + } + } +} + +// Setup Modbus controller parameters +static esp_err_t mbc_tcp_slave_setup(void* comm_info) +{ + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + MB_SLAVE_CHECK((comm_info != NULL), ESP_ERR_INVALID_ARG, + "mb wrong communication settings."); + mb_communication_info_t* comm_settings = (mb_communication_info_t*)comm_info; + MB_SLAVE_CHECK((comm_settings->ip_mode == MB_MODE_TCP), + ESP_ERR_INVALID_ARG, "mb incorrect mode = (0x%x).", (uint8_t)comm_settings->ip_mode); + MB_SLAVE_CHECK(((comm_settings->ip_addr_type == MB_IPV4) || (comm_settings->ip_addr_type == MB_IPV6)), + ESP_ERR_INVALID_ARG, "mb incorrect addr type = (0x%x).", (uint8_t)comm_settings->ip_addr_type); + MB_SLAVE_CHECK((comm_settings->ip_netif_ptr != NULL), + ESP_ERR_INVALID_ARG, "mb incorrect iface address."); + // Set communication options of the controller + mbs_opts->mbs_comm = *comm_settings; + return ESP_OK; +} + +// Start Modbus controller start function +static esp_err_t mbc_tcp_slave_start(void) +{ + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + eMBErrorCode status = MB_EIO; + + // Initialize Modbus stack using mbcontroller parameters + status = eMBTCPInit((USHORT)mbs_opts->mbs_comm.ip_port); + MB_SLAVE_CHECK((status == MB_ENOERR), ESP_ERR_INVALID_STATE, + "mb stack initialization failure, eMBInit() returns (0x%x).", status); + + eMBPortProto proto = (mbs_opts->mbs_comm.ip_mode == MB_MODE_TCP) ? MB_PROTO_TCP : MB_PROTO_UDP; + eMBPortIpVer ip_ver = (mbs_opts->mbs_comm.ip_addr_type == MB_IPV4) ? MB_PORT_IPV4 : MB_PORT_IPV6; + vMBTCPPortSlaveSetNetOpt(mbs_opts->mbs_comm.ip_netif_ptr, ip_ver, proto, (char*)mbs_opts->mbs_comm.ip_addr); + vMBTCPPortSlaveStartServerTask(); + + status = eMBEnable(); + MB_SLAVE_CHECK((status == MB_ENOERR), ESP_ERR_INVALID_STATE, + "mb TCP stack start failure, eMBEnable() returned (0x%x).", (uint32_t)status); + // Set the mbcontroller start flag + EventBits_t flag = xEventGroupSetBits(mbs_opts->mbs_event_group, + (EventBits_t)MB_EVENT_STACK_STARTED); + MB_SLAVE_CHECK((flag & MB_EVENT_STACK_STARTED), + ESP_ERR_INVALID_STATE, "mb stack start event set error."); + return ESP_OK; +} + +// Modbus controller destroy function +static esp_err_t mbc_tcp_slave_destroy(void) +{ + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + eMBErrorCode mb_error = MB_ENOERR; + // Stop polling by clearing correspondent bit in the event group + EventBits_t flag = xEventGroupClearBits(mbs_opts->mbs_event_group, + (EventBits_t)MB_EVENT_STACK_STARTED); + MB_SLAVE_CHECK((flag & MB_EVENT_STACK_STARTED), + ESP_ERR_INVALID_STATE, "mb stack stop event failure."); + // Disable and then destroy the Modbus stack + mb_error = eMBDisable(); + MB_SLAVE_CHECK((mb_error == MB_ENOERR), ESP_ERR_INVALID_STATE, "mb stack disable failure."); + (void)vTaskDelete(mbs_opts->mbs_task_handle); + (void)vQueueDelete(mbs_opts->mbs_notification_queue_handle); + (void)vEventGroupDelete(mbs_opts->mbs_event_group); + (void)vMBTCPPortClose(); + free(mbs_interface_ptr); + vMBPortSetMode((UCHAR)MB_PORT_INACTIVE); + mbs_interface_ptr = NULL; + return ESP_OK; +} + +esp_err_t mbc_tcp_slave_set_descriptor(const mb_register_area_descriptor_t descr_info) +{ + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + MB_SLAVE_CHECK(((descr_info.type < MB_PARAM_COUNT) && (descr_info.type >= MB_PARAM_HOLDING)), + ESP_ERR_INVALID_ARG, "mb incorrect modbus instance type = (0x%x).", + (uint32_t)descr_info.type); + MB_SLAVE_CHECK((descr_info.address != NULL), + ESP_ERR_INVALID_ARG, "mb instance pointer is NULL."); + MB_SLAVE_CHECK((descr_info.size >= MB_INST_MIN_SIZE) && (descr_info.size < (MB_INST_MAX_SIZE)), + ESP_ERR_INVALID_ARG, "mb instance size is incorrect = (0x%x).", + (uint32_t)descr_info.size); + mbs_opts->mbs_area_descriptors[descr_info.type] = descr_info; + return ESP_OK; +} + +// Helper function to send parameter information to application task +static esp_err_t send_param_info(mb_event_group_t par_type, uint16_t mb_offset, + uint8_t* par_address, uint16_t par_size) +{ + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + esp_err_t error = ESP_FAIL; + mb_param_info_t par_info; + // Check if queue is not full the send parameter information + par_info.type = par_type; + par_info.size = par_size; + par_info.address = par_address; + par_info.time_stamp = get_time_stamp(); + par_info.mb_offset = mb_offset; + BaseType_t status = xQueueSend(mbs_opts->mbs_notification_queue_handle, + &par_info, MB_PAR_INFO_TOUT); + if (pdTRUE == status) { + ESP_LOGD(MB_SLAVE_TAG, "Queue send parameter info (type, address, size): %d, 0x%.4x, %d", + par_type, (uint32_t)par_address, par_size); + error = ESP_OK; + } else if (errQUEUE_FULL == status) { + ESP_LOGD(MB_SLAVE_TAG, "Parameter queue is overflowed."); + } + return error; +} + +// Helper function to send notification +static esp_err_t send_param_access_notification(mb_event_group_t event) +{ + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + esp_err_t err = ESP_FAIL; + mb_event_group_t bits = (mb_event_group_t)xEventGroupSetBits(mbs_opts->mbs_event_group, + (EventBits_t)event); + if (bits & event) { + ESP_LOGD(MB_SLAVE_TAG, "The MB_REG_CHANGE_EVENT = 0x%.2x is set.", (uint8_t)event); + err = ESP_OK; + } + return err; +} + +// Blocking function to get event on parameter group change for application task +static mb_event_group_t mbc_tcp_slave_check_event(mb_event_group_t group) +{ + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + MB_SLAVE_ASSERT(mbs_opts->mbs_event_group != NULL); + BaseType_t status = xEventGroupWaitBits(mbs_opts->mbs_event_group, (BaseType_t)group, + pdTRUE , pdFALSE, portMAX_DELAY); + return (mb_event_group_t)status; +} + +// Function to get notification about parameter change from application task +static esp_err_t mbc_tcp_slave_get_param_info(mb_param_info_t* reg_info, uint32_t timeout) +{ + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + esp_err_t err = ESP_ERR_TIMEOUT; + MB_SLAVE_CHECK((mbs_opts->mbs_notification_queue_handle != NULL), + ESP_ERR_INVALID_ARG, "mb queue handle is invalid."); + MB_SLAVE_CHECK((reg_info != NULL), ESP_ERR_INVALID_ARG, "mb register information is invalid."); + BaseType_t status = xQueueReceive(mbs_opts->mbs_notification_queue_handle, + reg_info, pdMS_TO_TICKS(timeout)); + if (status == pdTRUE) { + err = ESP_OK; + } + return err; +} + +/* ----------------------- Callback functions for Modbus stack ---------------------------------*/ +// These are executed by modbus stack to read appropriate type of registers. + +// This is required to suppress warning when register start address is zero +#pragma GCC diagnostic ignored "-Wtype-limits" + +// Callback function for reading of MB Input Registers +eMBErrorCode eMBRegInputCBTcpSlave(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs) +{ + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + MB_SLAVE_ASSERT(pucRegBuffer != NULL); + USHORT usRegInputNregs = (USHORT)(mbs_opts->mbs_area_descriptors[MB_PARAM_INPUT].size >> 1); // Number of input registers + USHORT usInputRegStart = (USHORT)mbs_opts->mbs_area_descriptors[MB_PARAM_INPUT].start_offset; // Get Modbus start address + UCHAR* pucInputBuffer = (UCHAR*)mbs_opts->mbs_area_descriptors[MB_PARAM_INPUT].address; // Get instance address + USHORT usRegs = usNRegs; + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegIndex; + // If input or configuration parameters are incorrect then return an error to stack layer + if ((usAddress >= usInputRegStart) + && (pucInputBuffer != NULL) + && (usNRegs >= 1) + && ((usAddress + usRegs) <= (usInputRegStart + usRegInputNregs + 1)) + && (usRegInputNregs >= 1)) { + iRegIndex = (USHORT)(usAddress - usInputRegStart - 1); + iRegIndex <<= 1; // register Address to byte address + pucInputBuffer += iRegIndex; + UCHAR* pucBufferStart = pucInputBuffer; + while (usRegs > 0) { + _XFER_2_RD(pucRegBuffer, pucInputBuffer); + iRegIndex += 2; + usRegs -= 1; + } + // Send access notification + (void)send_param_access_notification(MB_EVENT_INPUT_REG_RD); + // Send parameter info to application task + (void)send_param_info(MB_EVENT_INPUT_REG_RD, (uint16_t)usAddress, + (uint8_t*)pucBufferStart, (uint16_t)usNRegs); + } else { + eStatus = MB_ENOREG; + } + return eStatus; +} + +// Callback function for reading of MB Holding Registers +// Executed by stack when request to read/write holding registers is received +eMBErrorCode eMBRegHoldingCBTcpSlave(UCHAR * pucRegBuffer, USHORT usAddress, + USHORT usNRegs, eMBRegisterMode eMode) +{ + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + MB_SLAVE_ASSERT(pucRegBuffer != NULL); + USHORT usRegHoldingNregs = (USHORT)(mbs_opts->mbs_area_descriptors[MB_PARAM_HOLDING].size >> 1); + USHORT usRegHoldingStart = (USHORT)mbs_opts->mbs_area_descriptors[MB_PARAM_HOLDING].start_offset; + UCHAR* pucHoldingBuffer = (UCHAR*)mbs_opts->mbs_area_descriptors[MB_PARAM_HOLDING].address; + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegIndex; + USHORT usRegs = usNRegs; + // Check input and configuration parameters for correctness + if ((usAddress >= usRegHoldingStart) + && (pucHoldingBuffer != NULL) + && ((usAddress + usRegs) <= (usRegHoldingStart + usRegHoldingNregs + 1)) + && (usRegHoldingNregs >= 1) + && (usNRegs >= 1)) { + iRegIndex = (USHORT) (usAddress - usRegHoldingStart - 1); + iRegIndex <<= 1; // register Address to byte address + pucHoldingBuffer += iRegIndex; + UCHAR* pucBufferStart = pucHoldingBuffer; + switch (eMode) { + case MB_REG_READ: + while (usRegs > 0) { + _XFER_2_RD(pucRegBuffer, pucHoldingBuffer); + iRegIndex += 2; + usRegs -= 1; + }; + // Send access notification + (void)send_param_access_notification(MB_EVENT_HOLDING_REG_RD); + // Send parameter info + (void)send_param_info(MB_EVENT_HOLDING_REG_RD, (uint16_t)usAddress, + (uint8_t*)pucBufferStart, (uint16_t)usNRegs); + break; + case MB_REG_WRITE: + while (usRegs > 0) { + _XFER_2_WR(pucHoldingBuffer, pucRegBuffer); + pucHoldingBuffer += 2; + iRegIndex += 2; + usRegs -= 1; + }; + // Send access notification + (void)send_param_access_notification(MB_EVENT_HOLDING_REG_WR); + // Send parameter info + (void)send_param_info(MB_EVENT_HOLDING_REG_WR, (uint16_t)usAddress, + (uint8_t*)pucBufferStart, (uint16_t)usNRegs); + break; + } + } else { + eStatus = MB_ENOREG; + } + return eStatus; +} + +// Callback function for reading of MB Coils Registers +eMBErrorCode eMBRegCoilsCBTcpSlave(UCHAR* pucRegBuffer, USHORT usAddress, + USHORT usNCoils, eMBRegisterMode eMode) +{ + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + MB_SLAVE_ASSERT(NULL != pucRegBuffer); + USHORT usRegCoilNregs = (USHORT)(mbs_opts->mbs_area_descriptors[MB_PARAM_COIL].size >> 1); // number of registers in storage area + USHORT usRegCoilsStart = (USHORT)mbs_opts->mbs_area_descriptors[MB_PARAM_COIL].start_offset; // MB offset of coils registers + UCHAR* pucRegCoilsBuf = (UCHAR*)mbs_opts->mbs_area_descriptors[MB_PARAM_COIL].address; + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegIndex; + USHORT usCoils = usNCoils; + usAddress--; // The address is already +1 + if ((usAddress >= usRegCoilsStart) + && (usRegCoilNregs >= 1) + && ((usAddress + usCoils) <= (usRegCoilsStart + (usRegCoilNregs << 4) + 1)) + && (pucRegCoilsBuf != NULL) + && (usNCoils >= 1)) { + iRegIndex = (USHORT) (usAddress - usRegCoilsStart); + CHAR* pucCoilsDataBuf = (CHAR*)(pucRegCoilsBuf + (iRegIndex >> 3)); + switch (eMode) { + case MB_REG_READ: + while (usCoils > 0) { + UCHAR ucResult = xMBUtilGetBits((UCHAR*)pucRegCoilsBuf, iRegIndex, 1); + xMBUtilSetBits(pucRegBuffer, iRegIndex - (usAddress - usRegCoilsStart), 1, ucResult); + iRegIndex++; + usCoils--; + } + // Send an event to notify application task about event + (void)send_param_access_notification(MB_EVENT_COILS_RD); + (void)send_param_info(MB_EVENT_COILS_RD, (uint16_t)usAddress, + (uint8_t*)(pucCoilsDataBuf), (uint16_t)usNCoils); + break; + case MB_REG_WRITE: + while (usCoils > 0) { + UCHAR ucResult = xMBUtilGetBits(pucRegBuffer, + iRegIndex - (usAddress - usRegCoilsStart), 1); + xMBUtilSetBits((uint8_t*)pucRegCoilsBuf, iRegIndex, 1, ucResult); + iRegIndex++; + usCoils--; + } + // Send an event to notify application task about event + (void)send_param_access_notification(MB_EVENT_COILS_WR); + (void)send_param_info(MB_EVENT_COILS_WR, (uint16_t)usAddress, + (uint8_t*)pucCoilsDataBuf, (uint16_t)usNCoils); + break; + } // switch ( eMode ) + } else { + // If the configuration or input parameters are incorrect then return error to stack + eStatus = MB_ENOREG; + } + return eStatus; +} + +// Callback function for reading of MB Discrete Input Registers +eMBErrorCode eMBRegDiscreteCBTcpSlave(UCHAR* pucRegBuffer, USHORT usAddress, + USHORT usNDiscrete) +{ + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + MB_SLAVE_ASSERT(pucRegBuffer != NULL); + USHORT usRegDiscreteNregs = (USHORT)(mbs_opts->mbs_area_descriptors[MB_PARAM_DISCRETE].size >> 1); // number of registers in storage area + USHORT usRegDiscreteStart = (USHORT)mbs_opts->mbs_area_descriptors[MB_PARAM_DISCRETE].start_offset; // MB offset of registers + UCHAR* pucRegDiscreteBuf = (UCHAR*)mbs_opts->mbs_area_descriptors[MB_PARAM_DISCRETE].address; // the storage address + eMBErrorCode eStatus = MB_ENOERR; + USHORT iRegIndex, iRegBitIndex, iNReg; + UCHAR* pucDiscreteInputBuf; + iNReg = usNDiscrete / 8 + 1; + pucDiscreteInputBuf = (UCHAR*) pucRegDiscreteBuf; + // It already plus one in modbus function method. + usAddress--; + if ((usAddress >= usRegDiscreteStart) + && (usRegDiscreteNregs >= 1) + && (pucRegDiscreteBuf != NULL) + && ((usAddress + usNDiscrete) <= (usRegDiscreteStart + (usRegDiscreteNregs * 16))) + && (usNDiscrete >= 1)) { + iRegIndex = (USHORT) (usAddress - usRegDiscreteStart) / 8; // Get register index in the buffer for bit number + iRegBitIndex = (USHORT)(usAddress - usRegDiscreteStart) % 8; // Get bit index + UCHAR* pucTempBuf = &pucDiscreteInputBuf[iRegIndex]; + while (iNReg > 0) { + *pucRegBuffer++ = xMBUtilGetBits(&pucDiscreteInputBuf[iRegIndex++], iRegBitIndex, 8); + iNReg--; + } + pucRegBuffer--; + // Last discrete + usNDiscrete = usNDiscrete % 8; + // Filling zero to high bit + *pucRegBuffer = *pucRegBuffer << (8 - usNDiscrete); + *pucRegBuffer = *pucRegBuffer >> (8 - usNDiscrete); + // Send an event to notify application task about event + (void)send_param_access_notification(MB_EVENT_DISCRETE_RD); + (void)send_param_info(MB_EVENT_DISCRETE_RD, (uint16_t)usAddress, + (uint8_t*)pucTempBuf, (uint16_t)usNDiscrete); + } else { + eStatus = MB_ENOREG; + } + return eStatus; +} +#pragma GCC diagnostic pop // require GCC + +// Initialization of Modbus controller +esp_err_t mbc_tcp_slave_create(void** handler) +{ + // Allocate space for options + if (mbs_interface_ptr == NULL) { + mbs_interface_ptr = malloc(sizeof(mb_slave_interface_t)); + } + MB_SLAVE_ASSERT(mbs_interface_ptr != NULL); + mb_slave_options_t* mbs_opts = &mbs_interface_ptr->opts; + mbs_opts->port_type = MB_PORT_TCP_SLAVE; // set interface port type + + vMBPortSetMode((UCHAR)MB_PORT_TCP_SLAVE); + + // Set default values of communication options + mbs_opts->mbs_comm.ip_port = MB_TCP_DEFAULT_PORT; + + // Initialization of active context of the Modbus controller + BaseType_t status = 0; + + // Parameter change notification queue + mbs_opts->mbs_event_group = xEventGroupCreate(); + MB_SLAVE_CHECK((mbs_opts->mbs_event_group != NULL), + ESP_ERR_NO_MEM, "mb event group error."); + // Parameter change notification queue + mbs_opts->mbs_notification_queue_handle = xQueueCreate( + MB_CONTROLLER_NOTIFY_QUEUE_SIZE, + sizeof(mb_param_info_t)); + MB_SLAVE_CHECK((mbs_opts->mbs_notification_queue_handle != NULL), + ESP_ERR_NO_MEM, "mb notify queue creation error."); + // Create Modbus controller task + status = xTaskCreate((void*)&modbus_tcp_slave_task, + "modbus_tcp_slave_task", + MB_CONTROLLER_STACK_SIZE, + NULL, + MB_CONTROLLER_PRIORITY, + &mbs_opts->mbs_task_handle); + if (status != pdPASS) { + vTaskDelete(mbs_opts->mbs_task_handle); + MB_SLAVE_CHECK((status == pdPASS), ESP_ERR_NO_MEM, + "mb controller task creation error, xTaskCreate() returns (0x%x).", + (uint32_t)status); + } + + // The task is created but handle is incorrect + MB_SLAVE_ASSERT(mbs_opts->mbs_task_handle != NULL); + + // Initialization of interface pointers + mbs_interface_ptr->init = mbc_tcp_slave_create; + mbs_interface_ptr->destroy = mbc_tcp_slave_destroy; + mbs_interface_ptr->setup = mbc_tcp_slave_setup; + mbs_interface_ptr->start = mbc_tcp_slave_start; + mbs_interface_ptr->check_event = mbc_tcp_slave_check_event; + mbs_interface_ptr->get_param_info = mbc_tcp_slave_get_param_info; + mbs_interface_ptr->set_descriptor = mbc_tcp_slave_set_descriptor; + + // Initialize stack callback function pointers + mbs_interface_ptr->slave_reg_cb_discrete = eMBRegDiscreteCBTcpSlave; + mbs_interface_ptr->slave_reg_cb_input = eMBRegInputCBTcpSlave; + mbs_interface_ptr->slave_reg_cb_holding = eMBRegHoldingCBTcpSlave; + mbs_interface_ptr->slave_reg_cb_coils = eMBRegCoilsCBTcpSlave; + + *handler = (void*)mbs_interface_ptr; + + return ESP_OK; +} diff --git a/components/freemodbus/tcp_slave/modbus_controller/mbc_tcp_slave.h b/components/freemodbus/tcp_slave/modbus_controller/mbc_tcp_slave.h new file mode 100644 index 00000000..efa9194d --- /dev/null +++ b/components/freemodbus/tcp_slave/modbus_controller/mbc_tcp_slave.h @@ -0,0 +1,41 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + +// mbc_tcp_slave.h Modbus controller TCP slave implementation header file + +#ifndef _MODBUS_TCP_CONTROLLER_SLAVE +#define _MODBUS_TCP_CONTROLLER_SLAVE + +#include // for standard int types definition +#include // for NULL and std defines +#include "esp_modbus_common.h" // for common defines + +/* ----------------------- Defines ------------------------------------------*/ + +#define MB_CONTROLLER_NOTIFY_QUEUE_SIZE (CONFIG_FMB_CONTROLLER_NOTIFY_QUEUE_SIZE) // Number of messages in parameter notification queue +#define MB_CONTROLLER_NOTIFY_TIMEOUT (pdMS_TO_TICKS(CONFIG_FMB_CONTROLLER_NOTIFY_TIMEOUT)) // notification timeout + +/** + * @brief Initialize Modbus controller and stack for TCP slave + * + * @param[out] handler handler(pointer) to slave data structure + * @return + * - ESP_OK Success + * - ESP_ERR_NO_MEM Parameter error + */ +esp_err_t mbc_tcp_slave_create(void** handler); + +#endif // _MODBUS_TCP_CONTROLLER_SLAVE + diff --git a/components/freemodbus/tcp_slave/port/port_tcp_slave.c b/components/freemodbus/tcp_slave/port/port_tcp_slave.c new file mode 100644 index 00000000..5a9d2546 --- /dev/null +++ b/components/freemodbus/tcp_slave/port/port_tcp_slave.c @@ -0,0 +1,709 @@ +/* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ +/* + * FreeModbus Libary: ESP32 TCP Port + * Copyright (C) 2006 Christian Walter + * Parts of crt0.S Copyright (c) 1995, 1996, 1998 Cygnus Support + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * File: $Id: port.h,v 1.2 2006/09/04 14:39:20 wolti Exp $ + */ + +/* ----------------------- System includes ----------------------------------*/ +#include +#include +#include "esp_err.h" +#include "sys/time.h" +#include "esp_netif.h" + +/* ----------------------- lwIP includes ------------------------------------*/ +#include "lwip/err.h" +#include "lwip/sockets.h" +#include "lwip/netdb.h" +#include "net/if.h" + +/* ----------------------- Modbus includes ----------------------------------*/ +#include "mb.h" +#include "mbport.h" +#include "port.h" +#include "mbframe.h" +#include "port_tcp_slave.h" +#include "esp_modbus_common.h" // for common types for network options + +/* ----------------------- Defines -----------------------------------------*/ +#define MB_TCP_DISCONNECT_TIMEOUT ( CONFIG_FMB_TCP_CONNECTION_TOUT_SEC * 1000000 ) // disconnect timeout in uS +#define MB_TCP_RESP_TIMEOUT_MS ( MB_MASTER_TIMEOUT_MS_RESPOND - 2 ) // slave response time limit +#define MB_TCP_SLAVE_PORT_TAG "MB_TCP_SLAVE_PORT" +#define MB_TCP_NET_LISTEN_BACKLOG ( SOMAXCONN ) + +/* ----------------------- Prototypes ---------------------------------------*/ +void vMBPortEventClose( void ); + +/* ----------------------- Static variables ---------------------------------*/ +static int xListenSock = -1; +static MbSlavePortConfig_t xConfig = { 0 }; + +/* ----------------------- Static functions ---------------------------------*/ +// The helper function to get time stamp in microseconds +static int64_t xMBTCPGetTimeStamp(void) +{ + int64_t xTimeStamp = esp_timer_get_time(); + return xTimeStamp; +} + +static void vxMBTCPPortMStoTimeVal(USHORT usTimeoutMs, struct timeval *pxTimeout) +{ + pxTimeout->tv_sec = usTimeoutMs / 1000; + pxTimeout->tv_usec = (usTimeoutMs - (pxTimeout->tv_sec * 1000)) * 1000; +} + +static xQueueHandle xMBTCPPortRespQueueCreate(void) +{ + xQueueHandle xRespQueueHandle = xQueueCreate(2, sizeof(void*)); + MB_PORT_CHECK((xRespQueueHandle != NULL), NULL, "TCP respond queue creation failure."); + return xRespQueueHandle; +} + +static void vMBTCPPortRespQueueDelete(xQueueHandle xRespQueueHandle) +{ + vQueueDelete(xRespQueueHandle); +} + +static void* vxMBTCPPortRespQueueRecv(xQueueHandle xRespQueueHandle) +{ + void* pvResp = NULL; + MB_PORT_CHECK(xRespQueueHandle != NULL, NULL, "Response queue is not initialized."); + BaseType_t xStatus = xQueueReceive(xRespQueueHandle, + (void*)&pvResp, + pdMS_TO_TICKS(MB_TCP_RESP_TIMEOUT_MS)); + MB_PORT_CHECK((xStatus == pdTRUE), NULL, "Could not get respond confirmation."); + MB_PORT_CHECK((pvResp), NULL, "Incorrect response processing."); + return pvResp; +} + +static BOOL vxMBTCPPortRespQueueSend(xQueueHandle xRespQueueHandle, void* pvResp) +{ + MB_PORT_CHECK(xRespQueueHandle != NULL, FALSE, "Response queue is not initialized."); + BaseType_t xStatus = xQueueSend(xConfig.xRespQueueHandle, + (const void*)&pvResp, + pdMS_TO_TICKS(MB_TCP_RESP_TIMEOUT_MS)); + MB_PORT_CHECK((xStatus == pdTRUE), FALSE, "FAIL to send to response queue."); + return TRUE; +} + +static void vMBTCPPortServerTask(void *pvParameters); + +/* ----------------------- Begin implementation -----------------------------*/ +BOOL +xMBTCPPortInit( USHORT usTCPPort ) +{ + BOOL bOkay = FALSE; + + xConfig.pxMbClientInfo = calloc(MB_TCP_PORT_MAX_CONN + 1, sizeof(MbClientInfo_t*)); + if (!xConfig.pxMbClientInfo) { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "TCP client info allocation failure."); + return FALSE; + } + for(int idx = 0; idx < MB_TCP_PORT_MAX_CONN; xConfig.pxMbClientInfo[idx] = NULL, idx++); + + xConfig.xRespQueueHandle = xMBTCPPortRespQueueCreate(); + if (!xConfig.xRespQueueHandle) { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Response queue allocation failure."); + return FALSE; + } + + xConfig.usPort = usTCPPort; + xConfig.eMbProto = MB_PROTO_TCP; + xConfig.usClientCount = 0; + xConfig.pvNetIface = NULL; + xConfig.xIpVer = MB_PORT_IPV4; + xConfig.pcBindAddr = NULL; + + // Create task for packet processing + BaseType_t xErr = xTaskCreate(vMBTCPPortServerTask, + "tcp_server_task", + MB_TCP_STACK_SIZE, + NULL, + MB_TCP_TASK_PRIO, + &xConfig.xMbTcpTaskHandle); + vTaskSuspend(xConfig.xMbTcpTaskHandle); + if (xErr != pdTRUE) + { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Server task creation failure."); + vTaskDelete(xConfig.xMbTcpTaskHandle); + } else { + ESP_LOGI(MB_TCP_SLAVE_PORT_TAG, "Protocol stack initialized."); + bOkay = TRUE; + } + return bOkay; +} + +void vMBTCPPortSlaveSetNetOpt(void* pvNetIf, eMBPortIpVer xIpVersion, eMBPortProto xProto, CHAR* pcBindAddrStr) +{ + // Set network options + xConfig.pvNetIface = pvNetIf; + xConfig.eMbProto = xProto; + xConfig.xIpVer = xIpVersion; + xConfig.pcBindAddr = pcBindAddrStr; +} + +void vMBTCPPortSlaveStartServerTask(void) +{ + vTaskResume(xConfig.xMbTcpTaskHandle); +} + +static int xMBTCPPortAcceptConnection(int xListenSockId, char** pcIPAddr) +{ + MB_PORT_CHECK(pcIPAddr, -1, "Wrong IP address pointer."); + MB_PORT_CHECK((xListenSockId > 0), -1, "Incorrect listen socket ID."); + + // Address structure large enough for both IPv4 or IPv6 address + struct sockaddr_in6 xSrcAddr; + + CHAR cAddrStr[128]; + int xSockId = -1; + CHAR* pcStr = NULL; + socklen_t xSize = sizeof(struct sockaddr_in6); + + // Accept new socket connection if not active + xSockId = accept(xListenSockId, (struct sockaddr *)&xSrcAddr, &xSize); + if (xSockId < 0) { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Unable to accept connection: errno=%d", errno); + close(xSockId); + } else { + // Get the sender's ip address as string + if (xSrcAddr.sin6_family == PF_INET) { + inet_ntoa_r(((struct sockaddr_in *)&xSrcAddr)->sin_addr.s_addr, cAddrStr, sizeof(cAddrStr) - 1); + } else if (xSrcAddr.sin6_family == PF_INET6) { + inet6_ntoa_r(xSrcAddr.sin6_addr, cAddrStr, sizeof(cAddrStr) - 1); + } + ESP_LOGI(MB_TCP_SLAVE_PORT_TAG, "Socket (#%d), accept client connection from address: %s", xSockId, cAddrStr); + pcStr = calloc(1, strlen(cAddrStr) + 1); + if (pcStr && pcIPAddr) { + memcpy(pcStr, cAddrStr, strlen(cAddrStr)); + pcStr[strlen(cAddrStr)] = '\0'; + *pcIPAddr = pcStr; // Set IP address of connected client + } + } + return xSockId; +} + +static BOOL xMBTCPPortCloseConnection(MbClientInfo_t* pxInfo) +{ + MB_PORT_CHECK(pxInfo, FALSE, "Client info is NULL."); + + if (pxInfo->xSockId == -1) { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Wrong socket info or disconnected socket: %d.", pxInfo->xSockId); + return FALSE; + } + if (shutdown(pxInfo->xSockId, SHUT_RDWR) == -1) { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Socket (#%d), shutdown failed: errno %d", pxInfo->xSockId, errno); + } + close(pxInfo->xSockId); + pxInfo->xSockId = -1; + if (xConfig.usClientCount) { + xConfig.usClientCount--; // decrement counter of client connections + } else { + xConfig.pxCurClientInfo = NULL; + } + return TRUE; +} + +static int xMBTCPPortRxPoll(MbClientInfo_t* pxClientInfo, ULONG xTimeoutMs) +{ + int xRet = ERR_CLSD; + struct timeval xTimeVal; + fd_set xReadSet; + int64_t xStartTimeStamp = 0; + + // Receive data from connected client + if (pxClientInfo && pxClientInfo->xSockId > -1) { + // Set receive timeout + vxMBTCPPortMStoTimeVal(xTimeoutMs, &xTimeVal); + xStartTimeStamp = xMBTCPGetTimeStamp(); + while (1) + { + FD_ZERO(&xReadSet); + FD_SET(pxClientInfo->xSockId, &xReadSet); + xRet = select(pxClientInfo->xSockId + 1, &xReadSet, NULL, NULL, &xTimeVal); + if (xRet == -1) + { + // If select an error occurred + xRet = ERR_CLSD; + break; + } else if (xRet == 0) { + // timeout occurred + if ((xStartTimeStamp + xTimeoutMs * 1000) > xMBTCPGetTimeStamp()) { + ESP_LOGD(MB_TCP_SLAVE_PORT_TAG, "Socket (#%d) Read timeout.", pxClientInfo->xSockId); + xRet = ERR_TIMEOUT; + break; + } + } + if (FD_ISSET(pxClientInfo->xSockId, &xReadSet)) { + // If new buffer received then read Modbus packet into buffer + MB_PORT_CHECK((pxClientInfo->usTCPBufPos + pxClientInfo->usTCPFrameBytesLeft < MB_TCP_BUF_SIZE), + ERR_BUF, "Socket (#%d), incorrect request buffer size = %d, ignore.", + pxClientInfo->xSockId, + (pxClientInfo->usTCPBufPos + pxClientInfo->usTCPFrameBytesLeft)); + int xLength = recv(pxClientInfo->xSockId, &pxClientInfo->pucTCPBuf[pxClientInfo->usTCPBufPos], + pxClientInfo->usTCPFrameBytesLeft, MSG_DONTWAIT); + if (xLength < 0) { + // If an error occurred during receiving + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Receive failed: length=%d, errno=%d", xLength, errno); + xRet = (err_t)xLength; + break; + } else if (xLength == 0) { + // Socket connection closed + ESP_LOGD(MB_TCP_SLAVE_PORT_TAG, "Socket (#%d)(%s), connection closed.", + pxClientInfo->xSockId, pxClientInfo->pcIpAddr); + xRet = ERR_CLSD; + break; + } else { + // New data received + pxClientInfo->usTCPBufPos += xLength; + pxClientInfo->usTCPFrameBytesLeft -= xLength; + if (pxClientInfo->usTCPBufPos >= MB_TCP_FUNC) { + // Length is a byte count of Modbus PDU (function code + data) and the + // unit identifier. + xLength = (int)MB_TCP_GET_FIELD(pxClientInfo->pucTCPBuf, MB_TCP_LEN); + // Is the frame already complete. + if (pxClientInfo->usTCPBufPos < (MB_TCP_UID + xLength)) { + // The incomplete frame is received + pxClientInfo->usTCPFrameBytesLeft = xLength + MB_TCP_UID - pxClientInfo->usTCPBufPos; + } else if (pxClientInfo->usTCPBufPos == (MB_TCP_UID + xLength)) { +#if MB_TCP_DEBUG + prvvMBTCPLogFrame(MB_TCP_SLAVE_PORT_TAG, (UCHAR*)&pxClientInfo->pucTCPBuf[0], pxClientInfo->usTCPBufPos); +#endif + // Copy TID field from incoming packet + pxClientInfo->usTidCnt = MB_TCP_GET_FIELD(pxClientInfo->pucTCPBuf, MB_TCP_TID); + xRet = pxClientInfo->usTCPBufPos; + break; + } else if ((pxClientInfo->usTCPBufPos + xLength) >= MB_TCP_BUF_SIZE) { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Incorrect buffer received (%u) bytes.", xLength); + // This should not happen. We can't deal with such a client and + // drop the connection for security reasons. + xRet = ERR_BUF; + break; + } + } // if ( pxClientInfo->usTCPBufPos >= MB_TCP_FUNC ) + } // if data received + } // if (FD_ISSET(pxClientInfo->xSockId, &xReadSet)) + } // while (1) + } + return (xRet); +} + +// Create a listening socket on pcBindIp: Port +static int +vMBTCPPortBindAddr(const CHAR* pcBindIp) +{ + int xPar, xRet; + int xListenSockFd = -1; + struct addrinfo xHint; + struct addrinfo* pxAddrList; + struct addrinfo* pxCurAddr; + CHAR* pcStr = NULL; + + memset( &xHint, 0, sizeof( xHint ) ); + + // Bind to IPv6 and/or IPv4, but only in the desired protocol + // Todo: Find a reason why AF_UNSPEC does not work for IPv6 + xHint.ai_family = (xConfig.xIpVer == MB_PORT_IPV4) ? AF_INET : AF_INET6; + xHint.ai_socktype = (xConfig.eMbProto == MB_PROTO_UDP) ? SOCK_DGRAM : SOCK_STREAM; + // The LWIP has an issue when connection to IPv6 socket + xHint.ai_protocol = (xConfig.eMbProto == MB_PROTO_UDP) ? IPPROTO_UDP : IPPROTO_TCP; + xHint.ai_flags = AI_NUMERICSERV; + + if (pcBindIp == NULL) { + xHint.ai_flags |= AI_PASSIVE; + } else { + xHint.ai_flags |= AI_CANONNAME; + } + + if (asprintf(&pcStr, "%u", xConfig.usPort) == -1) { + abort(); + } + + xRet = getaddrinfo(pcBindIp, pcStr, &xHint, &pxAddrList); + free(pcStr); + + if (xRet != 0) { + return -1; + } + + // Try the sockaddr until a binding succeeds + for (pxCurAddr = pxAddrList; pxCurAddr != NULL; pxCurAddr = pxCurAddr->ai_next) + { + xListenSockFd = (int)socket(pxCurAddr->ai_family, pxCurAddr->ai_socktype, + pxCurAddr->ai_protocol); + if (xListenSockFd < 0) + { + continue; + } + + xPar = 1; + // Allow multi client connections + if (setsockopt(xListenSockFd, SOL_SOCKET, SO_REUSEADDR, + (const char*)&xPar, sizeof(xPar)) != 0) + { + close(xListenSockFd); + xListenSockFd = -1; + continue; + } + + if (bind(xListenSockFd, (struct sockaddr *)pxCurAddr->ai_addr, + (socklen_t)pxCurAddr->ai_addrlen) != 0 ) + { + close(xListenSockFd); + xListenSockFd = -1; + continue; + } + + // Listen only makes sense for TCP + if (xConfig.eMbProto == MB_PROTO_TCP) + { + if (listen(xListenSockFd, MB_TCP_NET_LISTEN_BACKLOG) != 0) + { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Error occurred during listen: errno=%d", errno); + close(xListenSockFd); + xListenSockFd = -1; + continue; + } + } + // Bind was successful + pcStr = (pxCurAddr->ai_canonname == NULL) ? (CHAR*)"\0" : pxCurAddr->ai_canonname; + ESP_LOGI(MB_TCP_SLAVE_PORT_TAG, "Socket (#%d), listener %s on port: %d, errno=%d", + xListenSockFd, pcStr, xConfig.usPort, errno); + break; + } + + freeaddrinfo(pxAddrList); + return(xListenSockFd); +} + +static void +vMBTCPPortFreeClientInfo(MbClientInfo_t* pxClientInfo) +{ + if (pxClientInfo) { + if (pxClientInfo->pucTCPBuf) { + free((void*)pxClientInfo->pucTCPBuf); + } + if (pxClientInfo->pcIpAddr) { + free((void*)pxClientInfo->pcIpAddr); + } + free((void*)pxClientInfo); + } +} + + +static void vMBTCPPortServerTask(void *pvParameters) +{ + int xErr = 0; + fd_set xReadSet; + int i; + CHAR* pcClientIp = NULL; + struct timeval xTimeVal; + + // Main connection cycle + while (1) { + // Create listen socket + xListenSock = vMBTCPPortBindAddr(xConfig.pcBindAddr); + if (xListenSock < 0) { + continue; + } + + // Connections handling cycle + while (1) { + //clear the socket set + FD_ZERO(&xReadSet); + //add master socket to set + FD_SET(xListenSock, &xReadSet); + int xMaxSd = xListenSock; + xConfig.usClientCount = 0; + + vxMBTCPPortMStoTimeVal(1, &xTimeVal); + // Initialize read set and file descriptor according to + // all registered connected clients + for (i = 0; i < MB_TCP_PORT_MAX_CONN; i++) { + if ((xConfig.pxMbClientInfo[i] != NULL) && (xConfig.pxMbClientInfo[i]->xSockId > 0)) { + // calculate max file descriptor for select + xMaxSd = (xConfig.pxMbClientInfo[i]->xSockId > xMaxSd) ? + xConfig.pxMbClientInfo[i]->xSockId : xMaxSd; + FD_SET(xConfig.pxMbClientInfo[i]->xSockId, &xReadSet); + xConfig.usClientCount++; + } + } + + // Wait for an activity on one of the sockets, timeout is NULL, so wait indefinitely + xErr = select(xMaxSd + 1 , &xReadSet , NULL , NULL , NULL); + if ((xErr < 0) && (errno != EINTR)) { + // error occurred during wait for read + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "select() errno = %d.", errno); + continue; + } else if (xErr == 0) { + // If timeout happened, something is wrong + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "select() timeout, errno = %d.", errno); + } + + // If something happened on the master socket, then its an incoming connection. + if (FD_ISSET(xListenSock, &xReadSet) && xConfig.usClientCount < MB_TCP_PORT_MAX_CONN) { + MbClientInfo_t* pxClientInfo = NULL; + // find first empty place to insert connection info + for (i = 0; i < MB_TCP_PORT_MAX_CONN; i++) { + pxClientInfo = xConfig.pxMbClientInfo[i]; + if (pxClientInfo == NULL) { + break; + } + } + // if request for new connection but no space left + if (pxClientInfo != NULL) { + if (xConfig.pxMbClientInfo[MB_TCP_PORT_MAX_CONN] == NULL) { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Fail to accept connection %d, only %d connections supported.", i + 1, MB_TCP_PORT_MAX_CONN); + } + xConfig.pxMbClientInfo[MB_TCP_PORT_MAX_CONN] = pxClientInfo; // set last connection info + } else { + // allocate memory for new client info + pxClientInfo = calloc(1, sizeof(MbClientInfo_t)); + if (!pxClientInfo) { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Client info allocation fail."); + vMBTCPPortFreeClientInfo(pxClientInfo); + pxClientInfo = NULL; + } else { + // Accept new client connection + pxClientInfo->xSockId = xMBTCPPortAcceptConnection(xListenSock, &pcClientIp); + if (pxClientInfo->xSockId < 0) { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Fail to accept connection for client %d.", (xConfig.usClientCount - 1)); + // Accept connection fail, then free client info and continue polling. + vMBTCPPortFreeClientInfo(pxClientInfo); + pxClientInfo = NULL; + continue; + } + pxClientInfo->pucTCPBuf = calloc(MB_TCP_BUF_SIZE, sizeof(UCHAR)); + if (!pxClientInfo->pucTCPBuf) { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Fail to allocate buffer for client %d.", (xConfig.usClientCount - 1)); + vMBTCPPortFreeClientInfo(pxClientInfo); + pxClientInfo = NULL; + continue; + } + // Fill the connection info structure + xConfig.pxMbClientInfo[i] = pxClientInfo; + pxClientInfo->xIndex = i; + xConfig.usClientCount++; + pxClientInfo->pcIpAddr = pcClientIp; + pxClientInfo->xRecvTimeStamp = xMBTCPGetTimeStamp(); + xConfig.pxMbClientInfo[MB_TCP_PORT_MAX_CONN] = NULL; + pxClientInfo->usTCPFrameBytesLeft = MB_TCP_FUNC; + pxClientInfo->usTCPBufPos = 0; + } + } + } + // Handle data request from client + if (xErr > 0) { + // Handling client connection requests + for (i = 0; i < MB_TCP_PORT_MAX_CONN; i++) { + MbClientInfo_t* pxClientInfo = xConfig.pxMbClientInfo[i]; + if ((pxClientInfo != NULL) && (pxClientInfo->xSockId > 0)) { + if (FD_ISSET(pxClientInfo->xSockId, &xReadSet)) { + // Other sockets are ready to be read + xErr = xMBTCPPortRxPoll(pxClientInfo, MB_TCP_READ_TIMEOUT_MS); + // If an invalid data received from socket or connection fail + // or if timeout then drop connection and restart + if (xErr < 0) { + uint64_t xTimeStamp = xMBTCPGetTimeStamp(); + // If data update is timed out + switch(xErr) + { + case ERR_TIMEOUT: + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Socket (#%d)(%s), data receive timeout, time[us]: %d, close active connection.", + pxClientInfo->xSockId, pxClientInfo->pcIpAddr, + (int)(xTimeStamp - pxClientInfo->xRecvTimeStamp)); + break; + case ERR_CLSD: + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Socket (#%d)(%s), connection closed by peer.", + pxClientInfo->xSockId, pxClientInfo->pcIpAddr); + break; + case ERR_BUF: + default: + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Socket (#%d)(%s), read data error: %d", + pxClientInfo->xSockId, pxClientInfo->pcIpAddr, xErr); + break; + } + // Close client connection + xMBTCPPortCloseConnection(pxClientInfo); + + // This client does not respond, then unregister it + vMBTCPPortFreeClientInfo(pxClientInfo); + xConfig.pxMbClientInfo[i] = NULL; + xConfig.pxMbClientInfo[MB_TCP_PORT_MAX_CONN] = NULL; + // If no any active connections, break + if (!xConfig.usClientCount) { + xConfig.pxCurClientInfo = NULL; + break; + } + } else { + pxClientInfo->xRecvTimeStamp = xMBTCPGetTimeStamp(); + + // set current client info to active client from which we received request + xConfig.pxCurClientInfo = pxClientInfo; + + // Complete frame received, inform state machine to process frame + xMBPortEventPost(EV_FRAME_RECEIVED); + + ESP_LOGD(MB_TCP_SLAVE_PORT_TAG, "Socket (#%d)(%s), get packet TID=0x%X, %d bytes.", + pxClientInfo->xSockId, pxClientInfo->pcIpAddr, + pxClientInfo->usTidCnt, xErr); + + // Wait while response is not processed by stack by timeout + UCHAR* pucSentBuffer = vxMBTCPPortRespQueueRecv(xConfig.xRespQueueHandle); + if (pucSentBuffer == NULL) { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Response time exceeds configured %d [ms], ignore packet.", + MB_TCP_RESP_TIMEOUT_MS); + } else { + USHORT usSentTid = MB_TCP_GET_FIELD(pucSentBuffer, MB_TCP_TID); + if (usSentTid != pxClientInfo->usTidCnt) { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Sent TID(%x) != Recv TID(%x), ignore packet.", + usSentTid, pxClientInfo->usTidCnt); + } + } + + // Get time stamp of last data update + pxClientInfo->xSendTimeStamp = xMBTCPGetTimeStamp(); + ESP_LOGD(MB_TCP_SLAVE_PORT_TAG, "Client %d, Socket(#%d), processing time = %d (us).", + pxClientInfo->xIndex, pxClientInfo->xSockId, + (int)(pxClientInfo->xSendTimeStamp - pxClientInfo->xRecvTimeStamp)); + } + } else { + if (pxClientInfo) { + // client is not ready to be read + int64_t xTime = xMBTCPGetTimeStamp() - pxClientInfo->xRecvTimeStamp; + if (xTime > MB_TCP_DISCONNECT_TIMEOUT) { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Client %d, Socket(#%d) do not answer for %d (us). Drop connection...", + pxClientInfo->xIndex, pxClientInfo->xSockId, (int)(xTime)); + xMBTCPPortCloseConnection(pxClientInfo); + + // This client does not respond, then delete registered data + vMBTCPPortFreeClientInfo(pxClientInfo); + xConfig.pxMbClientInfo[i] = NULL; + } + } else { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Client %d is disconnected.", i); + } + } + } // if ((pxClientInfo != NULL) + } // Handling client connection requests + } + } // while(1) // Handle connection cycle + } // Main connection cycle + vTaskDelete(NULL); +} + +void +vMBTCPPortClose( ) +{ + // Release resources for the event queue. + vMBPortEventClose( ); + vTaskDelete(xConfig.xMbTcpTaskHandle); +} + +void +vMBTCPPortDisable( void ) +{ + vTaskSuspend(xConfig.xMbTcpTaskHandle); + for (int i = 0; i < MB_TCP_PORT_MAX_CONN; i++) { + MbClientInfo_t* pxClientInfo = xConfig.pxMbClientInfo[i]; + if ((pxClientInfo != NULL) && (pxClientInfo->xSockId > 0)) { + xMBTCPPortCloseConnection(pxClientInfo); + vMBTCPPortFreeClientInfo(pxClientInfo); + xConfig.pxMbClientInfo[i] = NULL; + } + } + close(xListenSock); + xListenSock = -1; + vMBTCPPortRespQueueDelete(xConfig.xRespQueueHandle); +} + +BOOL +xMBTCPPortGetRequest( UCHAR ** ppucMBTCPFrame, USHORT * usTCPLength ) +{ + BOOL xRet = FALSE; + if (xConfig.pxCurClientInfo) { + *ppucMBTCPFrame = &xConfig.pxCurClientInfo->pucTCPBuf[0]; + *usTCPLength = xConfig.pxCurClientInfo->usTCPBufPos; + + // Reset the buffer. + xConfig.pxCurClientInfo->usTCPBufPos = 0; + xConfig.pxCurClientInfo->usTCPFrameBytesLeft = MB_TCP_FUNC; + xRet = TRUE; + } + return xRet; +} + +BOOL +xMBTCPPortSendResponse( UCHAR * pucMBTCPFrame, USHORT usTCPLength ) +{ + BOOL bFrameSent = FALSE; + fd_set xWriteSet; + fd_set xErrorSet; + int xErr = -1; + struct timeval xTimeVal; + + if (xConfig.pxCurClientInfo) { + FD_ZERO(&xWriteSet); + FD_ZERO(&xErrorSet); + FD_SET(xConfig.pxCurClientInfo->xSockId, &xWriteSet); + FD_SET(xConfig.pxCurClientInfo->xSockId, &xErrorSet); + vxMBTCPPortMStoTimeVal(MB_TCP_SEND_TIMEOUT_MS, &xTimeVal); + // Check if socket writable + xErr = select(xConfig.pxCurClientInfo->xSockId + 1, NULL, &xWriteSet, &xErrorSet, &xTimeVal); + if ((xErr == -1) || FD_ISSET(xConfig.pxCurClientInfo->xSockId, &xErrorSet)) { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Socket(#%d) , send select() error = %d.", + xConfig.pxCurClientInfo->xSockId, errno); + return FALSE; + } + + // Apply TID field from request to the frame before send response + pucMBTCPFrame[MB_TCP_TID] = (UCHAR)(xConfig.pxCurClientInfo->usTidCnt >> 8U); + pucMBTCPFrame[MB_TCP_TID + 1] = (UCHAR)(xConfig.pxCurClientInfo->usTidCnt & 0xFF); + + // Write message into socket and disable Nagle's algorithm + xErr = send(xConfig.pxCurClientInfo->xSockId, pucMBTCPFrame, usTCPLength, TCP_NODELAY); + if (xErr < 0) { + ESP_LOGE(MB_TCP_SLAVE_PORT_TAG, "Socket(#%d), fail to send data, errno = %d", + xConfig.pxCurClientInfo->xSockId, errno); + xConfig.pxCurClientInfo->xError = xErr; + } else { + bFrameSent = TRUE; + vxMBTCPPortRespQueueSend(xConfig.xRespQueueHandle, (void*)pucMBTCPFrame); + } + } else { + ESP_LOGD(MB_TCP_SLAVE_PORT_TAG, "Port is not active. Release lock."); + vxMBTCPPortRespQueueSend(xConfig.xRespQueueHandle, (void*)pucMBTCPFrame); + } + return bFrameSent; +} + diff --git a/components/freemodbus/tcp_slave/port/port_tcp_slave.h b/components/freemodbus/tcp_slave/port/port_tcp_slave.h new file mode 100644 index 00000000..ffed7959 --- /dev/null +++ b/components/freemodbus/tcp_slave/port/port_tcp_slave.h @@ -0,0 +1,113 @@ + /* Copyright 2018 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. +*/ + /* + * FreeModbus Libary: ESP32 TCP Port + * Copyright (C) 2006 Christian Walter + * Parts of crt0.S Copyright (c) 1995, 1996, 1998 Cygnus Support + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * File: $Id: port.h,v 1.2 2006/09/04 14:39:20 wolti Exp $ + */ + +#ifndef _PORT_TCP_SLAVE_H +#define _PORT_TCP_SLAVE_H + +/* ----------------------- Platform includes --------------------------------*/ +#include "esp_log.h" + +#include "lwip/opt.h" +#include "lwip/sys.h" +#include "port.h" +#include "esp_modbus_common.h" // for common types for network options + +/* ----------------------- Defines ------------------------------------------*/ + +#ifndef TRUE +#define TRUE 1 +#endif + +#ifndef FALSE +#define FALSE 0 +#endif + +#ifdef __cplusplus +PR_BEGIN_EXTERN_C +#endif + +/* ----------------------- Type definitions ---------------------------------*/ +typedef struct { + int xIndex; /*!< Modbus info index */ + int xSockId; /*!< Socket id */ + int xError; /*!< TCP/UDP sock error */ + const char* pcIpAddr; /*!< TCP/UDP IP address (string) */ + UCHAR* pucTCPBuf; /*!< buffer pointer */ + USHORT usTCPBufPos; /*!< buffer active position */ + USHORT usTCPFrameBytesLeft; /*!< buffer left bytes to receive transaction */ + int64_t xSendTimeStamp; /*!< send request timestamp */ + int64_t xRecvTimeStamp; /*!< receive response timestamp */ + USHORT usTidCnt; /*!< last TID counter from packet */ +} MbClientInfo_t; + +typedef struct { + TaskHandle_t xMbTcpTaskHandle; /*!< Server task handle */ + xQueueHandle xRespQueueHandle; /*!< Response queue handle */ + MbClientInfo_t* pxCurClientInfo; /*!< Current client info */ + MbClientInfo_t** pxMbClientInfo; /*!< Pointers to information about connected clients */ + USHORT usPort; /*!< TCP/UDP port number */ + CHAR* pcBindAddr; /*!< IP address to bind */ + eMBPortProto eMbProto; /*!< Protocol type used by port */ + USHORT usClientCount; /*!< Client connection count */ + void* pvNetIface; /*!< Network netif interface pointer for port */ + eMBPortIpVer xIpVer; /*!< IP protocol version */ +} MbSlavePortConfig_t; + +/* ----------------------- Function prototypes ------------------------------*/ + +/** + * Function to setup communication options for TCP/UDP Modbus port + * + * @param pvNetIf netif interface pointer + * @param xIpVersion IP version + * @param xProto protocol type option + * @param pcBindAddr IP bind address + * + * @return error code + */ +void vMBTCPPortSlaveSetNetOpt(void* pvNetIf, eMBPortIpVer xIpVersion, eMBPortProto xProto, CHAR* pcBindAddr); + +/** + * Resume TCP Slave processing task + * + * @return None + */ +void vMBTCPPortSlaveStartServerTask(void); + +#ifdef __cplusplus +PR_END_EXTERN_C +#endif +#endif diff --git a/examples/protocols/modbus/mb_example_common/CMakeLists.txt b/examples/protocols/modbus/mb_example_common/CMakeLists.txt new file mode 100644 index 00000000..5dceb368 --- /dev/null +++ b/examples/protocols/modbus/mb_example_common/CMakeLists.txt @@ -0,0 +1,6 @@ +# 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.5) +idf_component_register(SRCS "modbus_params.c" + INCLUDE_DIRS "include" + PRIV_REQUIRES freemodbus) \ No newline at end of file diff --git a/examples/protocols/modbus/mb_example_common/README.md b/examples/protocols/modbus/mb_example_common/README.md new file mode 100644 index 00000000..4a08b7e8 --- /dev/null +++ b/examples/protocols/modbus/mb_example_common/README.md @@ -0,0 +1,10 @@ +# 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) \ No newline at end of file diff --git a/examples/protocols/modbus/mb_example_common/component.mk b/examples/protocols/modbus/mb_example_common/component.mk new file mode 100644 index 00000000..9b8ec902 --- /dev/null +++ b/examples/protocols/modbus/mb_example_common/component.mk @@ -0,0 +1,5 @@ +# +# Component Makefile +# +COMPONENT_ADD_INCLUDEDIRS := include +COMPONENT_SRCDIRS := . \ No newline at end of file diff --git a/examples/protocols/modbus/mb_example_common/include/modbus_params.h b/examples/protocols/modbus/mb_example_common/include/modbus_params.h new file mode 100644 index 00000000..f75996f3 --- /dev/null +++ b/examples/protocols/modbus/mb_example_common/include/modbus_params.h @@ -0,0 +1,62 @@ +/*===================================================================================== + * 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 + +// 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:8; +} discrete_reg_params_t; +#pragma pack(pop) + +#pragma pack(push, 1) +typedef struct +{ + uint8_t coils_port0; + uint8_t coils_port1; +} coil_reg_params_t; +#pragma pack(pop) + +#pragma pack(push, 1) +typedef struct +{ + float input_data0; + float input_data1; + float input_data2; + float input_data3; + uint16_t data[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]; +} 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) diff --git a/examples/protocols/modbus/mb_example_common/modbus_params.c b/examples/protocols/modbus/mb_example_common/modbus_params.c new file mode 100644 index 00000000..5a0bcadb --- /dev/null +++ b/examples/protocols/modbus/mb_example_common/modbus_params.c @@ -0,0 +1,17 @@ +/*===================================================================================== + * Description: + * C file to define parameter storage instances + *====================================================================================*/ +#include +#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 }; + diff --git a/examples/protocols/modbus/serial/README.md b/examples/protocols/modbus/serial/README.md new file mode 100644 index 00000000..2e5d0b7f --- /dev/null +++ b/examples/protocols/modbus/serial/README.md @@ -0,0 +1,82 @@ +# 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. + + diff --git a/examples/protocols/modbus/serial/example_test.py b/examples/protocols/modbus/serial/example_test.py new file mode 100644 index 00000000..56f5f0c4 --- /dev/null +++ b/examples/protocols/modbus/serial/example_test.py @@ -0,0 +1,288 @@ +# Need Python 3 string formatting functions +from __future__ import print_function + +import os +import re +import logging +from threading import Thread + +import ttfw_idf + +LOG_LEVEL = logging.DEBUG +LOGGER_NAME = "modbus_test" + +# Allowed parameter reads +TEST_READ_MIN_COUNT = 10 # Minimum number of correct readings +TEST_READ_MAX_ERR_COUNT = 2 # Maximum allowed read errors during initialization + +TEST_THREAD_EXPECT_TIMEOUT = 120 # Test theread expect timeout in seconds +TEST_THREAD_JOIN_TIMEOUT = 180 # Test theread join timeout in seconds + +# Test definitions +TEST_MASTER_RTU = 'master_rtu' +TEST_SLAVE_RTU = 'slave_rtu' + +TEST_MASTER_ASCII = 'master_ascii' +TEST_SLAVE_ASCII = 'slave_ascii' + +# Define tuple of strings to expect for each DUT. +# +master_expect = ("MASTER_TEST: Modbus master stack initialized...", "MASTER_TEST: Start modbus test...", "MASTER_TEST: Destroy master...") +slave_expect = ("SLAVE_TEST: Modbus slave stack initialized.", "SLAVE_TEST: Start modbus test...", "SLAVE_TEST: Modbus controller destroyed.") + +# The dictionary for expected values in listing +expect_dict_master_ok = {"START": (), + "READ_PAR_OK": (), + "ALARM_MSG": (u'7',)} + +expect_dict_master_err = {"READ_PAR_ERR": (u'263', u'ESP_ERR_TIMEOUT'), + "READ_STK_ERR": (u'107', u'ESP_ERR_TIMEOUT')} + +# The dictionary for regular expression patterns to check in listing +pattern_dict_master_ok = {"START": (r'.*I \([0-9]+\) MASTER_TEST: Start modbus test...'), + "READ_PAR_OK": (r'.*I\s\([0-9]+\) MASTER_TEST: Characteristic #[0-9]+ [a-zA-Z0-9_]+' + r'\s\([a-zA-Z\%\/]+\) value = [a-zA-Z0-9\.\s]*\(0x[a-zA-Z0-9]+\) read successful.'), + "ALARM_MSG": (r'.*I \([0-9]*\) MASTER_TEST: Alarm triggered by cid #([0-9]+).')} + +pattern_dict_master_err = {"READ_PAR_ERR_TOUT": (r'.*E \([0-9]+\) MASTER_TEST: Characteristic #[0-9]+' + r'\s\([a-zA-Z0-9_]+\) read fail, err = [0-9]+ \([_A-Z]+\).'), + "READ_STK_ERR_TOUT": (r'.*E \([0-9]+\) MB_CONTROLLER_MASTER: [a-zA-Z0-9_]+\([0-9]+\):\s' + r'SERIAL master get parameter failure error=\(0x([a-zA-Z0-9]+)\) \(([_A-Z]+)\).')} + +# The dictionary for expected values in listing +expect_dict_slave_ok = {"START": (), + "READ_PAR_OK": (), + "DESTROY": ()} + +# The dictionary for regular expression patterns to check in listing +pattern_dict_slave_ok = {"START": (r'.*I \([0-9]+\) SLAVE_TEST: Start modbus test...'), + "READ_PAR_OK": (r'.*I\s\([0-9]+\) SLAVE_TEST: [A-Z]+ READ \([a-zA-Z0-9_]+ us\),\s' + r'ADDR:[0-9]+, TYPE:[0-9]+, INST_ADDR:0x[a-zA-Z0-9]+, SIZE:[0-9]+'), + "DESTROY": (r'.*I\s\([0-9]+\) SLAVE_TEST: Modbus controller destroyed.')} + +logger = logging.getLogger(LOGGER_NAME) + + +class DutTestThread(Thread): + def __init__(self, dut=None, name=None, expect=None): + """ Initialize the thread parameters + """ + self.tname = name + self.dut = dut + self.expected = expect + self.result = False + self.data = None + super(DutTestThread, self).__init__() + + def run(self): + """ The function implements thread functionality + """ + # Must reset again as flashing during start_app will reset multiple times, causing unexpected results + self.dut.reset() + + # Capture output from the DUT + self.dut.start_capture_raw_data() + + # Check expected strings in the listing + for string in self.expected: + self.dut.expect(string, TEST_THREAD_EXPECT_TIMEOUT) + + # Check DUT exceptions + dut_exceptions = self.dut.get_exceptions() + if "Guru Meditation Error:" in dut_exceptions: + raise Exception("%s generated an exception: %s\n" % (str(self.dut), dut_exceptions)) + + # Mark thread has run to completion without any exceptions + self.data = self.dut.stop_capture_raw_data() + self.result = True + + +def test_filter_output(data=None, start_pattern=None, end_pattern=None): + """Use patters to filter output + """ + start_index = str(data).find(start_pattern) + end_index = str(data).find(end_pattern) + logger.debug("Listing start index= %d, end=%d" % (start_index, end_index)) + if start_index == -1 or end_index == -1: + return data + return data[start_index:end_index + len(end_pattern)] + + +def test_expect_re(data, pattern): + """ + Check if re pattern is matched in data cache + :param data: data to process + :param pattern: compiled RegEx pattern + :return: match groups if match succeed otherwise None + """ + ret = None + if isinstance(pattern, type(u'')): + pattern = pattern.encode('utf-8') + regex = re.compile(pattern) + if isinstance(data, type(u'')): + data = data.encode('utf-8') + match = regex.search(data) + if match: + ret = tuple(None if x is None else x.decode() for x in match.groups()) + index = match.end() + else: + index = None + return ret, index + + +def test_check_output(data=None, check_dict=None, expect_dict=None): + """ Check output for the test + Check log using regular expressions: + """ + global logger + match_count = 0 + index = 0 + data_lines = data.splitlines() + for key, pattern in check_dict.items(): + if key not in expect_dict: + break + # Check pattern in the each line + for line in data_lines: + group, index = test_expect_re(line, pattern) + if index is not None: + logger.debug("Found key{%s}=%s, line: \n%s" % (key, group, line)) + if expect_dict[key] == group: + logger.debug("The result is correct for the key:%s, expected:%s == returned:%s" % (key, str(expect_dict[key]), str(group))) + match_count += 1 + return match_count + + +def test_check_mode(dut=None, mode_str=None, value=None): + """ Check communication mode for dut + """ + global logger + try: + opt = dut.app.get_sdkconfig()[mode_str] + logger.info("%s {%s} = %s.\n" % (str(dut), mode_str, opt)) + return value == opt + except Exception: + logger.info('ENV_TEST_FAILURE: %s: Cannot find option %s in sdkconfig.' % (str(dut), mode_str)) + return False + + +@ttfw_idf.idf_example_test(env_tag='UT_T2_RS485', ignore=True) +def test_modbus_communication(env, comm_mode): + global logger + + # Get device under test. "dut1 - master", "dut2 - slave" must be properly connected through RS485 interface driver + dut_master = env.get_dut("modbus_master", "examples/protocols/modbus/serial/mb_master", dut_class=ttfw_idf.ESP32DUT) + dut_slave = env.get_dut("modbus_slave", "examples/protocols/modbus/serial/mb_slave", dut_class=ttfw_idf.ESP32DUT) + + try: + logger.debug("Environment vars: %s\r\n" % os.environ) + logger.debug("DUT slave sdkconfig: %s\r\n" % dut_slave.app.get_sdkconfig()) + logger.debug("DUT master sdkconfig: %s\r\n" % dut_master.app.get_sdkconfig()) + + # Check Kconfig configuration options for each built example + if test_check_mode(dut_master, "CONFIG_MB_COMM_MODE_ASCII", "y") and test_check_mode(dut_slave, "CONFIG_MB_COMM_MODE_ASCII", "y"): + logger.info("ENV_TEST_INFO: Modbus ASCII test mode selected in the configuration. \n") + slave_name = TEST_SLAVE_ASCII + master_name = TEST_MASTER_ASCII + elif test_check_mode(dut_master, "CONFIG_MB_COMM_MODE_RTU", "y") and test_check_mode(dut_slave, "CONFIG_MB_COMM_MODE_RTU", "y"): + logger.info("ENV_TEST_INFO: Modbus RTU test mode selected in the configuration. \n") + slave_name = TEST_SLAVE_RTU + master_name = TEST_MASTER_RTU + else: + logger.error("ENV_TEST_FAILURE: Communication mode in master and slave configuration don't match.\n") + raise Exception("ENV_TEST_FAILURE: Communication mode in master and slave configuration don't match.\n") + # Check if slave address for example application is default one to be able to communicate + if not test_check_mode(dut_slave, "CONFIG_MB_SLAVE_ADDR", "1"): + logger.error("ENV_TEST_FAILURE: Slave address option is incorrect.\n") + raise Exception("ENV_TEST_FAILURE: Slave address option is incorrect.\n") + + # Flash app onto each DUT + dut_master.start_app() + dut_slave.start_app() + + # Create thread for each dut + dut_master_thread = DutTestThread(dut=dut_master, name=master_name, expect=master_expect) + dut_slave_thread = DutTestThread(dut=dut_slave, name=slave_name, expect=slave_expect) + + # Start each thread + dut_slave_thread.start() + dut_master_thread.start() + + # Wait for threads to complete + dut_slave_thread.join(timeout=TEST_THREAD_JOIN_TIMEOUT) + dut_master_thread.join(timeout=TEST_THREAD_JOIN_TIMEOUT) + + if dut_slave_thread.isAlive(): + logger.error("ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" % + (dut_slave_thread.tname, TEST_THREAD_JOIN_TIMEOUT)) + raise Exception("ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" % + (dut_slave_thread.tname, TEST_THREAD_JOIN_TIMEOUT)) + + if dut_master_thread.isAlive(): + logger.error("ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" % + (dut_master_thread.tname, TEST_THREAD_JOIN_TIMEOUT)) + raise Exception("ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" % + (dut_master_thread.tname, TEST_THREAD_JOIN_TIMEOUT)) + finally: + dut_master.close() + dut_slave.close() + + # Check if test threads completed successfully and captured data + if not dut_slave_thread.result or dut_slave_thread.data is None: + logger.error("The thread %s was not run successfully." % dut_slave_thread.tname) + raise Exception("The thread %s was not run successfully." % dut_slave_thread.tname) + + if not dut_master_thread.result or dut_master_thread.data is None: + logger.error("The thread %s was not run successfully." % dut_slave_thread.tname) + raise Exception("The thread %s was not run successfully." % dut_master_thread.tname) + + # Filter output to get test messages + master_output = test_filter_output(dut_master_thread.data, master_expect[0], master_expect[len(master_expect) - 1]) + if master_output is not None: + logger.info("The data for master thread is captured.") + logger.debug(master_output) + + slave_output = test_filter_output(dut_slave_thread.data, slave_expect[0], slave_expect[len(slave_expect) - 1]) + if slave_output is not None: + logger.info("The data for slave thread is captured.") + logger.debug(slave_output) + + # Check if parameters are read correctly by master + match_count = test_check_output(master_output, pattern_dict_master_ok, expect_dict_master_ok) + if match_count < TEST_READ_MIN_COUNT: + logger.error("There are errors reading parameters from %s, %d" % (dut_master_thread.tname, match_count)) + raise Exception("There are errors reading parameters from %s, %d" % (dut_master_thread.tname, match_count)) + logger.info("OK pattern test for %s, match_count=%d." % (dut_master_thread.tname, match_count)) + + # If the test completed successfully (alarm triggered) but there are some errors during reading of parameters + match_count = test_check_output(master_output, pattern_dict_master_err, expect_dict_master_err) + if match_count > TEST_READ_MAX_ERR_COUNT: + logger.error("There are errors reading parameters from %s, %d" % (dut_master_thread.tname, match_count)) + raise Exception("There are errors reading parameters from %s, %d" % (dut_master_thread.tname, match_count)) + logger.info("ERROR pattern test for %s, match_count=%d." % (dut_master_thread.tname, match_count)) + + match_count = test_check_output(slave_output, pattern_dict_slave_ok, expect_dict_slave_ok) + if match_count < TEST_READ_MIN_COUNT: + logger.error("There are errors reading parameters from %s, %d" % (dut_slave_thread.tname, match_count)) + raise Exception("There are errors reading parameters from %s, %d" % (dut_slave_thread.tname, match_count)) + logger.info("OK pattern test for %s, match_count=%d." % (dut_slave_thread.tname, match_count)) + + +if __name__ == '__main__': + logger = logging.getLogger(LOGGER_NAME) + # create file handler which logs even debug messages + fh = logging.FileHandler('modbus_test.log') + fh.setLevel(logging.DEBUG) + logger.setLevel(logging.DEBUG) + # create console handler + ch = logging.StreamHandler() + ch.setLevel(logging.INFO) + # set format of output for both handlers + formatter = logging.Formatter('%(levelname)s:%(message)s') + ch.setFormatter(formatter) + fh.setFormatter(formatter) + logger.addHandler(fh) + logger.addHandler(ch) + logger.info("Start script %s." % os.path.basename(__file__)) + print("Logging file name: %s" % logger.handlers[0].baseFilename) + test_modbus_communication() + logging.shutdown() diff --git a/examples/protocols/modbus/serial/mb_master/CMakeLists.txt b/examples/protocols/modbus/serial/mb_master/CMakeLists.txt new file mode 100644 index 00000000..51733e07 --- /dev/null +++ b/examples/protocols/modbus/serial/mb_master/CMakeLists.txt @@ -0,0 +1,8 @@ +# 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.5) + +set(EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/protocols/modbus/mb_example_common) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(modbus_master) diff --git a/examples/protocols/modbus/serial/mb_master/Makefile b/examples/protocols/modbus/serial/mb_master/Makefile new file mode 100644 index 00000000..8119959f --- /dev/null +++ b/examples/protocols/modbus/serial/mb_master/Makefile @@ -0,0 +1,11 @@ +# +# This is a project Makefile. It is assumed the directory this Makefile resides in is a +# project subdirectory. +# + +PROJECT_NAME := modbus_master + +EXTRA_COMPONENT_DIRS := $(IDF_PATH)/examples/protocols/modbus/mb_example_common + +include $(IDF_PATH)/make/project.mk + diff --git a/examples/protocols/modbus/serial/mb_master/README.md b/examples/protocols/modbus/serial/mb_master/README.md new file mode 100644 index 00000000..543d152b --- /dev/null +++ b/examples/protocols/modbus/serial/mb_master/README.md @@ -0,0 +1,155 @@ +| Supported Targets | ESP32 | +| ----------------- | ----- | + +# 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 WROVER-KIT board. + +Option 2: +Several ESP32 WROVER-KIT board 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 WROVER-KIT 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 WROVER KIT 1 | | RS-485 side | | External PC (emulator) with USB to serial or + RTS --+--->| DE | / \ | DE|---+ ESP32 WROVER KIT 2 (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). +``` + -------------------------------------------------------------------------------------------------------------------------- + | ESP32 Interface | #define | Default ESP32 Pin | Default ESP32-S2 Pins | External RS485 Driver Pin | + | ----------------------|--------------------|-----------------------|-----------------------|---------------------------| + | Transmit Data (TxD) | CONFIG_MB_UART_TXD | GPIO23 | GPIO20 | DI | + | Receive Data (RxD) | CONFIG_MB_UART_RXD | GPIO22 | GPIO19 | RO | + | Request To Send (RTS) | CONFIG_MB_UART_RTS | GPIO18 | GPIO18 | ~RE/DE | + | Ground | n/a | GND | GND | GND | + -------------------------------------------------------------------------------------------------------------------------- +``` +Note: The GPIO22 - GPIO25 can not be used with ESP32-S2 chip because they are used for flash chip connection. Please refer to UART documentation for selected target. + +Connect USB to RS485 adapter to computer and connect its D+, D- output lines with the D+, D- lines of RS485 line driver connected to ESP32 (See picture 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 WROVER KIT 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). + diff --git a/examples/protocols/modbus/serial/mb_master/main/CMakeLists.txt b/examples/protocols/modbus/serial/mb_master/main/CMakeLists.txt new file mode 100644 index 00000000..9a6cf30e --- /dev/null +++ b/examples/protocols/modbus/serial/mb_master/main/CMakeLists.txt @@ -0,0 +1,5 @@ +set(PROJECT_NAME "modbus_master") + +idf_component_register(SRCS "master.c" + INCLUDE_DIRS ".") + diff --git a/examples/protocols/modbus/serial/mb_master/main/Kconfig.projbuild b/examples/protocols/modbus/serial/mb_master/main/Kconfig.projbuild new file mode 100644 index 00000000..b5b2f7a7 --- /dev/null +++ b/examples/protocols/modbus/serial/mb_master/main/Kconfig.projbuild @@ -0,0 +1,66 @@ +menu "Modbus Example Configuration" + + config MB_UART_PORT_NUM + int "UART port number" + range 0 2 if IDF_TARGET_ESP32 + default 2 if IDF_TARGET_ESP32 + range 0 1 if IDF_TARGET_ESP32S2 + default 1 if IDF_TARGET_ESP32S2 + 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 0 34 if IDF_TARGET_ESP32 + default 22 if IDF_TARGET_ESP32 + range 0 46 if IDF_TARGET_ESP32S2 + default 19 if IDF_TARGET_ESP32S2 + 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 0 34 if IDF_TARGET_ESP32 + default 23 if IDF_TARGET_ESP32 + range 0 46 if IDF_TARGET_ESP32S2 + default 20 if IDF_TARGET_ESP32S2 + 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 0 34 if IDF_TARGET_ESP32 + range 0 46 if IDF_TARGET_ESP32S2 + default 18 + 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 diff --git a/examples/protocols/modbus/serial/mb_master/main/component.mk b/examples/protocols/modbus/serial/mb_master/main/component.mk new file mode 100644 index 00000000..a98f634e --- /dev/null +++ b/examples/protocols/modbus/serial/mb_master/main/component.mk @@ -0,0 +1,4 @@ +# +# "main" pseudo-component makefile. +# +# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.) diff --git a/examples/protocols/modbus/serial/mb_master/main/master.c b/examples/protocols/modbus/serial/mb_master/main/master.c new file mode 100644 index 00000000..227785db --- /dev/null +++ b/examples/protocols/modbus/serial/mb_master/main/master.c @@ -0,0 +1,320 @@ +// Copyright 2016-2019 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#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_RATE_MS) + +// Timeout between polls +#define POLL_TIMEOUT_MS (1) +#define POLL_TIMEOUT_TICS (POLL_TIMEOUT_MS / portTICK_RATE_MS) + +#define MASTER_TAG "MASTER_TEST" + +#define MASTER_CHECK(a, ret_val, str, ...) \ + if (!(a)) { \ + ESP_LOGE(MASTER_TAG, "%s(%u): " str, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ + return (ret_val); \ + } + +// 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 } + +// 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_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, 0, 8, + COIL_OFFSET(coils_port0), PARAM_TYPE_U16, 2, OPTS( BIT1, 0, 0 ), PAR_PERMS_READ_WRITE_TRIGGER }, + { CID_RELAY_P2, STR("RelayP2"), STR("on/off"), MB_DEVICE_ADDR1, MB_PARAM_COIL, 8, 8, + COIL_OFFSET(coils_port1), PARAM_TYPE_U16, 2, OPTS( BIT0, 0, 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(MASTER_TAG, "Wrong parameter offset for CID #%d", 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(MASTER_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(MASTER_TAG, "Characteristic #%d %s (%s) value = (0x%08x) read successful.", + param_descriptor->cid, + (char*)param_descriptor->param_key, + (char*)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(MASTER_TAG, "Characteristic #%d %s (%s) value = (0x%08x), write successful.", + param_descriptor->cid, + (char*)param_descriptor->param_key, + (char*)param_descriptor->param_units, + *(uint32_t*)temp_data_ptr); + } else { + ESP_LOGE(MASTER_TAG, "Characteristic #%d (%s) write fail, err = 0x%x (%s).", + param_descriptor->cid, + (char*)param_descriptor->param_key, + (int)err, + (char*)esp_err_to_name(err)); + } + } + } else { + ESP_LOGE(MASTER_TAG, "Characteristic #%d (%s) read fail, err = 0x%x (%s).", + param_descriptor->cid, + (char*)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*)&value, &type); + if (err == ESP_OK) { + *(float*)temp_data_ptr = value; + if ((param_descriptor->mb_param_type == MB_PARAM_HOLDING) || + (param_descriptor->mb_param_type == MB_PARAM_INPUT)) { + ESP_LOGI(MASTER_TAG, "Characteristic #%d %s (%s) value = %f (0x%x) read successful.", + param_descriptor->cid, + (char*)param_descriptor->param_key, + (char*)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 { + uint16_t state = *(uint16_t*)temp_data_ptr; + const char* rw_str = (state & param_descriptor->param_opts.opt1) ? "ON" : "OFF"; + ESP_LOGI(MASTER_TAG, "Characteristic #%d %s (%s) value = %s (0x%x) read successful.", + param_descriptor->cid, + (char*)param_descriptor->param_key, + (char*)param_descriptor->param_units, + (const char*)rw_str, + *(uint16_t*)temp_data_ptr); + if (state & param_descriptor->param_opts.opt1) { + alarm_state = true; + break; + } + } + } else { + ESP_LOGE(MASTER_TAG, "Characteristic #%d (%s) read fail, err = 0x%x (%s).", + param_descriptor->cid, + (char*)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(MASTER_TAG, "Alarm triggered by cid #%d.", + param_descriptor->cid); + } else { + ESP_LOGE(MASTER_TAG, "Alarm is not triggered after %d retries.", + MASTER_MAX_RETRY); + } + ESP_LOGI(MASTER_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); + MASTER_CHECK((master_handler != NULL), ESP_ERR_INVALID_STATE, + "mb controller initialization fail."); + MASTER_CHECK((err == ESP_OK), ESP_ERR_INVALID_STATE, + "mb controller initialization fail, returns(0x%x).", + (uint32_t)err); + err = mbc_master_setup((void*)&comm); + MASTER_CHECK((err == ESP_OK), ESP_ERR_INVALID_STATE, + "mb controller setup fail, returns(0x%x).", + (uint32_t)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); + + err = mbc_master_start(); + MASTER_CHECK((err == ESP_OK), ESP_ERR_INVALID_STATE, + "mb controller start fail, returns(0x%x).", + (uint32_t)err); + + MASTER_CHECK((err == ESP_OK), ESP_ERR_INVALID_STATE, + "mb serial set pin failure, uart_set_pin() returned (0x%x).", (uint32_t)err); + // Set driver mode to Half Duplex + err = uart_set_mode(MB_PORT_NUM, UART_MODE_RS485_HALF_DUPLEX); + MASTER_CHECK((err == ESP_OK), ESP_ERR_INVALID_STATE, + "mb serial set mode failure, uart_set_mode() returned (0x%x).", (uint32_t)err); + + vTaskDelay(5); + err = mbc_master_set_descriptor(&device_parameters[0], num_device_parameters); + MASTER_CHECK((err == ESP_OK), ESP_ERR_INVALID_STATE, + "mb controller set descriptor fail, returns(0x%x).", + (uint32_t)err); + ESP_LOGI(MASTER_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); +} diff --git a/examples/protocols/modbus/serial/mb_master/sdkconfig.defaults b/examples/protocols/modbus/serial/mb_master/sdkconfig.defaults new file mode 100644 index 00000000..7b669af0 --- /dev/null +++ b/examples/protocols/modbus/serial/mb_master/sdkconfig.defaults @@ -0,0 +1,11 @@ +# +# Modbus configuration +# +CONFIG_MB_COMM_MODE_ASCII=y +CONFIG_MB_UART_BAUD_RATE=115200 +CONFIG_FMB_TIMER_PORT_ENABLED=y +CONFIG_FMB_TIMER_GROUP=0 +CONFIG_FMB_TIMER_INDEX=0 +CONFIG_FMB_TIMER_ISR_IN_IRAM=y +CONFIG_FMB_MASTER_DELAY_MS_CONVERT=200 +CONFIG_FMB_MASTER_TIMEOUT_MS_RESPOND=150 diff --git a/examples/protocols/modbus/serial/mb_slave/CMakeLists.txt b/examples/protocols/modbus/serial/mb_slave/CMakeLists.txt new file mode 100644 index 00000000..ef502085 --- /dev/null +++ b/examples/protocols/modbus/serial/mb_slave/CMakeLists.txt @@ -0,0 +1,9 @@ +# 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.5) + +set(EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/protocols/modbus/mb_example_common) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) + +project(modbus_slave) diff --git a/examples/protocols/modbus/serial/mb_slave/Makefile b/examples/protocols/modbus/serial/mb_slave/Makefile new file mode 100644 index 00000000..b9df4baa --- /dev/null +++ b/examples/protocols/modbus/serial/mb_slave/Makefile @@ -0,0 +1,11 @@ +# +# This is a project Makefile. It is assumed the directory this Makefile resides in is a +# project subdirectory. +# + +PROJECT_NAME := modbus_slave + +EXTRA_COMPONENT_DIRS := $(IDF_PATH)/examples/protocols/modbus/mb_example_common + +include $(IDF_PATH)/make/project.mk + diff --git a/examples/protocols/modbus/serial/mb_slave/README.md b/examples/protocols/modbus/serial/mb_slave/README.md new file mode 100644 index 00000000..427c0cb6 --- /dev/null +++ b/examples/protocols/modbus/serial/mb_slave/README.md @@ -0,0 +1,96 @@ +| Supported Targets | ESP32 | +| ----------------- | ----- | + +# Modbus Slave Example + +This example demonstrates using of FreeModbus stack port implementation for ESP32. 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 contains the `/port` folder inside with FreeModbus stack port for ESP32. 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: +PC + USB Serial adapter connected to USB port + RS485 line drivers + ESP32 WROVER-KIT 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 WROVER-KIT 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 WROVER KIT 1 | | 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 command and table below. +``` + -------------------------------------------------------------------------------------------------------------------------- + | ESP32 Interface | #define | Default ESP32 Pin | Default ESP32-S2 Pins | External RS485 Driver Pin | + | ----------------------|--------------------|-----------------------|-----------------------|---------------------------| + | Transmit Data (TxD) | CONFIG_MB_UART_TXD | GPIO23 | GPIO20 | DI | + | Receive Data (RxD) | CONFIG_MB_UART_RXD | GPIO22 | GPIO19 | RO | + | Request To Send (RTS) | CONFIG_MB_UART_RTS | GPIO18 | GPIO18 | ~RE/DE | + | Ground | n/a | GND | GND | GND | + -------------------------------------------------------------------------------------------------------------------------- +``` +Note: The GPIO22 - GPIO25 can not be used with ESP32-S2 chip because they are used for flash chip connection. Please refer to UART documentation for selected target. + +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 WROVER-KIT 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. + diff --git a/examples/protocols/modbus/serial/mb_slave/main/CMakeLists.txt b/examples/protocols/modbus/serial/mb_slave/main/CMakeLists.txt new file mode 100644 index 00000000..b4a0874a --- /dev/null +++ b/examples/protocols/modbus/serial/mb_slave/main/CMakeLists.txt @@ -0,0 +1,4 @@ +set(PROJECT_NAME "modbus_slave") + +idf_component_register(SRCS "slave.c" + INCLUDE_DIRS ".") \ No newline at end of file diff --git a/examples/protocols/modbus/serial/mb_slave/main/Kconfig.projbuild b/examples/protocols/modbus/serial/mb_slave/main/Kconfig.projbuild new file mode 100644 index 00000000..e722f864 --- /dev/null +++ b/examples/protocols/modbus/serial/mb_slave/main/Kconfig.projbuild @@ -0,0 +1,75 @@ +menu "Modbus Example Configuration" + + config MB_UART_PORT_NUM + int "UART port number" + range 0 2 if IDF_TARGET_ESP32 + default 2 if IDF_TARGET_ESP32 + range 0 1 if IDF_TARGET_ESP32S2 + default 1 if IDF_TARGET_ESP32S2 + 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 0 34 if IDF_TARGET_ESP32 + default 22 if IDF_TARGET_ESP32 + range 0 46 if IDF_TARGET_ESP32S2 + default 19 if IDF_TARGET_ESP32S2 + 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 0 34 if IDF_TARGET_ESP32 + default 23 if IDF_TARGET_ESP32 + range 0 46 if IDF_TARGET_ESP32S2 + default 20 if IDF_TARGET_ESP32S2 + 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 0 34 if IDF_TARGET_ESP32 + range 0 46 if IDF_TARGET_ESP32S2 + default 18 + 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 diff --git a/examples/protocols/modbus/serial/mb_slave/main/component.mk b/examples/protocols/modbus/serial/mb_slave/main/component.mk new file mode 100644 index 00000000..b4fa7279 --- /dev/null +++ b/examples/protocols/modbus/serial/mb_slave/main/component.mk @@ -0,0 +1,4 @@ +# +# Main Makefile. This is basically the same as a component makefile. +# +# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.) diff --git a/examples/protocols/modbus/serial/mb_slave/main/slave.c b/examples/protocols/modbus/serial/mb_slave/main/slave.c new file mode 100644 index 00000000..70a23d37 --- /dev/null +++ b/examples/protocols/modbus/serial/mb_slave/main/slave.c @@ -0,0 +1,202 @@ +/* FreeModbus Slave Example ESP32 + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ +#include +#include +#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 MB_REG_DISCRETE_INPUT_START (0x0000) +#define MB_REG_INPUT_START (0x0000) +#define MB_REG_HOLDING_START (0x0000) +#define MB_REG_COILS_START (0x0000) + +#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 *SLAVE_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_input1 = 1; + discrete_reg_params.discrete_input3 = 1; + discrete_reg_params.discrete_input5 = 1; + discrete_reg_params.discrete_input7 = 1; + + 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; + + 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; +} + +// 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(SLAVE_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 parameters 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; // Offset of register area in Modbus protocol + reg_area.address = (void*)&holding_reg_params; // Set pointer to storage instance + reg_area.size = sizeof(holding_reg_params); // 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; + reg_area.address = (void*)&input_reg_params; + reg_area.size = sizeof(input_reg_params); + 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(SLAVE_TAG, "Modbus slave stack initialized."); + ESP_LOGI(SLAVE_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 + mb_event_group_t event = mbc_slave_check_event(MB_READ_WRITE_MASK); + const char* rw_str = (event & MB_READ_MASK) ? "READ" : "WRITE"; + + // Filter events and process them accordingly + if(event & (MB_EVENT_HOLDING_REG_WR | MB_EVENT_HOLDING_REG_RD)) { + // Get parameter information from parameter queue + ESP_ERROR_CHECK(mbc_slave_get_param_info(®_info, MB_PAR_INFO_GET_TOUT)); + ESP_LOGI(SLAVE_TAG, "HOLDING %s (%u us), ADDR:%u, TYPE:%u, INST_ADDR:0x%.4x, SIZE:%u", + rw_str, + (uint32_t)reg_info.time_stamp, + (uint32_t)reg_info.mb_offset, + (uint32_t)reg_info.type, + (uint32_t)reg_info.address, + (uint32_t)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 (event & MB_EVENT_INPUT_REG_RD) { + ESP_ERROR_CHECK(mbc_slave_get_param_info(®_info, MB_PAR_INFO_GET_TOUT)); + ESP_LOGI(SLAVE_TAG, "INPUT READ (%u us), ADDR:%u, TYPE:%u, INST_ADDR:0x%.4x, SIZE:%u", + (uint32_t)reg_info.time_stamp, + (uint32_t)reg_info.mb_offset, + (uint32_t)reg_info.type, + (uint32_t)reg_info.address, + (uint32_t)reg_info.size); + } else if (event & MB_EVENT_DISCRETE_RD) { + ESP_ERROR_CHECK(mbc_slave_get_param_info(®_info, MB_PAR_INFO_GET_TOUT)); + ESP_LOGI(SLAVE_TAG, "DISCRETE READ (%u us): ADDR:%u, TYPE:%u, INST_ADDR:0x%.4x, SIZE:%u", + (uint32_t)reg_info.time_stamp, + (uint32_t)reg_info.mb_offset, + (uint32_t)reg_info.type, + (uint32_t)reg_info.address, + (uint32_t)reg_info.size); + } else if (event & (MB_EVENT_COILS_RD | MB_EVENT_COILS_WR)) { + ESP_ERROR_CHECK(mbc_slave_get_param_info(®_info, MB_PAR_INFO_GET_TOUT)); + ESP_LOGI(SLAVE_TAG, "COILS %s (%u us), ADDR:%u, TYPE:%u, INST_ADDR:0x%.4x, SIZE:%u", + rw_str, + (uint32_t)reg_info.time_stamp, + (uint32_t)reg_info.mb_offset, + (uint32_t)reg_info.type, + (uint32_t)reg_info.address, + (uint32_t)reg_info.size); + if (coil_reg_params.coils_port1 == 0xFF) break; + } + } + // Destroy of Modbus controller on alarm + ESP_LOGI(SLAVE_TAG,"Modbus controller destroyed."); + vTaskDelay(100); + ESP_ERROR_CHECK(mbc_slave_destroy()); +} diff --git a/examples/protocols/modbus/serial/mb_slave/sdkconfig.defaults b/examples/protocols/modbus/serial/mb_slave/sdkconfig.defaults new file mode 100644 index 00000000..334a4213 --- /dev/null +++ b/examples/protocols/modbus/serial/mb_slave/sdkconfig.defaults @@ -0,0 +1,10 @@ +# +# 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_GROUP=0 +CONFIG_FMB_TIMER_INDEX=0 +CONFIG_FMB_TIMER_ISR_IN_IRAM=y diff --git a/examples/protocols/modbus/tcp/README.md b/examples/protocols/modbus/tcp/README.md new file mode 100644 index 00000000..5e62a000 --- /dev/null +++ b/examples/protocols/modbus/tcp/README.md @@ -0,0 +1,58 @@ +# 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. + + diff --git a/examples/protocols/modbus/tcp/example_test.py b/examples/protocols/modbus/tcp/example_test.py new file mode 100644 index 00000000..1db10be0 --- /dev/null +++ b/examples/protocols/modbus/tcp/example_test.py @@ -0,0 +1,303 @@ +import os +import re +import logging +from threading import Thread + +import ttfw_idf +from tiny_test_fw import DUT + +LOG_LEVEL = logging.DEBUG +LOGGER_NAME = "modbus_test" + +# Allowed options for the test +TEST_READ_MAX_ERR_COUNT = 3 # Maximum allowed read errors during initialization +TEST_THREAD_JOIN_TIMEOUT = 60 # Test theread join timeout in seconds +TEST_EXPECT_STR_TIMEOUT = 30 # Test expect timeout in seconds +TEST_MASTER_TCP = 'mb_tcp_master' +TEST_SLAVE_TCP = 'mb_tcp_slave' + +STACK_DEFAULT = 0 +STACK_IPV4 = 1 +STACK_IPV6 = 2 +STACK_INIT = 3 +STACK_CONNECT = 4 +STACK_START = 5 +STACK_PAR_OK = 6 +STACK_PAR_FAIL = 7 +STACK_DESTROY = 8 + +pattern_dict_slave = {STACK_IPV4: (r'.*I \([0-9]+\) example_connect: - IPv4 address: ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*'), + STACK_IPV6: (r'.*I \([0-9]+\) example_connect: - IPv6 address: (([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4}).*'), + STACK_INIT: (r'.*I \(([0-9]+)\) MB_TCP_SLAVE_PORT: (Protocol stack initialized).'), + STACK_CONNECT: (r'.*I\s\(([0-9]+)\) MB_TCP_SLAVE_PORT: Socket \(#[0-9]+\), accept client connection from address: ' + r'([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*'), + STACK_START: (r'.*I\s\(([0-9]+)\) SLAVE_TEST: (Start modbus test).*'), + STACK_PAR_OK: (r'.*I\s\(([0-9]+)\) SLAVE_TEST: ([A-Z]+ [A-Z]+) \([a-zA-Z0-9_]+ us\),\s' + r'ADDR:([0-9]+), TYPE:[0-9]+, INST_ADDR:0x[a-zA-Z0-9]+, SIZE:[0-9]+'), + STACK_PAR_FAIL: (r'.*E \(([0-9]+)\) SLAVE_TEST: Response time exceeds configured [0-9]+ [ms], ignore packet.*'), + STACK_DESTROY: (r'.*I\s\(([0-9]+)\) SLAVE_TEST: (Modbus controller destroyed).')} + +pattern_dict_master = {STACK_IPV4: (r'.*I \([0-9]+\) example_connect: - IPv4 address: ([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*'), + STACK_IPV6: (r'.*I \([0-9]+\) example_connect: - IPv6 address: (([A-Fa-f0-9]{1,4}::?){1,7}[A-Fa-f0-9]{1,4}).*'), + STACK_INIT: (r'.*I \(([0-9]+)\) MASTER_TEST: (Modbus master stack initialized).*'), + STACK_CONNECT: (r'.*.*I\s\(([0-9]+)\) MB_TCP_MASTER_PORT: (Connected [0-9]+ slaves), start polling.*'), + STACK_START: (r'.*I \(([0-9]+)\) MASTER_TEST: (Start modbus test).*'), + STACK_PAR_OK: (r'.*I\s\(([0-9]+)\) MASTER_TEST: Characteristic #[0-9]+ ([a-zA-Z0-9_]+)' + r'\s\([a-zA-Z\%\/]+\) value = [a-zA-Z0-9\.]+ \(0x[a-zA-Z0-9]+\) read successful.*'), + STACK_PAR_FAIL: (r'.*E \(([0-9]+)\) MASTER_TEST: Characteristic #[0-9]+\s\(([a-zA-Z0-9_]+)\)\s' + r'read fail, err = [0-9]+ \([_A-Z]+\).*'), + STACK_DESTROY: (r'.*I\s\(([0-9]+)\) MASTER_TEST: (Destroy master).*')} + +logger = logging.getLogger(LOGGER_NAME) + + +class DutTestThread(Thread): + """ Test thread class + """ + def __init__(self, dut=None, name=None, ip_addr=None, expect=None): + """ Initialize the thread parameters + """ + self.tname = name + self.dut = dut + self.expected = expect + self.data = None + self.ip_addr = ip_addr + self.test_finish = False + self.param_fail_count = 0 + self.param_ok_count = 0 + self.test_stage = STACK_DEFAULT + super(DutTestThread, self).__init__() + + def __enter__(self): + logger.debug("Restart %s." % self.tname) + # Reset DUT first + self.dut.reset() + # Capture output from the DUT + self.dut.start_capture_raw_data(capture_id=self.dut.name) + return self + + def __exit__(self, exc_type, exc_value, traceback): + """ The exit method of context manager + """ + if exc_type is not None or exc_value is not None: + logger.info("Thread %s rised an exception type: %s, value: %s" % (self.tname, str(exc_type), str(exc_value))) + + def run(self): + """ The function implements thread functionality + """ + # Initialize slave IP for master board + if (self.ip_addr is not None): + self.set_ip(0) + + # Check expected strings in the listing + self.test_start(TEST_EXPECT_STR_TIMEOUT) + + # Check DUT exceptions + dut_exceptions = self.dut.get_exceptions() + if "Guru Meditation Error:" in dut_exceptions: + raise Exception("%s generated an exception: %s\n" % (str(self.dut), dut_exceptions)) + + # Mark thread has run to completion without any exceptions + self.data = self.dut.stop_capture_raw_data(capture_id=self.dut.name) + + def set_ip(self, index=0): + """ The method to send slave IP to master application + """ + message = r'.*Waiting IP([0-9]{1,2}) from stdin.*' + # Read all data from previous restart to get prompt correctly + self.dut.read() + result = self.dut.expect(re.compile(message), TEST_EXPECT_STR_TIMEOUT) + if int(result[0]) != index: + raise Exception("Incorrect index of IP=%d for %s\n" % (int(result[0]), str(self.dut))) + message = "IP%s=%s" % (result[0], self.ip_addr) + self.dut.write(message, "\r\n", False) + logger.debug("Sent message for %s: %s" % (self.tname, message)) + message = r'.*IP\([0-9]+\) = \[([0-9a-zA-Z\.\:]+)\] set from stdin.*' + result = self.dut.expect(re.compile(message), TEST_EXPECT_STR_TIMEOUT) + logger.debug("Thread %s initialized with slave IP (%s)." % (self.tname, result[0])) + + def test_start(self, timeout_value): + """ The method to initialize and handle test stages + """ + def handle_get_ip4(data): + """ Handle get_ip v4 + """ + logger.debug("%s[STACK_IPV4]: %s" % (self.tname, str(data))) + self.test_stage = STACK_IPV4 + + def handle_get_ip6(data): + """ Handle get_ip v6 + """ + logger.debug("%s[STACK_IPV6]: %s" % (self.tname, str(data))) + self.test_stage = STACK_IPV6 + + def handle_init(data): + """ Handle init + """ + logger.debug("%s[STACK_INIT]: %s" % (self.tname, str(data))) + self.test_stage = STACK_INIT + + def handle_connect(data): + """ Handle connect + """ + logger.debug("%s[STACK_CONNECT]: %s" % (self.tname, str(data))) + self.test_stage = STACK_CONNECT + + def handle_test_start(data): + """ Handle connect + """ + logger.debug("%s[STACK_START]: %s" % (self.tname, str(data))) + self.test_stage = STACK_START + + def handle_par_ok(data): + """ Handle parameter ok + """ + logger.debug("%s[READ_PAR_OK]: %s" % (self.tname, str(data))) + if self.test_stage >= STACK_START: + self.param_ok_count += 1 + self.test_stage = STACK_PAR_OK + + def handle_par_fail(data): + """ Handle parameter fail + """ + logger.debug("%s[READ_PAR_FAIL]: %s" % (self.tname, str(data))) + self.param_fail_count += 1 + self.test_stage = STACK_PAR_FAIL + + def handle_destroy(data): + """ Handle destroy + """ + logger.debug("%s[DESTROY]: %s" % (self.tname, str(data))) + self.test_stage = STACK_DESTROY + self.test_finish = True + + while not self.test_finish: + try: + self.dut.expect_any((re.compile(self.expected[STACK_IPV4]), handle_get_ip4), + (re.compile(self.expected[STACK_IPV6]), handle_get_ip6), + (re.compile(self.expected[STACK_INIT]), handle_init), + (re.compile(self.expected[STACK_CONNECT]), handle_connect), + (re.compile(self.expected[STACK_START]), handle_test_start), + (re.compile(self.expected[STACK_PAR_OK]), handle_par_ok), + (re.compile(self.expected[STACK_PAR_FAIL]), handle_par_fail), + (re.compile(self.expected[STACK_DESTROY]), handle_destroy), + timeout=timeout_value) + except DUT.ExpectTimeout: + logger.debug("%s, expect timeout on stage #%d (%s seconds)" % (self.tname, self.test_stage, timeout_value)) + self.test_finish = True + + +def test_check_mode(dut=None, mode_str=None, value=None): + """ Check communication mode for dut + """ + global logger + try: + opt = dut.app.get_sdkconfig()[mode_str] + logger.debug("%s {%s} = %s.\n" % (str(dut), mode_str, opt)) + return value == opt + except Exception: + logger.error('ENV_TEST_FAILURE: %s: Cannot find option %s in sdkconfig.' % (str(dut), mode_str)) + return False + + +@ttfw_idf.idf_example_test(env_tag='Example_Modbus_TCP') +def test_modbus_communication(env, comm_mode): + global logger + + rel_project_path = os.path.join('examples', 'protocols', 'modbus', 'tcp') + # Get device under test. Both duts must be able to be connected to WiFi router + dut_master = env.get_dut('modbus_tcp_master', os.path.join(rel_project_path, TEST_MASTER_TCP)) + dut_slave = env.get_dut('modbus_tcp_slave', os.path.join(rel_project_path, TEST_SLAVE_TCP)) + log_file = os.path.join(env.log_path, "modbus_tcp_test.log") + print("Logging file name: %s" % log_file) + + try: + # create file handler which logs even debug messages + logger.setLevel(logging.DEBUG) + fh = logging.FileHandler(log_file) + fh.setLevel(logging.DEBUG) + # set format of output for both handlers + formatter = logging.Formatter('%(levelname)s:%(message)s') + fh.setFormatter(formatter) + logger.addHandler(fh) + # create console handler + ch = logging.StreamHandler() + ch.setLevel(logging.INFO) + # set format of output for both handlers + formatter = logging.Formatter('%(levelname)s:%(message)s') + ch.setFormatter(formatter) + logger.addHandler(ch) + + # Check Kconfig configuration options for each built example + if (test_check_mode(dut_master, "CONFIG_FMB_COMM_MODE_TCP_EN", "y") and + test_check_mode(dut_slave, "CONFIG_FMB_COMM_MODE_TCP_EN", "y")): + slave_name = TEST_SLAVE_TCP + master_name = TEST_MASTER_TCP + else: + logger.error("ENV_TEST_FAILURE: IP resolver mode do not match in the master and slave implementation.\n") + raise Exception("ENV_TEST_FAILURE: IP resolver mode do not match in the master and slave implementation.\n") + address = None + if test_check_mode(dut_master, "CONFIG_MB_SLAVE_IP_FROM_STDIN", "y"): + logger.info("ENV_TEST_INFO: Set slave IP address through STDIN.\n") + # Flash app onto DUT (Todo: Debug case when the slave flashed before master then expect does not work correctly for no reason + dut_slave.start_app() + dut_master.start_app() + if test_check_mode(dut_master, "CONFIG_EXAMPLE_CONNECT_IPV6", "y"): + address = dut_slave.expect(re.compile(pattern_dict_slave[STACK_IPV6]), TEST_EXPECT_STR_TIMEOUT) + else: + address = dut_slave.expect(re.compile(pattern_dict_slave[STACK_IPV4]), TEST_EXPECT_STR_TIMEOUT) + if address is not None: + print("Found IP slave address: %s" % address[0]) + else: + raise Exception("ENV_TEST_FAILURE: Slave IP address is not found in the output. Check network settings.\n") + else: + raise Exception("ENV_TEST_FAILURE: Slave IP resolver is not configured correctly.\n") + + # Create thread for each dut + with DutTestThread(dut=dut_master, name=master_name, ip_addr=address[0], expect=pattern_dict_master) as dut_master_thread: + with DutTestThread(dut=dut_slave, name=slave_name, ip_addr=None, expect=pattern_dict_slave) as dut_slave_thread: + + # Start each thread + dut_slave_thread.start() + dut_master_thread.start() + + # Wait for threads to complete + dut_slave_thread.join(timeout=TEST_THREAD_JOIN_TIMEOUT) + dut_master_thread.join(timeout=TEST_THREAD_JOIN_TIMEOUT) + + if dut_slave_thread.isAlive(): + logger.error("ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" % + (dut_slave_thread.tname, TEST_THREAD_JOIN_TIMEOUT)) + raise Exception("ENV_TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" % + (dut_slave_thread.tname, TEST_THREAD_JOIN_TIMEOUT)) + + if dut_master_thread.isAlive(): + logger.error("TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" % + (dut_master_thread.tname, TEST_THREAD_JOIN_TIMEOUT)) + raise Exception("TEST_FAILURE: The thread %s is not completed successfully after %d seconds.\n" % + (dut_master_thread.tname, TEST_THREAD_JOIN_TIMEOUT)) + + logger.info("TEST_INFO: %s error count = %d, %s error count = %d.\n" % + (dut_master_thread.tname, dut_master_thread.param_fail_count, + dut_slave_thread.tname, dut_slave_thread.param_fail_count)) + logger.info("TEST_INFO: %s ok count = %d, %s ok count = %d.\n" % + (dut_master_thread.tname, dut_master_thread.param_ok_count, + dut_slave_thread.tname, dut_slave_thread.param_ok_count)) + + if ((dut_master_thread.param_fail_count > TEST_READ_MAX_ERR_COUNT) or + (dut_slave_thread.param_fail_count > TEST_READ_MAX_ERR_COUNT) or + (dut_slave_thread.param_ok_count == 0) or + (dut_master_thread.param_ok_count == 0)): + raise Exception("TEST_FAILURE: %s parameter read error(ok) count = %d(%d), %s parameter read error(ok) count = %d(%d).\n" % + (dut_master_thread.tname, dut_master_thread.param_fail_count, dut_master_thread.param_ok_count, + dut_slave_thread.tname, dut_slave_thread.param_fail_count, dut_slave_thread.param_ok_count)) + logger.info("TEST_SUCCESS: The Modbus parameter test is completed successfully.\n") + + finally: + dut_master.close() + dut_slave.close() + logging.shutdown() + + +if __name__ == '__main__': + test_modbus_communication() diff --git a/examples/protocols/modbus/tcp/mb_tcp_master/CMakeLists.txt b/examples/protocols/modbus/tcp/mb_tcp_master/CMakeLists.txt new file mode 100644 index 00000000..ab7d677b --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_master/CMakeLists.txt @@ -0,0 +1,11 @@ +# 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.5) + +set(EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/protocols/modbus/mb_example_common) +# (Not part of the boilerplate) +# This example uses an extra component for common functions such as Wi-Fi and Ethernet connection. +list(APPEND EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/common_components/protocol_examples_common) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(modbus_tcp_master) diff --git a/examples/protocols/modbus/tcp/mb_tcp_master/Makefile b/examples/protocols/modbus/tcp/mb_tcp_master/Makefile new file mode 100644 index 00000000..1f60bf1c --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_master/Makefile @@ -0,0 +1,11 @@ +# +# This is a project Makefile. It is assumed the directory this Makefile resides in is a +# project subdirectory. +# + +PROJECT_NAME := modbus_tcp_master + +EXTRA_COMPONENT_DIRS := $(IDF_PATH)/examples/protocols/modbus/mb_example_common +EXTRA_COMPONENT_DIRS += $(IDF_PATH)/examples/common_components/protocol_examples_common + +include $(IDF_PATH)/make/project.mk diff --git a/examples/protocols/modbus/tcp/mb_tcp_master/README.md b/examples/protocols/modbus/tcp/mb_tcp_master/README.md new file mode 100644 index 00000000..0f66c72d --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_master/README.md @@ -0,0 +1,143 @@ +# Modbus TCP Master Example + +This example demonstrates using of FreeModbus stack port implementation for ESP32 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(-S2) development board with modbus_tcp_slave example. + +Option 2: +Several ESP32(-S2) 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(-S2) 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 WROVER KIT 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 addresse(s). +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). + diff --git a/examples/protocols/modbus/tcp/mb_tcp_master/main/CMakeLists.txt b/examples/protocols/modbus/tcp/mb_tcp_master/main/CMakeLists.txt new file mode 100644 index 00000000..6a75e2d6 --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_master/main/CMakeLists.txt @@ -0,0 +1,5 @@ +set(PROJECT_NAME "modbus_tcp_master") + +idf_component_register(SRCS "tcp_master.c" + INCLUDE_DIRS ".") + diff --git a/examples/protocols/modbus/tcp/mb_tcp_master/main/Kconfig.projbuild b/examples/protocols/modbus/tcp/mb_tcp_master/main/Kconfig.projbuild new file mode 100644 index 00000000..31e15aeb --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_master/main/Kconfig.projbuild @@ -0,0 +1,16 @@ +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 diff --git a/examples/protocols/modbus/tcp/mb_tcp_master/main/component.mk b/examples/protocols/modbus/tcp/mb_tcp_master/main/component.mk new file mode 100644 index 00000000..a98f634e --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_master/main/component.mk @@ -0,0 +1,4 @@ +# +# "main" pseudo-component makefile. +# +# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.) diff --git a/examples/protocols/modbus/tcp/mb_tcp_master/main/tcp_master.c b/examples/protocols/modbus/tcp/mb_tcp_master/main/tcp_master.c new file mode 100644 index 00000000..5a9cb629 --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_master/main/tcp_master.c @@ -0,0 +1,600 @@ +// Copyright 2016-2019 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "string.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 "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_RATE_MS) + +// Timeout between polls +#define POLL_TIMEOUT_MS (1) +#define POLL_TIMEOUT_TICS (POLL_TIMEOUT_MS / portTICK_RATE_MS) +#define MB_MDNS_PORT (502) + +#define MASTER_TAG "MASTER_TEST" + +#define MASTER_CHECK(a, ret_val, str, ...) \ + if (!(a)) { \ + ESP_LOGE(MASTER_TAG, "%s(%u): " str, __FUNCTION__, __LINE__, ##__VA_ARGS__); \ + return (ret_val); \ + } + +// 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" + +// 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 address 1 + MB_DEVICE_COUNT +}; + +// 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_RELAY_P1, + CID_RELAY_P2, + 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_RELAY_P1, STR("RelayP1"), STR("on/off"), MB_DEVICE_ADDR1, MB_PARAM_COIL, 0, 8, + COIL_OFFSET(coils_port0), PARAM_TYPE_U16, 2, OPTS( BIT1, 0, 0 ), PAR_PERMS_READ_WRITE_TRIGGER }, + { CID_RELAY_P2, STR("RelayP2"), STR("on/off"), MB_DEVICE_ADDR1, MB_PARAM_COIL, 8, 8, + COIL_OFFSET(coils_port1), PARAM_TYPE_U16, 2, OPTS( BIT0, 0, 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[MB_DEVICE_COUNT] = { +#if CONFIG_MB_SLAVE_IP_FROM_STDIN + "FROM_STDIN", // Address corresponds to MB_DEVICE_ADDR1 and set to predefined value by user + NULL +#elif CONFIG_MB_MDNS_IP_RESOLVER + NULL, + NULL +#endif +}; + +#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; + unsigned 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(MASTER_TAG, "IP(%d) = [%s] set from stdin.", ip_cnt, ip_str); + if ((ip_cnt >= MB_DEVICE_COUNT) || (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(MASTER_TAG, "Leave IP(%d) = [%s] set manually.", ip_cnt, addr_table[ip_cnt]); + ip_cnt++; + } else { + ESP_LOGI(MASTER_TAG, "IP(%d) is not set in the table.", ip_cnt); + break; + } + } + } + return ip_cnt; +} + +#elif CONFIG_MB_MDNS_IP_RESOLVER + +// 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(MASTER_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(const char* name, mdns_result_t* result, char** resolved_ip, + mb_tcp_addr_type_t addr_type) +{ + if (!name || !result) { + return ESP_ERR_INVALID_ARG; + } + mdns_result_t* r = result; + int t; + char* slave_ip = NULL; + 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, name) == 0) && (r->port == CONFIG_FMB_TCP_PORT_DEFAULT)) { + printf(" PTR : %s\n", r->instance_name); + if (r->txt_count) { + printf(" TXT : [%u] ", 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(MASTER_TAG, "Resolved slave %s[%s]:%u", r->hostname, slave_ip, r->port); + *resolved_ip = slave_ip; + return ESP_OK; + } + } + } + *resolved_ip = NULL; + ESP_LOGD(MASTER_TAG, "Fail to resolve slave: %s", name); + return ESP_ERR_NOT_FOUND; +} + +static int master_create_slave_list(mdns_result_t* results, char** addr_table, + mb_tcp_addr_type_t addr_type) +{ + if (!results) { + return -1; + } + int i, addr, resolved = 0; + const mb_parameter_descriptor_t* pdescr = &device_parameters[0]; + char** ip_table = addr_table; + char slave_name[22] = {0}; + char* slave_ip = NULL; + + for (i = 0; (i < num_device_parameters && pdescr); i++, pdescr++) { + addr = pdescr->mb_slave_addr; + if (-1 == sprintf(slave_name, "mb_slave_tcp_%02X", addr)) { + ESP_LOGI(MASTER_TAG, "Fail to create instance name for index: %d", addr); + abort(); + } + if (!ip_table[addr - 1]) { + esp_err_t err = master_resolve_slave(slave_name, results, &slave_ip, addr_type); + if (err != ESP_OK) { + ESP_LOGE(MASTER_TAG, "Index: %d, sl_addr: %d, name:%s, failed to resolve!", + i, addr, slave_name); + // Set correspond index to NULL indicate host not resolved + ip_table[addr - 1] = NULL; + continue; + } + ip_table[addr - 1] = slave_ip; //slave_name; + ESP_LOGI(MASTER_TAG, "Index: %d, sl_addr: %d, name:%s, resolve to IP: [%s]", + i, addr, slave_name, slave_ip); + resolved++; + } else { + ESP_LOGI(MASTER_TAG, "Index: %d, sl_addr: %d, name:%s, set to IP: [%s]", + i, addr, slave_name, ip_table[addr - 1]); + resolved++; + } + } + return resolved; +} + +static void master_destroy_slave_list(char** table) +{ + for (int i = 0; ((i < MB_DEVICE_COUNT) && table[i] != NULL); i++) { + if (table[i]) { + free(table[i]); + } + } +} + +static int master_query_slave_service(const char * service_name, const char * proto, + mb_tcp_addr_type_t addr_type) +{ + ESP_LOGI(MASTER_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(MASTER_TAG, "Query Failed: %s", esp_err_to_name(err)); + return count; + } + if(!results){ + ESP_LOGW(MASTER_TAG, "No results found!"); + return count; + } + + count = master_create_slave_list(results, slave_ip_address_table, addr_type); + + mdns_query_results_free(results); + return count; +} +#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(MASTER_TAG, "Wrong parameter offset for CID #%d", 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(MASTER_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; + err = mbc_master_get_parameter(cid, (char*)param_descriptor->param_key, + (uint8_t*)&value, &type); + if (err == ESP_OK) { + *(float*)temp_data_ptr = value; + if ((param_descriptor->mb_param_type == MB_PARAM_HOLDING) || + (param_descriptor->mb_param_type == MB_PARAM_INPUT)) { + ESP_LOGI(MASTER_TAG, "Characteristic #%d %s (%s) value = %f (0x%x) read successful.", + param_descriptor->cid, + (char*)param_descriptor->param_key, + (char*)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 { + uint16_t state = *(uint16_t*)temp_data_ptr; + const char* rw_str = (state & param_descriptor->param_opts.opt1) ? "ON" : "OFF"; + ESP_LOGI(MASTER_TAG, "Characteristic #%d %s (%s) value = %s (0x%x) read successful.", + param_descriptor->cid, + (char*)param_descriptor->param_key, + (char*)param_descriptor->param_units, + (const char*)rw_str, + *(uint16_t*)temp_data_ptr); + if (state & param_descriptor->param_opts.opt1) { + alarm_state = true; + break; + } + } + } else { + ESP_LOGE(MASTER_TAG, "Characteristic #%d (%s) read fail, err = %d (%s).", + param_descriptor->cid, + (char*)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(MASTER_TAG, "Alarm triggered by cid #%d.", + param_descriptor->cid); + } else { + ESP_LOGE(MASTER_TAG, "Alarm is not triggered after %d retries.", + MASTER_MAX_RETRY); + } + ESP_LOGI(MASTER_TAG, "Destroy master..."); + vTaskDelay(100); + ESP_ERROR_CHECK(mbc_master_destroy()); +} + +// Modbus master initialization +static esp_err_t master_init(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(); + } + ESP_ERROR_CHECK(result); + esp_netif_init(); + ESP_ERROR_CHECK(esp_event_loop_create_default()); + +#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. + ESP_ERROR_CHECK(example_connect()); + + ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE)); + + mb_communication_info_t comm_info = { 0 }; + comm_info.ip_port = MB_TCP_PORT; +#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_addr = (void*)slave_ip_address_table; + comm_info.ip_netif_ptr = (void*)get_example_netif(); + +#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", comm_info.ip_addr_type); + } + if (res < num_device_parameters) { + ESP_LOGE(MASTER_TAG, "Could not resolve one or more slave IP addresses, resolved: %d out of %d.", res, num_device_parameters ); + ESP_LOGE(MASTER_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(MASTER_TAG, "Configured %d IP addresse(s).", ip_cnt); + } else { + ESP_LOGE(MASTER_TAG, "Fail to get IP address from stdin. Continue."); + } +#endif + + void* master_handler = NULL; + + esp_err_t err = mbc_master_init_tcp(&master_handler); + MASTER_CHECK((master_handler != NULL), ESP_ERR_INVALID_STATE, + "mb controller initialization fail."); + MASTER_CHECK((err == ESP_OK), ESP_ERR_INVALID_STATE, + "mb controller initialization fail, returns(0x%x).", + (uint32_t)err); + + err = mbc_master_setup((void*)&comm_info); + MASTER_CHECK((err == ESP_OK), ESP_ERR_INVALID_STATE, + "mb controller setup fail, returns(0x%x).", + (uint32_t)err); + + err = mbc_master_set_descriptor(&device_parameters[0], num_device_parameters); + MASTER_CHECK((err == ESP_OK), ESP_ERR_INVALID_STATE, + "mb controller set descriptor fail, returns(0x%x).", + (uint32_t)err); + ESP_LOGI(MASTER_TAG, "Modbus master stack initialized..."); + + err = mbc_master_start(); + MASTER_CHECK((err == ESP_OK), ESP_ERR_INVALID_STATE, + "mb controller start fail, returns(0x%x).", + (uint32_t)err); + vTaskDelay(5); + return err; +} + +void app_main(void) +{ + // Initialization of device peripheral and objects + ESP_ERROR_CHECK(master_init()); + vTaskDelay(10); + + master_operation_func(NULL); +#if CONFIG_MB_MDNS_IP_RESOLVER + master_destroy_slave_list(slave_ip_address_table); +#endif + +} diff --git a/examples/protocols/modbus/tcp/mb_tcp_master/sdkconfig.defaults b/examples/protocols/modbus/tcp/mb_tcp_master/sdkconfig.defaults new file mode 100644 index 00000000..baccdaf7 --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_master/sdkconfig.defaults @@ -0,0 +1,19 @@ +# +# 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_FMB_TIMER_GROUP=0 +CONFIG_FMB_TIMER_INDEX=0 +CONFIG_FMB_TIMER_ISR_IN_IRAM=y +CONFIG_MB_MDNS_IP_RESOLVER=n +CONFIG_MB_SLAVE_IP_FROM_STDIN=y +CONFIG_EXAMPLE_CONNECT_IPV6=n \ No newline at end of file diff --git a/examples/protocols/modbus/tcp/mb_tcp_slave/CMakeLists.txt b/examples/protocols/modbus/tcp/mb_tcp_slave/CMakeLists.txt new file mode 100644 index 00000000..e0399628 --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_slave/CMakeLists.txt @@ -0,0 +1,13 @@ +# 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.5) + +# This component includes modbus example common definitions +set(EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/protocols/modbus/mb_example_common) + +# (Not part of the boilerplate) +# This example uses an extra component for common functions such as Wi-Fi and Ethernet connection. +list(APPEND EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/common_components/protocol_examples_common) + +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(modbus_tcp_slave) diff --git a/examples/protocols/modbus/tcp/mb_tcp_slave/Makefile b/examples/protocols/modbus/tcp/mb_tcp_slave/Makefile new file mode 100644 index 00000000..e93a985a --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_slave/Makefile @@ -0,0 +1,11 @@ +# +# This is a project Makefile. It is assumed the directory this Makefile resides in is a +# project subdirectory. +# +PROJECT_NAME := modbus_tcp_slave + +EXTRA_COMPONENT_DIRS := $(IDF_PATH)/examples/protocols/modbus/mb_example_common +EXTRA_COMPONENT_DIRS += $(IDF_PATH)/examples/common_components/protocol_examples_common + +include $(IDF_PATH)/make/project.mk + diff --git a/examples/protocols/modbus/tcp/mb_tcp_slave/README.md b/examples/protocols/modbus/tcp/mb_tcp_slave/README.md new file mode 100644 index 00000000..641c999c --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_slave/README.md @@ -0,0 +1,83 @@ +# Modbus Slave Example + +This example demonstrates using of FreeModbus TCP slave stack port implementation for ESP32(-S2). 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. 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(-S2) 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(-S2) 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(-S2) 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. + diff --git a/examples/protocols/modbus/tcp/mb_tcp_slave/main/CMakeLists.txt b/examples/protocols/modbus/tcp/mb_tcp_slave/main/CMakeLists.txt new file mode 100644 index 00000000..33dbfa35 --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_slave/main/CMakeLists.txt @@ -0,0 +1,4 @@ +set(PROJECT_NAME "modbus_tcp_slave") + +idf_component_register(SRCS "tcp_slave.c" + INCLUDE_DIRS ".") \ No newline at end of file diff --git a/examples/protocols/modbus/tcp/mb_tcp_slave/main/Kconfig.projbuild b/examples/protocols/modbus/tcp/mb_tcp_slave/main/Kconfig.projbuild new file mode 100644 index 00000000..1c6d766d --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_slave/main/Kconfig.projbuild @@ -0,0 +1,18 @@ +menu "Modbus Example Configuration" + + config MB_SLAVE_ADDR + int "Modbus slave address" + range 1 127 + 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 \ No newline at end of file diff --git a/examples/protocols/modbus/tcp/mb_tcp_slave/main/component.mk b/examples/protocols/modbus/tcp/mb_tcp_slave/main/component.mk new file mode 100644 index 00000000..a98f634e --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_slave/main/component.mk @@ -0,0 +1,4 @@ +# +# "main" pseudo-component makefile. +# +# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.) diff --git a/examples/protocols/modbus/tcp/mb_tcp_slave/main/tcp_slave.c b/examples/protocols/modbus/tcp/mb_tcp_slave/main/tcp_slave.c new file mode 100644 index 00000000..a74b0c27 --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_slave/main/tcp_slave.c @@ -0,0 +1,289 @@ +/* FreeModbus Slave Example ESP32 + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ +#include +#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 "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 MB_REG_DISCRETE_INPUT_START (0x0000) +#define MB_REG_INPUT_START (0x0000) +#define MB_REG_HOLDING_START (0x0000) +#define MB_REG_COILS_START (0x0000) + +#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 SLAVE_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_SLAVE_ADDR (CONFIG_MB_SLAVE_ADDR) + +#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() +{ + 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(SLAVE_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))); +} + +#endif + +// Set register values into known state +static void setup_reg_data(void) +{ + // Define initial state of parameters + discrete_reg_params.discrete_input1 = 1; + discrete_reg_params.discrete_input3 = 1; + discrete_reg_params.discrete_input5 = 1; + discrete_reg_params.discrete_input7 = 1; + + 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; + + 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; +} + +// 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_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(); + } + ESP_ERROR_CHECK(result); + esp_netif_init(); + ESP_ERROR_CHECK(esp_event_loop_create_default()); + +#if CONFIG_MB_MDNS_IP_RESOLVER + 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. + */ + ESP_ERROR_CHECK(example_connect()); + + ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE)); + + // Set UART log level + esp_log_level_set(SLAVE_TAG, ESP_LOG_INFO); + void* mbc_slave_handler = NULL; + + ESP_ERROR_CHECK(mbc_slave_init_tcp(&mbc_slave_handler)); // Initialization of Modbus controller + + mb_param_info_t reg_info; // keeps the Modbus registers access information + mb_register_area_descriptor_t reg_area; // Modbus register area descriptor structure + + mb_communication_info_t comm_info = { 0 }; + comm_info.ip_port = MB_TCP_PORT_NUMBER; +#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_addr = NULL; + comm_info.ip_netif_ptr = (void*)get_example_netif(); + // Setup communication parameters and start stack + 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; // Offset of register area in Modbus protocol + reg_area.address = (void*)&holding_reg_params; // Set pointer to storage instance + reg_area.size = sizeof(holding_reg_params); // 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; + reg_area.address = (void*)&input_reg_params; + reg_area.size = sizeof(input_reg_params); + 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()); + + ESP_LOGI(SLAVE_TAG, "Modbus slave stack initialized."); + ESP_LOGI(SLAVE_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 + mb_event_group_t event = mbc_slave_check_event(MB_READ_WRITE_MASK); + const char* rw_str = (event & MB_READ_MASK) ? "READ" : "WRITE"; + // Filter events and process them accordingly + if(event & (MB_EVENT_HOLDING_REG_WR | MB_EVENT_HOLDING_REG_RD)) { + // Get parameter information from parameter queue + ESP_ERROR_CHECK(mbc_slave_get_param_info(®_info, MB_PAR_INFO_GET_TOUT)); + ESP_LOGI(SLAVE_TAG, "HOLDING %s (%u us), ADDR:%u, TYPE:%u, INST_ADDR:0x%.4x, SIZE:%u", + rw_str, + (uint32_t)reg_info.time_stamp, + (uint32_t)reg_info.mb_offset, + (uint32_t)reg_info.type, + (uint32_t)reg_info.address, + (uint32_t)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 (event & MB_EVENT_INPUT_REG_RD) { + ESP_ERROR_CHECK(mbc_slave_get_param_info(®_info, MB_PAR_INFO_GET_TOUT)); + ESP_LOGI(SLAVE_TAG, "INPUT READ (%u us), ADDR:%u, TYPE:%u, INST_ADDR:0x%.4x, SIZE:%u", + (uint32_t)reg_info.time_stamp, + (uint32_t)reg_info.mb_offset, + (uint32_t)reg_info.type, + (uint32_t)reg_info.address, + (uint32_t)reg_info.size); + } else if (event & MB_EVENT_DISCRETE_RD) { + ESP_ERROR_CHECK(mbc_slave_get_param_info(®_info, MB_PAR_INFO_GET_TOUT)); + ESP_LOGI(SLAVE_TAG, "DISCRETE READ (%u us): ADDR:%u, TYPE:%u, INST_ADDR:0x%.4x, SIZE:%u", + (uint32_t)reg_info.time_stamp, + (uint32_t)reg_info.mb_offset, + (uint32_t)reg_info.type, + (uint32_t)reg_info.address, + (uint32_t)reg_info.size); + } else if (event & (MB_EVENT_COILS_RD | MB_EVENT_COILS_WR)) { + ESP_ERROR_CHECK(mbc_slave_get_param_info(®_info, MB_PAR_INFO_GET_TOUT)); + ESP_LOGI(SLAVE_TAG, "COILS %s (%u us), ADDR:%u, TYPE:%u, INST_ADDR:0x%.4x, SIZE:%u", + rw_str, + (uint32_t)reg_info.time_stamp, + (uint32_t)reg_info.mb_offset, + (uint32_t)reg_info.type, + (uint32_t)reg_info.address, + (uint32_t)reg_info.size); + if (coil_reg_params.coils_port1 == 0xFF) break; + } + } + // Destroy of Modbus controller on alarm + ESP_LOGI(SLAVE_TAG,"Modbus controller destroyed."); + vTaskDelay(100); + ESP_ERROR_CHECK(mbc_slave_destroy()); +#if CONFIG_MB_MDNS_IP_RESOLVER + mdns_free(); +#endif +} diff --git a/examples/protocols/modbus/tcp/mb_tcp_slave/sdkconfig.defaults b/examples/protocols/modbus/tcp/mb_tcp_slave/sdkconfig.defaults new file mode 100644 index 00000000..578350f5 --- /dev/null +++ b/examples/protocols/modbus/tcp/mb_tcp_slave/sdkconfig.defaults @@ -0,0 +1,21 @@ +# +# 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_FMB_TIMER_GROUP=0 +CONFIG_FMB_TIMER_INDEX=0 +CONFIG_FMB_TIMER_ISR_IN_IRAM=y +CONFIG_MB_MDNS_IP_RESOLVER=n +CONFIG_MB_SLAVE_IP_FROM_STDIN=y +CONFIG_MB_SLAVE_ADDR=1 +CONFIG_LOG_DEFAULT_LEVEL_DEBUG=y +CONFIG_EXAMPLE_CONNECT_IPV6=n \ No newline at end of file