├── examples ├── modbus_rtu_test.h ├── modbus_tcp_test.h ├── SConscript ├── modbus_rtu_test.c └── modbus_tcp_test.c ├── docs ├── version.md └── README.md ├── SConscript ├── src ├── SConscript ├── modbus-data.c ├── modbus-tcp.c ├── modbus-rtu.c └── modbus.c ├── .gitignore ├── inc ├── modbus-rtu.h ├── modbus-tcp-private.h ├── modbus-tcp.h ├── modbus-rtu-private.h ├── modbus-version.h ├── modbus-private.h └── modbus.h ├── README.md └── LICENSE /examples/modbus_rtu_test.h: -------------------------------------------------------------------------------- 1 | #ifndef __MODBUS_RTU_TEST_H 2 | #define __MODBUS_RTU_TEST_H 3 | #include 4 | #include 5 | #include 6 | 7 | #endif 8 | -------------------------------------------------------------------------------- /examples/modbus_tcp_test.h: -------------------------------------------------------------------------------- 1 | #ifndef __MODBUS_TCP_TEST_H 2 | #define __MODBUS_TCP_TEST_H 3 | #include 4 | #include 5 | #include 6 | 7 | #endif 8 | -------------------------------------------------------------------------------- /docs/version.md: -------------------------------------------------------------------------------- 1 | # 版本和修订 # 2 | 3 | | Date | Version | Author | Note | 4 | | -------- | :-----: | :---- | :---- | 5 | | 2019-03-04 | v1.0 | malongwei | 初始版本 | 6 | | | | | | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # 文档 2 | 3 | ## 软件包地址 4 | 5 | - https://github.com/loogg/libmodbus 6 | 7 | ## 文档列表 8 | 9 | |文件名 |描述| 10 | |:----- |:----| 11 | |[version.md](version.md) |版本信息| 12 | 13 | 14 | -------------------------------------------------------------------------------- /SConscript: -------------------------------------------------------------------------------- 1 | # RT-Thread building script for bridge 2 | 3 | import os 4 | from building import * 5 | 6 | cwd = GetCurrentDir() 7 | objs = [] 8 | list = os.listdir(cwd) 9 | 10 | if GetDepend('PKG_USING_LIBMODBUS'): 11 | for d in list: 12 | path = os.path.join(cwd, d) 13 | if os.path.isfile(os.path.join(path, 'SConscript')): 14 | objs = objs + SConscript(os.path.join(d, 'SConscript')) 15 | 16 | Return('objs') 17 | -------------------------------------------------------------------------------- /examples/SConscript: -------------------------------------------------------------------------------- 1 | from building import * 2 | 3 | cwd = GetCurrentDir() 4 | src = [] 5 | 6 | if GetDepend(['PKG_USING_LIBMODBUS_RTU_EXAMPLE']): 7 | src += Glob('modbus_rtu_test.c') 8 | 9 | if GetDepend(['PKG_USING_LIBMODBUS_TCP_EXAMPLE']): 10 | src += Glob('modbus_tcp_test.c') 11 | 12 | CPPPATH = [cwd] 13 | 14 | group = DefineGroup('libmodbus', src, depend = ['PKG_USING_LIBMODBUS'], CPPPATH = CPPPATH) 15 | 16 | Return('group') 17 | -------------------------------------------------------------------------------- /src/SConscript: -------------------------------------------------------------------------------- 1 | from building import * 2 | 3 | cwd = GetCurrentDir() 4 | src = Split(''' 5 | modbus.c 6 | modbus-data.c 7 | ''') 8 | 9 | if GetDepend(['PKG_USING_LIBMODBUS_RTU']): 10 | src += Glob('modbus-rtu.c') 11 | 12 | if GetDepend(['PKG_USING_LIBMODBUS_TCP']): 13 | src += Glob('modbus-tcp.c') 14 | 15 | CPPPATH = [cwd + '/../inc'] 16 | 17 | group = DefineGroup('libmodbus', src, depend = ['PKG_USING_LIBMODBUS'], CPPPATH = CPPPATH) 18 | 19 | Return('group') 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Object files 5 | *.o 6 | *.ko 7 | *.obj 8 | *.elf 9 | 10 | # Linker output 11 | *.ilk 12 | *.map 13 | *.exp 14 | 15 | # Precompiled Headers 16 | *.gch 17 | *.pch 18 | 19 | # Libraries 20 | *.lib 21 | *.a 22 | *.la 23 | *.lo 24 | 25 | # Shared objects (inc. Windows DLLs) 26 | *.dll 27 | *.so 28 | *.so.* 29 | *.dylib 30 | 31 | # Executables 32 | *.exe 33 | *.out 34 | *.app 35 | *.i*86 36 | *.x86_64 37 | *.hex 38 | 39 | # Debug files 40 | *.dSYM/ 41 | *.su 42 | *.idb 43 | *.pdb 44 | 45 | # Kernel Module Compile Results 46 | *.mod* 47 | *.cmd 48 | .tmp_versions/ 49 | modules.order 50 | Module.symvers 51 | Mkfile.old 52 | dkms.conf 53 | -------------------------------------------------------------------------------- /inc/modbus-rtu.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2001-2011 Stéphane Raimbault 3 | * 4 | * SPDX-License-Identifier: LGPL-2.1+ 5 | */ 6 | 7 | #ifndef MODBUS_RTU_H 8 | #define MODBUS_RTU_H 9 | 10 | #include "modbus.h" 11 | 12 | MODBUS_BEGIN_DECLS 13 | 14 | /* Modbus_Application_Protocol_V1_1b.pdf Chapter 4 Section 1 Page 5 15 | * RS232 / RS485 ADU = 253 bytes + slave (1 byte) + CRC (2 bytes) = 256 bytes 16 | */ 17 | #define MODBUS_RTU_MAX_ADU_LENGTH 256 18 | 19 | MODBUS_API modbus_t* modbus_new_rtu(const char *device, int baud, char parity, 20 | int data_bit, int stop_bit); 21 | 22 | #define MODBUS_RTU_RS232 0 23 | #define MODBUS_RTU_RS485 1 24 | 25 | MODBUS_API int modbus_rtu_set_serial_mode(modbus_t *ctx, int mode); 26 | MODBUS_API int modbus_rtu_get_serial_mode(modbus_t *ctx); 27 | 28 | #define MODBUS_RTU_RTS_NONE 0 29 | #define MODBUS_RTU_RTS_UP 1 30 | #define MODBUS_RTU_RTS_DOWN 2 31 | 32 | MODBUS_API int modbus_rtu_set_rts(modbus_t *ctx, int rts_pin, int mode); 33 | MODBUS_API int modbus_rtu_get_rts(modbus_t *ctx); 34 | 35 | MODBUS_API int modbus_rtu_set_custom_rts(modbus_t *ctx, void (*set_rts) (modbus_t *ctx, int on)); 36 | 37 | MODBUS_API int modbus_rtu_set_rts_delay(modbus_t *ctx, int us); 38 | MODBUS_API int modbus_rtu_get_rts_delay(modbus_t *ctx); 39 | 40 | MODBUS_END_DECLS 41 | 42 | #endif /* MODBUS_RTU_H */ 43 | -------------------------------------------------------------------------------- /inc/modbus-tcp-private.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2001-2011 Stéphane Raimbault 3 | * 4 | * SPDX-License-Identifier: LGPL-2.1+ 5 | */ 6 | 7 | #ifndef MODBUS_TCP_PRIVATE_H 8 | #define MODBUS_TCP_PRIVATE_H 9 | 10 | #define _MODBUS_TCP_HEADER_LENGTH 7 11 | #define _MODBUS_TCP_PRESET_REQ_LENGTH 12 12 | #define _MODBUS_TCP_PRESET_RSP_LENGTH 8 13 | 14 | #define _MODBUS_TCP_CHECKSUM_LENGTH 0 15 | 16 | 17 | /* In both structures, the transaction ID must be placed on first position 18 | to have a quick access not dependant of the TCP backend */ 19 | typedef struct _modbus_tcp { 20 | /* Extract from MODBUS Messaging on TCP/IP Implementation Guide V1.0b 21 | (page 23/46): 22 | The transaction identifier is used to associate the future response 23 | with the request. This identifier is unique on each TCP connection. */ 24 | uint16_t t_id; 25 | /* TCP port */ 26 | int port; 27 | /* IP address */ 28 | char ip[16]; 29 | int domain; 30 | } modbus_tcp_t; 31 | 32 | #define _MODBUS_TCP_PI_NODE_LENGTH 1025 33 | #define _MODBUS_TCP_PI_SERVICE_LENGTH 32 34 | 35 | typedef struct _modbus_tcp_pi { 36 | /* Transaction ID */ 37 | uint16_t t_id; 38 | /* TCP port */ 39 | int port; 40 | /* Node */ 41 | char node[_MODBUS_TCP_PI_NODE_LENGTH]; 42 | /* Service */ 43 | char service[_MODBUS_TCP_PI_SERVICE_LENGTH]; 44 | } modbus_tcp_pi_t; 45 | 46 | #endif /* MODBUS_TCP_PRIVATE_H */ 47 | -------------------------------------------------------------------------------- /inc/modbus-tcp.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2001-2010 Stéphane Raimbault 3 | * 4 | * SPDX-License-Identifier: LGPL-2.1+ 5 | */ 6 | 7 | #ifndef MODBUS_TCP_H 8 | #define MODBUS_TCP_H 9 | 10 | #include "modbus.h" 11 | 12 | MODBUS_BEGIN_DECLS 13 | 14 | #if defined(_WIN32) && !defined(__CYGWIN__) 15 | /* Win32 with MinGW, supplement to */ 16 | #include 17 | #if !defined(ECONNRESET) 18 | #define ECONNRESET WSAECONNRESET 19 | #endif 20 | #if !defined(ECONNREFUSED) 21 | #define ECONNREFUSED WSAECONNREFUSED 22 | #endif 23 | #if !defined(ETIMEDOUT) 24 | #define ETIMEDOUT WSAETIMEDOUT 25 | #endif 26 | #if !defined(ENOPROTOOPT) 27 | #define ENOPROTOOPT WSAENOPROTOOPT 28 | #endif 29 | #if !defined(EINPROGRESS) 30 | #define EINPROGRESS WSAEINPROGRESS 31 | #endif 32 | #endif 33 | 34 | #define MODBUS_TCP_DEFAULT_PORT 502 35 | #define MODBUS_TCP_SLAVE 0xFF 36 | 37 | /* Modbus_Application_Protocol_V1_1b.pdf Chapter 4 Section 1 Page 5 38 | * TCP MODBUS ADU = 253 bytes + MBAP (7 bytes) = 260 bytes 39 | */ 40 | #define MODBUS_TCP_MAX_ADU_LENGTH 260 41 | 42 | MODBUS_API modbus_t* modbus_new_tcp(const char *ip_address, int port ,int domain); 43 | MODBUS_API int modbus_tcp_listen(modbus_t *ctx, int nb_connection); 44 | MODBUS_API int modbus_tcp_accept(modbus_t *ctx, int *s); 45 | 46 | MODBUS_API modbus_t* modbus_new_tcp_pi(const char *node, const char *service); 47 | MODBUS_API int modbus_tcp_pi_listen(modbus_t *ctx, int nb_connection); 48 | MODBUS_API int modbus_tcp_pi_accept(modbus_t *ctx, int *s); 49 | 50 | MODBUS_END_DECLS 51 | 52 | #endif /* MODBUS_TCP_H */ 53 | -------------------------------------------------------------------------------- /examples/modbus_rtu_test.c: -------------------------------------------------------------------------------- 1 | #include "modbus_rtu_test.h" 2 | #include "modbus.h" 3 | #include "stdio.h" 4 | #include "string.h" 5 | 6 | #define RS485_RE GET_PIN(G, 8) 7 | 8 | static void test_thread(void *param) 9 | { 10 | uint16_t tab_reg[64] = {0}; 11 | modbus_t *ctx = RT_NULL; 12 | ctx = modbus_new_rtu("/dev/uart2", 115200, 'N', 8, 1); 13 | modbus_rtu_set_serial_mode(ctx, MODBUS_RTU_RS485); 14 | modbus_rtu_set_rts(ctx, RS485_RE, MODBUS_RTU_RTS_UP); 15 | modbus_set_slave(ctx, 3); 16 | modbus_connect(ctx); 17 | modbus_set_response_timeout(ctx, 0, 1000000); 18 | int num = 0; 19 | while (1) 20 | { 21 | memset(tab_reg, 0, 64 * 2); 22 | int regs = modbus_read_registers(ctx, 0, 20, tab_reg); 23 | printf("-------------------------------------------\n"); 24 | printf("[%4d][read num = %d]", num, regs); 25 | num++; 26 | int i; 27 | for (i = 0; i < 20; i++) 28 | { 29 | printf("<%#x>", tab_reg[i]); 30 | } 31 | printf("\n"); 32 | printf("-------------------------------------------\n"); 33 | rt_thread_mdelay(5000); 34 | } 35 | //7-关闭modbus端口 36 | modbus_close(ctx); 37 | 38 | //8-释放modbus资源 39 | modbus_free(ctx); 40 | } 41 | 42 | static int rtu_test_init(void) 43 | { 44 | rt_pin_mode(RS485_RE, PIN_MODE_OUTPUT); 45 | rt_thread_t tid; 46 | tid = rt_thread_create("test", 47 | test_thread, RT_NULL, 48 | 2048, 49 | 12, 10); 50 | if (tid != RT_NULL) 51 | rt_thread_startup(tid); 52 | return RT_EOK; 53 | } 54 | INIT_APP_EXPORT(rtu_test_init); 55 | -------------------------------------------------------------------------------- /inc/modbus-rtu-private.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2001-2011 Stéphane Raimbault 3 | * 4 | * SPDX-License-Identifier: LGPL-2.1+ 5 | */ 6 | 7 | #ifndef MODBUS_RTU_PRIVATE_H 8 | #define MODBUS_RTU_PRIVATE_H 9 | 10 | #ifndef _MSC_VER 11 | #include 12 | #else 13 | #include "stdint.h" 14 | #endif 15 | 16 | #if defined(_WIN32) 17 | #include 18 | #else 19 | #include 20 | #endif 21 | 22 | #define _MODBUS_RTU_HEADER_LENGTH 1 23 | #define _MODBUS_RTU_PRESET_REQ_LENGTH 6 24 | #define _MODBUS_RTU_PRESET_RSP_LENGTH 2 25 | 26 | #define _MODBUS_RTU_CHECKSUM_LENGTH 2 27 | 28 | #if defined(_WIN32) 29 | #if !defined(ENOTSUP) 30 | #define ENOTSUP WSAEOPNOTSUPP 31 | #endif 32 | 33 | /* WIN32: struct containing serial handle and a receive buffer */ 34 | #define PY_BUF_SIZE 512 35 | struct win32_ser { 36 | /* File handle */ 37 | HANDLE fd; 38 | /* Receive buffer */ 39 | uint8_t buf[PY_BUF_SIZE]; 40 | /* Received chars */ 41 | DWORD n_bytes; 42 | }; 43 | #endif /* _WIN32 */ 44 | 45 | typedef struct _modbus_rtu { 46 | /* Device: "/dev/ttyS0", "/dev/ttyUSB0" or "/dev/tty.USA19*" on Mac OS X. */ 47 | char *device; 48 | /* Bauds: 9600, 19200, 57600, 115200, etc */ 49 | int baud; 50 | /* Data bit */ 51 | uint8_t data_bit; 52 | /* Stop bit */ 53 | uint8_t stop_bit; 54 | /* Parity: 'N', 'O', 'E' */ 55 | char parity; 56 | #if defined(_WIN32) 57 | struct win32_ser w_ser; 58 | DCB old_dcb; 59 | #else 60 | /* Save old termios settings */ 61 | struct termios old_tios; 62 | #endif 63 | #if HAVE_DECL_TIOCSRS485 64 | int serial_mode; 65 | #endif 66 | #if HAVE_DECL_TIOCM_RTS 67 | int rts; 68 | int rts_delay; 69 | int onebyte_time; 70 | int rts_pin; 71 | void (*set_rts) (modbus_t *ctx, int on); 72 | #endif 73 | } modbus_rtu_t; 74 | 75 | #endif /* MODBUS_RTU_PRIVATE_H */ 76 | -------------------------------------------------------------------------------- /inc/modbus-version.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2010-2014 Stéphane Raimbault 3 | * 4 | * This library is free software; you can redistribute it and/or 5 | * modify it under the terms of the GNU Lesser General Public 6 | * License as published by the Free Software Foundation; either 7 | * version 2.1 of the License, or (at your option) any later version. 8 | * 9 | * This library is distributed in the hope that it will be useful, 10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 | * Lesser General Public License for more details. 13 | * 14 | * You should have received a copy of the GNU Lesser General Public 15 | * License along with this library; if not, write to the Free Software 16 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 17 | */ 18 | 19 | #ifndef MODBUS_VERSION_H 20 | #define MODBUS_VERSION_H 21 | 22 | /* The major version, (1, if %LIBMODBUS_VERSION is 1.2.3) */ 23 | #define LIBMODBUS_VERSION_MAJOR (3) 24 | 25 | /* The minor version (2, if %LIBMODBUS_VERSION is 1.2.3) */ 26 | #define LIBMODBUS_VERSION_MINOR (1) 27 | 28 | /* The micro version (3, if %LIBMODBUS_VERSION is 1.2.3) */ 29 | #define LIBMODBUS_VERSION_MICRO (4) 30 | 31 | /* The full version, like 1.2.3 */ 32 | #define LIBMODBUS_VERSION 3.1.4 33 | 34 | /* The full version, in string form (suited for string concatenation) 35 | */ 36 | #define LIBMODBUS_VERSION_STRING "3.1.4" 37 | 38 | /* Numerically encoded version, like 0x010203 */ 39 | #define LIBMODBUS_VERSION_HEX ((LIBMODBUS_VERSION_MAJOR << 24) | \ 40 | (LIBMODBUS_VERSION_MINOR << 16) | \ 41 | (LIBMODBUS_VERSION_MICRO << 8)) 42 | 43 | /* Evaluates to True if the version is greater than @major, @minor and @micro 44 | */ 45 | #define LIBMODBUS_VERSION_CHECK(major,minor,micro) \ 46 | (LIBMODBUS_VERSION_MAJOR > (major) || \ 47 | (LIBMODBUS_VERSION_MAJOR == (major) && \ 48 | LIBMODBUS_VERSION_MINOR > (minor)) || \ 49 | (LIBMODBUS_VERSION_MAJOR == (major) && \ 50 | LIBMODBUS_VERSION_MINOR == (minor) && \ 51 | LIBMODBUS_VERSION_MICRO >= (micro))) 52 | 53 | #endif /* MODBUS_VERSION_H */ 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LIBMODBUS 2 | 3 | ## 不再维护 4 | 5 | libmodbus 放弃维护,推荐使用轻量级 Modbus 协议栈 [agile_modbus](https://github.com/loogg/agile_modbus)。 6 | 7 | ## 1、介绍 8 | 9 | libmodbus是一个与使用Modbus协议的设备进行数据发送/接收的库。该库包含各种后端通过不同网络进行通信(例如,RTU模式下的串口或TCP / IPv6中的以太网)。 10 | 11 | libmodbus提供了较低通信层的抽象,并在所有支持的平台上提供相同的API。 12 | 13 | 本源码实现了在RT-Thread上的移植,支持MODBUS-RTU和MODBUS-TCP。源码地址: 14 | 作者:[loogg](https://github.com/loogg) 15 | 16 | ### 1.1、使用背景 17 | 18 | Modbus 协议是应用于电子控制器上的一种通用语言。通过此协议,控制器相互之间、控制器经由网络(例如以太网)和其它设备之间可以通信。它已经成为一通用工业标准。有了它,不同厂商生产的控制设备可以连成工业网络,进行集中监控。此协议定义了一个控制器能认识使用的消息结构,而不管它们是经过何种网络进行通信的。它描述了一控制器请求访问其它设备的过程,如何回应来自其它设备的请求,以及怎样侦测错误并记录。它制定了消息域格局和内容的公共格式。当在一Modbus网络上通信时,此协议决定了每个控制器须要知道它们的设备地址,识别按地址发来的消息,决定要产生何种行动。如果需要回应,控制器将生成反馈信息并用Modbus 协议发出。在其它网络上,包含了 Modbus 协议的消息转换为在此网络上使用的帧或包结构。这种转换也扩展了根据具体的网络解决节地址、路由路径及错误检测的方法。 19 | 20 | 21 | 22 | ### 1.2、目录结构 23 | 24 | 25 | | 名称 | 说明 | 26 | | ---- | ---- | 27 | | docs | 文档目录 | 28 | | examples | 例子目录,并有相应的一些说明 | 29 | | inc | 头文件目录 | 30 | | src | 源代码目录 | 31 | 32 | ### 1.3、许可证 33 | 34 | libmodbus package 遵循 LGPLv2.1 许可,详见 `LICENSE` 文件。 35 | 36 | ### 1.4、依赖 37 | 38 | - RT-Thread 4.0+ 39 | - Filesystem 40 | - libc 41 | - pin 42 | - serial 43 | - POSIX 44 | - SAL 45 | 46 | ## 2、如何打开 libmodbus 47 | 48 | 使用 libmodbus package 需要在 RT-Thread 的包管理器中选择它,具体路径如下: 49 | 50 | ``` 51 | RT-Thread online packages 52 | IoT - internet of things ---> 53 | [*] libmodbus: A Modbus library for RT-Thread 54 | ``` 55 | 56 | 然后让 RT-Thread 的包管理器自动更新,或者使用 `pkgs --update` 命令更新包到 BSP 中。 57 | 58 | ## 3、使用 libmodbus 59 | 60 | 在打开 libmodbus package 后,当进行 bsp 编译时,它会被加入到 bsp 工程中进行编译。 61 | 62 | ### 3.1、创建modbus RTU 环境 63 | 64 | - 初始化RTU环境指针 65 | 66 | ``` 67 | modbus_t *modbus_new_rtu(const char *device, int baud,char parity, int data_bit, int stop_bit) 68 | ``` 69 | 70 | - 设置串口模式 71 | 72 | ``` 73 | int modbus_rtu_set_serial_mode(modbus_t *ctx, int mode) 74 | ``` 75 | 76 | - 在RTU环境下设置RTS模式,为RS485模式下设置控制引脚 77 | 78 | ``` 79 | int modbus_rtu_set_rts(modbus_t *ctx, int rts_pin, int mode) 80 | ``` 81 | 82 | | mode | 说明 | 83 | | ---- | ---- | 84 | | MODBUS_RTU_RTS_NONE | 无控制 | 85 | | MODBUS_RTU_RTS_UP | 高电平为发送模式 | 86 | | MODBUS_RTU_RTS_DOWN | 低电平为发送模式 | 87 | 88 | ### 3.2、创建modbus TCP 环境 89 | 90 | - 初始化TCP环境指针 91 | 92 | ``` 93 | modbus_t *modbus_new_tcp(const char *ip, int port) 94 | ``` 95 | 96 | - 作为客户端连接服务器 97 | 98 | ``` 99 | int modbus_connect(modbus_t *ctx) 100 | ``` 101 | 102 | - 作为服务器监听 103 | 104 | ``` 105 | int modbus_tcp_listen(modbus_t * ctx, int nb_connection) 106 | 107 | int modbus_tcp_accept(modbus_t * ctx, int * s) 108 | ``` 109 | 110 | ### 3.3、示例 111 | MODBUS-RTU和MODBUS-TCP使用示例在 [/examples](/examples) 下,使用方法与原生libmodbus一致。 112 | 113 | ## 4、注意事项 114 | 115 | 在使用RTU-RS485模式时,先设置引脚模式,再设置RS485模式,再设置控制引脚 116 | ``` 117 | rt_pin_mode(MAX3491_RE, PIN_MODE_OUTPUT); 118 | modbus_t *ctx = RT_NULL; 119 | ctx = modbus_new_rtu("/dev/uart2", 115200, 'N', 8, 1); 120 | modbus_rtu_set_serial_mode(ctx, MODBUS_RTU_RS485); 121 | modbus_rtu_set_rts(ctx, MAX3491_RE, MODBUS_RTU_RTS_UP); 122 | ``` 123 | 其余API和libmodbus官方一致 124 | 125 | ## 5、联系方式 & 感谢 126 | 127 | * 维护:malongwei 128 | * 主页: 129 | * 邮箱:<2544047213@qq.com> -------------------------------------------------------------------------------- /inc/modbus-private.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2010-2012 Stéphane Raimbault 3 | * 4 | * SPDX-License-Identifier: LGPL-2.1+ 5 | */ 6 | 7 | #ifndef MODBUS_PRIVATE_H 8 | #define MODBUS_PRIVATE_H 9 | 10 | # include 11 | # include 12 | 13 | #include 14 | #include 15 | #include 16 | 17 | #include "modbus.h" 18 | 19 | MODBUS_BEGIN_DECLS 20 | 21 | /* It's not really the minimal length (the real one is report slave ID 22 | * in RTU (4 bytes)) but it's a convenient size to use in RTU or TCP 23 | * communications to read many values or write a single one. 24 | * Maximum between : 25 | * - HEADER_LENGTH_TCP (7) + function (1) + address (2) + number (2) 26 | * - HEADER_LENGTH_RTU (1) + function (1) + address (2) + number (2) + CRC (2) 27 | */ 28 | #define _MIN_REQ_LENGTH 12 29 | 30 | #define _REPORT_SLAVE_ID 180 31 | 32 | #define _MODBUS_EXCEPTION_RSP_LENGTH 5 33 | 34 | /* Timeouts in microsecond (0.5 s) */ 35 | #define _RESPONSE_TIMEOUT 500000 36 | #define _BYTE_TIMEOUT 500000 37 | 38 | typedef enum { 39 | _MODBUS_BACKEND_TYPE_RTU=0, 40 | _MODBUS_BACKEND_TYPE_TCP 41 | } modbus_backend_type_t; 42 | 43 | /* 44 | * ---------- Request Indication ---------- 45 | * | Client | ---------------------->| Server | 46 | * ---------- Confirmation Response ---------- 47 | */ 48 | typedef enum { 49 | /* Request message on the server side */ 50 | MSG_INDICATION, 51 | /* Request message on the client side */ 52 | MSG_CONFIRMATION 53 | } msg_type_t; 54 | 55 | /* This structure reduces the number of params in functions and so 56 | * optimizes the speed of execution (~ 37%). */ 57 | typedef struct _sft { 58 | int slave; 59 | int function; 60 | int t_id; 61 | } sft_t; 62 | 63 | typedef struct _modbus_backend { 64 | unsigned int backend_type; 65 | unsigned int header_length; 66 | unsigned int checksum_length; 67 | unsigned int max_adu_length; 68 | int (*set_slave) (modbus_t *ctx, int slave); 69 | int (*build_request_basis) (modbus_t *ctx, int function, int addr, 70 | int nb, uint8_t *req); 71 | int (*build_response_basis) (sft_t *sft, uint8_t *rsp); 72 | int (*prepare_response_tid) (const uint8_t *req, int *req_length); 73 | int (*send_msg_pre) (uint8_t *req, int req_length); 74 | ssize_t (*send) (modbus_t *ctx, const uint8_t *req, int req_length); 75 | int (*receive) (modbus_t *ctx, uint8_t *req); 76 | ssize_t (*recv) (modbus_t *ctx, uint8_t *rsp, int rsp_length); 77 | int (*check_integrity) (modbus_t *ctx, uint8_t *msg, 78 | const int msg_length); 79 | int (*pre_check_confirmation) (modbus_t *ctx, const uint8_t *req, 80 | const uint8_t *rsp, int rsp_length); 81 | int (*connect) (modbus_t *ctx); 82 | void (*close) (modbus_t *ctx); 83 | int (*flush) (modbus_t *ctx); 84 | int (*select) (modbus_t *ctx, fd_set *rset, struct timeval *tv, int msg_length); 85 | void (*free) (modbus_t *ctx); 86 | } modbus_backend_t; 87 | 88 | struct _modbus { 89 | /* Slave address */ 90 | int slave; 91 | /* Socket or file descriptor */ 92 | int s; 93 | int debug; 94 | int error_recovery; 95 | struct timeval response_timeout; 96 | struct timeval byte_timeout; 97 | const modbus_backend_t *backend; 98 | void *backend_data; 99 | }; 100 | 101 | void _modbus_init_common(modbus_t *ctx); 102 | void _error_print(modbus_t *ctx, const char *context); 103 | int _modbus_receive_msg(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type); 104 | 105 | #ifndef HAVE_STRLCPY 106 | size_t strlcpy(char *dest, const char *src, size_t dest_size); 107 | #endif 108 | 109 | MODBUS_END_DECLS 110 | 111 | #endif /* MODBUS_PRIVATE_H */ 112 | -------------------------------------------------------------------------------- /examples/modbus_tcp_test.c: -------------------------------------------------------------------------------- 1 | #include "modbus_tcp_test.h" 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | // static void test_thread(void *param) 11 | // { 12 | // uint16_t tab_reg[64] = {0}; 13 | // modbus_t *ctx = RT_NULL; 14 | 15 | // ctx = modbus_new_tcp("192.168.1.103", 601, AF_INET); 16 | // modbus_set_slave(ctx, 3); 17 | // modbus_set_response_timeout(ctx, 0, 1000000); 18 | // _mbtcp_start: 19 | // if(modbus_connect(ctx) < 0) 20 | // goto _mbtcp_restart; 21 | 22 | // int num = 0; 23 | // while (1) 24 | // { 25 | // memset(tab_reg, 0, 64 * 2); 26 | // int regs = modbus_read_registers(ctx, 0, 20, tab_reg); 27 | // if(regs < 0) 28 | // goto _mbtcp_restart; 29 | // printf("-------------------------------------------\n"); 30 | // printf("[%4d][read num = %d]", num, regs); 31 | // num++; 32 | // int i; 33 | // for (i = 0; i < 20; i++) 34 | // { 35 | // printf("<%#x>", tab_reg[i]); 36 | // } 37 | // printf("\n"); 38 | // printf("-------------------------------------------\n"); 39 | // rt_thread_mdelay(1000); 40 | // } 41 | 42 | // _mbtcp_restart: 43 | // //7-关闭modbus端口 44 | // modbus_close(ctx); 45 | // rt_thread_mdelay(2000); 46 | // goto _mbtcp_start; 47 | 48 | // //8-释放modbus资源 49 | // modbus_free(ctx); 50 | // } 51 | 52 | #define MAX_CLIENT_NUM 3 53 | #define CLIENT_TIMEOUT 10 //单位 s 54 | 55 | typedef struct 56 | { 57 | int fd; 58 | rt_tick_t tick_timeout; 59 | }client_session_t; 60 | 61 | static void test_thread(void *param) 62 | { 63 | int server_fd = -1; 64 | modbus_t *ctx = NULL; 65 | modbus_mapping_t *mb_mapping = NULL; 66 | client_session_t client_session[MAX_CLIENT_NUM]; 67 | 68 | for (int i = 0; i < MAX_CLIENT_NUM; i++) 69 | { 70 | client_session[i].fd = -1; 71 | client_session[i].tick_timeout = rt_tick_get() + rt_tick_from_millisecond(CLIENT_TIMEOUT * 1000); 72 | } 73 | 74 | int max_fd = -1; 75 | fd_set readset; 76 | int rc; 77 | struct timeval select_timeout; 78 | select_timeout.tv_sec = 1; 79 | select_timeout.tv_usec = 0; 80 | 81 | ctx = modbus_new_tcp(RT_NULL, 1502, AF_INET); 82 | RT_ASSERT(ctx != RT_NULL); 83 | mb_mapping = modbus_mapping_new(MODBUS_MAX_READ_BITS, 0, 84 | MODBUS_MAX_READ_REGISTERS, 0); 85 | RT_ASSERT(mb_mapping != RT_NULL); 86 | 87 | _mbtcp_start: 88 | server_fd = modbus_tcp_listen(ctx, 1); 89 | if (server_fd < 0) 90 | goto _mbtcp_restart; 91 | 92 | while (1) 93 | { 94 | max_fd = -1; 95 | FD_ZERO(&readset); 96 | FD_SET(server_fd, &readset); 97 | 98 | if(max_fd < server_fd) 99 | max_fd = server_fd; 100 | 101 | for (int i = 0; i < MAX_CLIENT_NUM; i++) 102 | { 103 | if(client_session[i].fd >= 0) 104 | { 105 | FD_SET(client_session[i].fd, &readset); 106 | if(max_fd < client_session[i].fd) 107 | max_fd = client_session[i].fd; 108 | } 109 | } 110 | 111 | rc = select(max_fd + 1, &readset, RT_NULL, RT_NULL, &select_timeout); 112 | if(rc < 0) 113 | { 114 | goto _mbtcp_restart; 115 | } 116 | else if(rc > 0) 117 | { 118 | if(FD_ISSET(server_fd, &readset)) 119 | { 120 | int client_sock_fd = modbus_tcp_accept(ctx, &server_fd); 121 | if(client_sock_fd >= 0) 122 | { 123 | int index = -1; 124 | for (int i = 0; i < MAX_CLIENT_NUM; i++) 125 | { 126 | if(client_session[i].fd < 0) 127 | { 128 | index = i; 129 | break; 130 | } 131 | } 132 | if(index >= 0) 133 | { 134 | client_session[index].fd = client_sock_fd; 135 | client_session[index].tick_timeout = rt_tick_get() + rt_tick_from_millisecond(CLIENT_TIMEOUT * 1000); 136 | } 137 | else 138 | { 139 | close(client_sock_fd); 140 | } 141 | } 142 | } 143 | 144 | for (int i = 0; i < MAX_CLIENT_NUM; i++) 145 | { 146 | if(client_session[i].fd >= 0) 147 | { 148 | if(FD_ISSET(client_session[i].fd, &readset)) 149 | { 150 | uint8_t query[MODBUS_TCP_MAX_ADU_LENGTH]; 151 | modbus_set_socket(ctx, client_session[i].fd); 152 | 153 | rc = modbus_receive(ctx, query); 154 | if (rc > 0) 155 | { 156 | rc = modbus_reply(ctx, query, rc, mb_mapping); 157 | if(rc < 0) 158 | { 159 | close(client_session[i].fd); 160 | client_session[i].fd = -1; 161 | } 162 | else 163 | { 164 | client_session[i].tick_timeout = rt_tick_get() + rt_tick_from_millisecond(CLIENT_TIMEOUT * 1000); 165 | } 166 | } 167 | else 168 | { 169 | close(client_session[i].fd); 170 | client_session[i].fd = -1; 171 | } 172 | } 173 | } 174 | } 175 | } 176 | 177 | // 客户端超时未收到数据断开 178 | for(int i =0;i= 0) 181 | { 182 | //超时 183 | if((rt_tick_get() - client_session[i].tick_timeout) < (RT_TICK_MAX / 2)) 184 | { 185 | close(client_session[i].fd); 186 | client_session[i].fd = -1; 187 | } 188 | } 189 | } 190 | } 191 | 192 | _mbtcp_restart: 193 | if(server_fd >= 0) 194 | { 195 | close(server_fd); 196 | server_fd = -1; 197 | } 198 | 199 | for(int i =0;i= 0) 202 | { 203 | close(client_session[i].fd); 204 | client_session[i].fd = -1; 205 | } 206 | } 207 | 208 | rt_thread_mdelay(5000); 209 | goto _mbtcp_start; 210 | 211 | modbus_free(ctx); 212 | } 213 | 214 | static int tcp_test_init(void) 215 | { 216 | rt_thread_t tid; 217 | tid = rt_thread_create("mbtcp_test", 218 | test_thread, RT_NULL, 219 | 2048, 220 | 12, 10); 221 | if (tid != RT_NULL) 222 | rt_thread_startup(tid); 223 | return RT_EOK; 224 | } 225 | INIT_APP_EXPORT(tcp_test_init); 226 | -------------------------------------------------------------------------------- /src/modbus-data.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2010-2014 Stéphane Raimbault 3 | * 4 | * SPDX-License-Identifier: LGPL-2.1+ 5 | */ 6 | 7 | #include 8 | 9 | #ifndef _MSC_VER 10 | # include 11 | #else 12 | # include "stdint.h" 13 | #endif 14 | 15 | #include 16 | 17 | #include 18 | #include 19 | 20 | #include "modbus.h" 21 | 22 | 23 | static inline uint16_t bswap_16(uint16_t x) 24 | { 25 | return (x >> 8) | (x << 8); 26 | } 27 | 28 | static inline uint32_t bswap_32(uint32_t x) 29 | { 30 | return (bswap_16(x & 0xffff) << 16) | (bswap_16(x >> 16)); 31 | } 32 | 33 | #define modbus_ntohl(x) (x) 34 | #define modbus_htonl(x) (x) 35 | /* Sets many bits from a single byte value (all 8 bits of the byte value are 36 | set) */ 37 | void modbus_set_bits_from_byte(uint8_t *dest, int idx, const uint8_t value) 38 | { 39 | int i; 40 | 41 | for (i=0; i < 8; i++) { 42 | dest[idx+i] = (value & (1 << i)) ? 1 : 0; 43 | } 44 | } 45 | 46 | /* Sets many bits from a table of bytes (only the bits between idx and 47 | idx + nb_bits are set) */ 48 | void modbus_set_bits_from_bytes(uint8_t *dest, int idx, unsigned int nb_bits, 49 | const uint8_t *tab_byte) 50 | { 51 | unsigned int i; 52 | int shift = 0; 53 | 54 | for (i = idx; i < idx + nb_bits; i++) { 55 | dest[i] = tab_byte[(i - idx) / 8] & (1 << shift) ? 1 : 0; 56 | /* gcc doesn't like: shift = (++shift) % 8; */ 57 | shift++; 58 | shift %= 8; 59 | } 60 | } 61 | 62 | /* Gets the byte value from many bits. 63 | To obtain a full byte, set nb_bits to 8. */ 64 | uint8_t modbus_get_byte_from_bits(const uint8_t *src, int idx, 65 | unsigned int nb_bits) 66 | { 67 | unsigned int i; 68 | uint8_t value = 0; 69 | 70 | if (nb_bits > 8) { 71 | /* Assert is ignored if NDEBUG is set */ 72 | RT_ASSERT(nb_bits < 8); 73 | nb_bits = 8; 74 | } 75 | 76 | for (i=0; i < nb_bits; i++) { 77 | value |= (src[idx+i] << i); 78 | } 79 | 80 | return value; 81 | } 82 | 83 | /* Get a float from 4 bytes (Modbus) without any conversion (ABCD) */ 84 | float modbus_get_float_abcd(const uint16_t *src) 85 | { 86 | float f; 87 | uint32_t i; 88 | 89 | i = modbus_ntohl(((uint32_t)src[0] << 16) + src[1]); 90 | memcpy(&f, &i, sizeof(float)); 91 | 92 | return f; 93 | } 94 | 95 | /* Get a long from 4 bytes (Modbus) without any conversion (ABCD) */ 96 | long modbus_get_long_abcd(const uint16_t *src) 97 | { 98 | long l; 99 | uint32_t i; 100 | 101 | i = modbus_ntohl(((uint32_t)src[0] << 16) + src[1]); 102 | memcpy(&l, &i, sizeof(long)); 103 | 104 | return l; 105 | } 106 | 107 | /* Get a float from 4 bytes (Modbus) in inversed format (DCBA) */ 108 | float modbus_get_float_dcba(const uint16_t *src) 109 | { 110 | float f; 111 | uint32_t i; 112 | 113 | i = modbus_ntohl(bswap_32((((uint32_t)src[0]) << 16) + src[1])); 114 | memcpy(&f, &i, sizeof(float)); 115 | 116 | return f; 117 | } 118 | 119 | /* Get a long from 4 bytes (Modbus) in inversed format (DCBA) */ 120 | long modbus_get_long_dcba(const uint16_t *src) 121 | { 122 | long l; 123 | uint32_t i; 124 | 125 | i = modbus_ntohl(bswap_32((((uint32_t)src[0]) << 16) + src[1])); 126 | memcpy(&l, &i, sizeof(long)); 127 | 128 | return l; 129 | } 130 | 131 | /* Get a float from 4 bytes (Modbus) with swapped bytes (BADC) */ 132 | float modbus_get_float_badc(const uint16_t *src) 133 | { 134 | float f; 135 | uint32_t i; 136 | 137 | i = modbus_ntohl((uint32_t)(bswap_16(src[0]) << 16) + bswap_16(src[1])); 138 | memcpy(&f, &i, sizeof(float)); 139 | 140 | return f; 141 | } 142 | 143 | /* Get a long from 4 bytes (Modbus) with swapped bytes (BADC) */ 144 | long modbus_get_long_badc(const uint16_t *src) 145 | { 146 | long l; 147 | uint32_t i; 148 | 149 | i = modbus_ntohl((uint32_t)(bswap_16(src[0]) << 16) + bswap_16(src[1])); 150 | memcpy(&l, &i, sizeof(long)); 151 | 152 | return l; 153 | } 154 | 155 | /* Get a float from 4 bytes (Modbus) with swapped words (CDAB) */ 156 | float modbus_get_float_cdab(const uint16_t *src) 157 | { 158 | float f; 159 | uint32_t i; 160 | 161 | i = modbus_ntohl((((uint32_t)src[1]) << 16) + src[0]); 162 | memcpy(&f, &i, sizeof(float)); 163 | 164 | return f; 165 | } 166 | 167 | /* Get a long from 4 bytes (Modbus) with swapped words (CDAB) */ 168 | long modbus_get_long_cdab(const uint16_t *src) 169 | { 170 | long l; 171 | uint32_t i; 172 | 173 | i = modbus_ntohl((((uint32_t)src[1]) << 16) + src[0]); 174 | memcpy(&l, &i, sizeof(long)); 175 | 176 | return l; 177 | } 178 | 179 | /* DEPRECATED - Get a float from 4 bytes in sort of Modbus format */ 180 | float modbus_get_float(const uint16_t *src) 181 | { 182 | float f; 183 | uint32_t i; 184 | 185 | i = (((uint32_t)src[1]) << 16) + src[0]; 186 | memcpy(&f, &i, sizeof(float)); 187 | 188 | return f; 189 | } 190 | 191 | 192 | /* Set a float to 4 bytes for Modbus w/o any conversion (ABCD) */ 193 | void modbus_set_float_abcd(float f, uint16_t *dest) 194 | { 195 | uint32_t i; 196 | 197 | memcpy(&i, &f, sizeof(uint32_t)); 198 | i = modbus_htonl(i); 199 | dest[0] = (uint16_t)(i >> 16); 200 | dest[1] = (uint16_t)i; 201 | } 202 | 203 | /* Set a long to 4 bytes for Modbus w/o any conversion (ABCD) */ 204 | void modbus_set_long_abcd(long l, uint16_t *dest) 205 | { 206 | uint32_t i; 207 | 208 | memcpy(&i, &l, sizeof(uint32_t)); 209 | i = modbus_htonl(i); 210 | dest[0] = (uint16_t)(i >> 16); 211 | dest[1] = (uint16_t)i; 212 | } 213 | 214 | /* Set a float to 4 bytes for Modbus with byte and word swap conversion (DCBA) */ 215 | void modbus_set_float_dcba(float f, uint16_t *dest) 216 | { 217 | uint32_t i; 218 | 219 | memcpy(&i, &f, sizeof(uint32_t)); 220 | i = bswap_32(modbus_htonl(i)); 221 | dest[0] = (uint16_t)(i >> 16); 222 | dest[1] = (uint16_t)i; 223 | } 224 | 225 | /* Set a long to 4 bytes for Modbus with byte and word swap conversion (DCBA) */ 226 | void modbus_set_long_dcba(long l, uint16_t *dest) 227 | { 228 | uint32_t i; 229 | 230 | memcpy(&i, &l, sizeof(uint32_t)); 231 | i = bswap_32(modbus_htonl(i)); 232 | dest[0] = (uint16_t)(i >> 16); 233 | dest[1] = (uint16_t)i; 234 | } 235 | 236 | /* Set a float to 4 bytes for Modbus with byte swap conversion (BADC) */ 237 | void modbus_set_float_badc(float f, uint16_t *dest) 238 | { 239 | uint32_t i; 240 | 241 | memcpy(&i, &f, sizeof(uint32_t)); 242 | i = modbus_htonl(i); 243 | dest[0] = (uint16_t)bswap_16(i >> 16); 244 | dest[1] = (uint16_t)bswap_16(i & 0xFFFF); 245 | } 246 | 247 | /* Set a long to 4 bytes for Modbus with byte swap conversion (BADC) */ 248 | void modbus_set_long_badc(long l, uint16_t *dest) 249 | { 250 | uint32_t i; 251 | 252 | memcpy(&i, &l, sizeof(uint32_t)); 253 | i = modbus_htonl(i); 254 | dest[0] = (uint16_t)bswap_16(i >> 16); 255 | dest[1] = (uint16_t)bswap_16(i & 0xFFFF); 256 | } 257 | 258 | /* Set a float to 4 bytes for Modbus with word swap conversion (CDAB) */ 259 | void modbus_set_float_cdab(float f, uint16_t *dest) 260 | { 261 | uint32_t i; 262 | 263 | memcpy(&i, &f, sizeof(uint32_t)); 264 | i = modbus_htonl(i); 265 | dest[0] = (uint16_t)i; 266 | dest[1] = (uint16_t)(i >> 16); 267 | } 268 | 269 | /* Set a long to 4 bytes for Modbus with word swap conversion (CDAB) */ 270 | void modbus_set_long_cdab(long l, uint16_t *dest) 271 | { 272 | uint32_t i; 273 | 274 | memcpy(&i, &l, sizeof(uint32_t)); 275 | i = modbus_htonl(i); 276 | dest[0] = (uint16_t)i; 277 | dest[1] = (uint16_t)(i >> 16); 278 | } 279 | 280 | /* DEPRECATED - Set a float to 4 bytes in a sort of Modbus format! */ 281 | void modbus_set_float(float f, uint16_t *dest) 282 | { 283 | uint32_t i; 284 | 285 | memcpy(&i, &f, sizeof(uint32_t)); 286 | dest[0] = (uint16_t)i; 287 | dest[1] = (uint16_t)(i >> 16); 288 | } 289 | -------------------------------------------------------------------------------- /inc/modbus.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2001-2013 Stéphane Raimbault 3 | * 4 | * SPDX-License-Identifier: LGPL-2.1+ 5 | */ 6 | 7 | #ifndef MODBUS_H 8 | #define MODBUS_H 9 | 10 | /* Add this for macros that defined unix flavor */ 11 | #if (defined(__unix__) || defined(unix)) && !defined(USG) 12 | #include 13 | #endif 14 | 15 | #ifndef _MSC_VER 16 | #include 17 | #else 18 | #include "stdint.h" 19 | #endif 20 | 21 | #include "modbus-version.h" 22 | 23 | #if defined(_MSC_VER) 24 | # if defined(DLLBUILD) 25 | /* define DLLBUILD when building the DLL */ 26 | # define MODBUS_API __declspec(dllexport) 27 | # else 28 | # define MODBUS_API __declspec(dllimport) 29 | # endif 30 | #else 31 | # define MODBUS_API 32 | #endif 33 | 34 | #ifdef __cplusplus 35 | # define MODBUS_BEGIN_DECLS extern "C" { 36 | # define MODBUS_END_DECLS } 37 | #else 38 | # define MODBUS_BEGIN_DECLS 39 | # define MODBUS_END_DECLS 40 | #endif 41 | 42 | MODBUS_BEGIN_DECLS 43 | 44 | #ifndef FALSE 45 | #define FALSE 0 46 | #endif 47 | 48 | #ifndef TRUE 49 | #define TRUE 1 50 | #endif 51 | 52 | #ifndef OFF 53 | #define OFF 0 54 | #endif 55 | 56 | #ifndef ON 57 | #define ON 1 58 | #endif 59 | 60 | /* Modbus function codes */ 61 | #define MODBUS_FC_READ_COILS 0x01 62 | #define MODBUS_FC_READ_DISCRETE_INPUTS 0x02 63 | #define MODBUS_FC_READ_HOLDING_REGISTERS 0x03 64 | #define MODBUS_FC_READ_INPUT_REGISTERS 0x04 65 | #define MODBUS_FC_WRITE_SINGLE_COIL 0x05 66 | #define MODBUS_FC_WRITE_SINGLE_REGISTER 0x06 67 | #define MODBUS_FC_READ_EXCEPTION_STATUS 0x07 68 | #define MODBUS_FC_WRITE_MULTIPLE_COILS 0x0F 69 | #define MODBUS_FC_WRITE_MULTIPLE_REGISTERS 0x10 70 | #define MODBUS_FC_REPORT_SLAVE_ID 0x11 71 | #define MODBUS_FC_MASK_WRITE_REGISTER 0x16 72 | #define MODBUS_FC_WRITE_AND_READ_REGISTERS 0x17 73 | 74 | #define MODBUS_BROADCAST_ADDRESS 0 75 | 76 | /* Modbus_Application_Protocol_V1_1b.pdf (chapter 6 section 1 page 12) 77 | * Quantity of Coils to read (2 bytes): 1 to 2000 (0x7D0) 78 | * (chapter 6 section 11 page 29) 79 | * Quantity of Coils to write (2 bytes): 1 to 1968 (0x7B0) 80 | */ 81 | #define MODBUS_MAX_READ_BITS 2000 82 | #define MODBUS_MAX_WRITE_BITS 1968 83 | 84 | /* Modbus_Application_Protocol_V1_1b.pdf (chapter 6 section 3 page 15) 85 | * Quantity of Registers to read (2 bytes): 1 to 125 (0x7D) 86 | * (chapter 6 section 12 page 31) 87 | * Quantity of Registers to write (2 bytes) 1 to 123 (0x7B) 88 | * (chapter 6 section 17 page 38) 89 | * Quantity of Registers to write in R/W registers (2 bytes) 1 to 121 (0x79) 90 | */ 91 | #define MODBUS_MAX_READ_REGISTERS 125 92 | #define MODBUS_MAX_WRITE_REGISTERS 123 93 | #define MODBUS_MAX_WR_WRITE_REGISTERS 121 94 | #define MODBUS_MAX_WR_READ_REGISTERS 125 95 | 96 | /* The size of the MODBUS PDU is limited by the size constraint inherited from 97 | * the first MODBUS implementation on Serial Line network (max. RS485 ADU = 256 98 | * bytes). Therefore, MODBUS PDU for serial line communication = 256 - Server 99 | * address (1 byte) - CRC (2 bytes) = 253 bytes. 100 | */ 101 | #define MODBUS_MAX_PDU_LENGTH 253 102 | 103 | /* Consequently: 104 | * - RTU MODBUS ADU = 253 bytes + Server address (1 byte) + CRC (2 bytes) = 256 105 | * bytes. 106 | * - TCP MODBUS ADU = 253 bytes + MBAP (7 bytes) = 260 bytes. 107 | * so the maximum of both backend in 260 bytes. This size can used to allocate 108 | * an array of bytes to store responses and it will be compatible with the two 109 | * backends. 110 | */ 111 | #define MODBUS_MAX_ADU_LENGTH 260 112 | 113 | /* Random number to avoid errno conflicts */ 114 | #define MODBUS_ENOBASE 112345678 115 | 116 | /* Protocol exceptions */ 117 | enum { 118 | MODBUS_EXCEPTION_ILLEGAL_FUNCTION = 0x01, 119 | MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, 120 | MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, 121 | MODBUS_EXCEPTION_SLAVE_OR_SERVER_FAILURE, 122 | MODBUS_EXCEPTION_ACKNOWLEDGE, 123 | MODBUS_EXCEPTION_SLAVE_OR_SERVER_BUSY, 124 | MODBUS_EXCEPTION_NEGATIVE_ACKNOWLEDGE, 125 | MODBUS_EXCEPTION_MEMORY_PARITY, 126 | MODBUS_EXCEPTION_NOT_DEFINED, 127 | MODBUS_EXCEPTION_GATEWAY_PATH, 128 | MODBUS_EXCEPTION_GATEWAY_TARGET, 129 | MODBUS_EXCEPTION_MAX 130 | }; 131 | 132 | #define EMBXILFUN (MODBUS_ENOBASE + MODBUS_EXCEPTION_ILLEGAL_FUNCTION) 133 | #define EMBXILADD (MODBUS_ENOBASE + MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS) 134 | #define EMBXILVAL (MODBUS_ENOBASE + MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE) 135 | #define EMBXSFAIL (MODBUS_ENOBASE + MODBUS_EXCEPTION_SLAVE_OR_SERVER_FAILURE) 136 | #define EMBXACK (MODBUS_ENOBASE + MODBUS_EXCEPTION_ACKNOWLEDGE) 137 | #define EMBXSBUSY (MODBUS_ENOBASE + MODBUS_EXCEPTION_SLAVE_OR_SERVER_BUSY) 138 | #define EMBXNACK (MODBUS_ENOBASE + MODBUS_EXCEPTION_NEGATIVE_ACKNOWLEDGE) 139 | #define EMBXMEMPAR (MODBUS_ENOBASE + MODBUS_EXCEPTION_MEMORY_PARITY) 140 | #define EMBXGPATH (MODBUS_ENOBASE + MODBUS_EXCEPTION_GATEWAY_PATH) 141 | #define EMBXGTAR (MODBUS_ENOBASE + MODBUS_EXCEPTION_GATEWAY_TARGET) 142 | 143 | /* Native libmodbus error codes */ 144 | #define EMBBADCRC (EMBXGTAR + 1) 145 | #define EMBBADDATA (EMBXGTAR + 2) 146 | #define EMBBADEXC (EMBXGTAR + 3) 147 | #define EMBUNKEXC (EMBXGTAR + 4) 148 | #define EMBMDATA (EMBXGTAR + 5) 149 | #define EMBBADSLAVE (EMBXGTAR + 6) 150 | 151 | extern const unsigned int libmodbus_version_major; 152 | extern const unsigned int libmodbus_version_minor; 153 | extern const unsigned int libmodbus_version_micro; 154 | 155 | typedef struct _modbus modbus_t; 156 | 157 | typedef struct { 158 | int nb_bits; 159 | int start_bits; 160 | int nb_input_bits; 161 | int start_input_bits; 162 | int nb_input_registers; 163 | int start_input_registers; 164 | int nb_registers; 165 | int start_registers; 166 | uint8_t *tab_bits; 167 | uint8_t *tab_input_bits; 168 | uint16_t *tab_input_registers; 169 | uint16_t *tab_registers; 170 | } modbus_mapping_t; 171 | 172 | typedef enum 173 | { 174 | MODBUS_ERROR_RECOVERY_NONE = 0, 175 | MODBUS_ERROR_RECOVERY_LINK = (1<<1), 176 | MODBUS_ERROR_RECOVERY_PROTOCOL = (1<<2) 177 | } modbus_error_recovery_mode; 178 | 179 | MODBUS_API int modbus_set_slave(modbus_t* ctx, int slave); 180 | MODBUS_API int modbus_set_error_recovery(modbus_t *ctx, modbus_error_recovery_mode error_recovery); 181 | MODBUS_API int modbus_set_socket(modbus_t *ctx, int s); 182 | MODBUS_API int modbus_get_socket(modbus_t *ctx); 183 | 184 | MODBUS_API int modbus_get_response_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec); 185 | MODBUS_API int modbus_set_response_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec); 186 | 187 | MODBUS_API int modbus_get_byte_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec); 188 | MODBUS_API int modbus_set_byte_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec); 189 | 190 | MODBUS_API int modbus_get_header_length(modbus_t *ctx); 191 | 192 | MODBUS_API int modbus_connect(modbus_t *ctx); 193 | MODBUS_API void modbus_close(modbus_t *ctx); 194 | 195 | MODBUS_API void modbus_free(modbus_t *ctx); 196 | 197 | MODBUS_API int modbus_flush(modbus_t *ctx); 198 | MODBUS_API int modbus_set_debug(modbus_t *ctx, int flag); 199 | 200 | MODBUS_API const char *modbus_strerror(int errnum); 201 | 202 | MODBUS_API int modbus_read_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest); 203 | MODBUS_API int modbus_read_input_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest); 204 | MODBUS_API int modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest); 205 | MODBUS_API int modbus_read_input_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest); 206 | MODBUS_API int modbus_write_bit(modbus_t *ctx, int coil_addr, int status); 207 | MODBUS_API int modbus_write_register(modbus_t *ctx, int reg_addr, int value); 208 | MODBUS_API int modbus_write_bits(modbus_t *ctx, int addr, int nb, const uint8_t *data); 209 | MODBUS_API int modbus_write_registers(modbus_t *ctx, int addr, int nb, const uint16_t *data); 210 | MODBUS_API int modbus_mask_write_register(modbus_t *ctx, int addr, uint16_t and_mask, uint16_t or_mask); 211 | MODBUS_API int modbus_write_and_read_registers(modbus_t *ctx, int write_addr, int write_nb, 212 | const uint16_t *src, int read_addr, int read_nb, 213 | uint16_t *dest); 214 | MODBUS_API int modbus_report_slave_id(modbus_t *ctx, int max_dest, uint8_t *dest); 215 | 216 | MODBUS_API modbus_mapping_t* modbus_mapping_new_start_address( 217 | unsigned int start_bits, unsigned int nb_bits, 218 | unsigned int start_input_bits, unsigned int nb_input_bits, 219 | unsigned int start_registers, unsigned int nb_registers, 220 | unsigned int start_input_registers, unsigned int nb_input_registers); 221 | 222 | MODBUS_API modbus_mapping_t* modbus_mapping_new(int nb_bits, int nb_input_bits, 223 | int nb_registers, int nb_input_registers); 224 | MODBUS_API void modbus_mapping_free(modbus_mapping_t *mb_mapping); 225 | 226 | MODBUS_API int modbus_send_raw_request(modbus_t *ctx, uint8_t *raw_req, int raw_req_length); 227 | 228 | MODBUS_API int modbus_receive(modbus_t *ctx, uint8_t *req); 229 | 230 | MODBUS_API int modbus_receive_confirmation(modbus_t *ctx, uint8_t *rsp); 231 | 232 | MODBUS_API int modbus_reply(modbus_t *ctx, const uint8_t *req, 233 | int req_length, modbus_mapping_t *mb_mapping); 234 | MODBUS_API int modbus_reply_exception(modbus_t *ctx, const uint8_t *req, 235 | unsigned int exception_code); 236 | 237 | /** 238 | * UTILS FUNCTIONS 239 | **/ 240 | 241 | #define MODBUS_GET_HIGH_BYTE(data) (((data) >> 8) & 0xFF) 242 | #define MODBUS_GET_LOW_BYTE(data) ((data) & 0xFF) 243 | #define MODBUS_GET_INT64_FROM_INT16(tab_int16, index) \ 244 | (((int64_t)tab_int16[(index) ] << 48) + \ 245 | ((int64_t)tab_int16[(index) + 1] << 32) + \ 246 | ((int64_t)tab_int16[(index) + 2] << 16) + \ 247 | (int64_t)tab_int16[(index) + 3]) 248 | #define MODBUS_GET_INT32_FROM_INT16(tab_int16, index) ((tab_int16[(index)] << 16) + tab_int16[(index) + 1]) 249 | #define MODBUS_GET_INT16_FROM_INT8(tab_int8, index) ((tab_int8[(index)] << 8) + tab_int8[(index) + 1]) 250 | #define MODBUS_SET_INT16_TO_INT8(tab_int8, index, value) \ 251 | do { \ 252 | tab_int8[(index)] = (value) >> 8; \ 253 | tab_int8[(index) + 1] = (value) & 0xFF; \ 254 | } while (0) 255 | #define MODBUS_SET_INT32_TO_INT16(tab_int16, index, value) \ 256 | do { \ 257 | tab_int16[(index) ] = (value) >> 16; \ 258 | tab_int16[(index) + 1] = (value); \ 259 | } while (0) 260 | #define MODBUS_SET_INT64_TO_INT16(tab_int16, index, value) \ 261 | do { \ 262 | tab_int16[(index) ] = (value) >> 48; \ 263 | tab_int16[(index) + 1] = (value) >> 32; \ 264 | tab_int16[(index) + 2] = (value) >> 16; \ 265 | tab_int16[(index) + 3] = (value); \ 266 | } while (0) 267 | 268 | MODBUS_API void modbus_set_bits_from_byte(uint8_t *dest, int idx, const uint8_t value); 269 | MODBUS_API void modbus_set_bits_from_bytes(uint8_t *dest, int idx, unsigned int nb_bits, 270 | const uint8_t *tab_byte); 271 | MODBUS_API uint8_t modbus_get_byte_from_bits(const uint8_t *src, int idx, unsigned int nb_bits); 272 | MODBUS_API float modbus_get_float(const uint16_t *src); 273 | MODBUS_API float modbus_get_float_abcd(const uint16_t *src); 274 | MODBUS_API float modbus_get_float_dcba(const uint16_t *src); 275 | MODBUS_API float modbus_get_float_badc(const uint16_t *src); 276 | MODBUS_API float modbus_get_float_cdab(const uint16_t *src); 277 | 278 | MODBUS_API long modbus_get_long_abcd(const uint16_t *src); 279 | MODBUS_API long modbus_get_long_dcba(const uint16_t *src); 280 | MODBUS_API long modbus_get_long_badc(const uint16_t *src); 281 | MODBUS_API long modbus_get_long_cdab(const uint16_t *src); 282 | 283 | MODBUS_API void modbus_set_float(float f, uint16_t *dest); 284 | MODBUS_API void modbus_set_float_abcd(float f, uint16_t *dest); 285 | MODBUS_API void modbus_set_float_dcba(float f, uint16_t *dest); 286 | MODBUS_API void modbus_set_float_badc(float f, uint16_t *dest); 287 | MODBUS_API void modbus_set_float_cdab(float f, uint16_t *dest); 288 | 289 | MODBUS_API void modbus_set_long_abcd(long l, uint16_t *dest); 290 | MODBUS_API void modbus_set_long_dcba(long l, uint16_t *dest); 291 | MODBUS_API void modbus_set_long_badc(long l, uint16_t *dest); 292 | MODBUS_API void modbus_set_long_cdab(long l, uint16_t *dest); 293 | 294 | #include "modbus-tcp.h" 295 | #include "modbus-rtu.h" 296 | 297 | MODBUS_END_DECLS 298 | 299 | #endif /* MODBUS_H */ 300 | -------------------------------------------------------------------------------- /src/modbus-tcp.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2001-2013 Stéphane Raimbault 3 | * 4 | * SPDX-License-Identifier: LGPL-2.1+ 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #ifndef _MSC_VER 12 | #include 13 | #endif 14 | 15 | #include 16 | 17 | #if defined(_WIN32) 18 | # define OS_WIN32 19 | /* ws2_32.dll has getaddrinfo and freeaddrinfo on Windows XP and later. 20 | * minwg32 headers check WINVER before allowing the use of these */ 21 | # ifndef WINVER 22 | # define WINVER 0x0501 23 | # endif 24 | /* Already set in modbus-tcp.h but it seems order matters in VS2005 */ 25 | # include 26 | # include 27 | # define SHUT_RDWR 2 28 | # define close closesocket 29 | #else 30 | # include 31 | 32 | 33 | #if defined(__OpenBSD__) || (defined(__FreeBSD__) && __FreeBSD__ < 5) 34 | # define OS_BSD 35 | # include 36 | #endif 37 | 38 | # include 39 | # include 40 | # include 41 | # include 42 | #endif 43 | 44 | #if !defined(MSG_NOSIGNAL) 45 | #define MSG_NOSIGNAL 0 46 | #endif 47 | 48 | #if defined(_AIX) && !defined(MSG_DONTWAIT) 49 | #define MSG_DONTWAIT MSG_NONBLOCK 50 | #endif 51 | 52 | #include 53 | #include 54 | #include 55 | 56 | #include "modbus-private.h" 57 | 58 | #include "modbus-tcp.h" 59 | #include "modbus-tcp-private.h" 60 | 61 | #ifdef OS_WIN32 62 | static int _modbus_tcp_init_win32(void) 63 | { 64 | /* Initialise Windows Socket API */ 65 | WSADATA wsaData; 66 | 67 | if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { 68 | fprintf(stderr, "WSAStartup() returned error code %d\n", 69 | (unsigned int)GetLastError()); 70 | errno = EIO; 71 | return -1; 72 | } 73 | return 0; 74 | } 75 | #endif 76 | 77 | static int _modbus_set_slave(modbus_t *ctx, int slave) 78 | { 79 | /* Broadcast address is 0 (MODBUS_BROADCAST_ADDRESS) */ 80 | if (slave >= 0 && slave <= 247) { 81 | ctx->slave = slave; 82 | } else if (slave == MODBUS_TCP_SLAVE) { 83 | /* The special value MODBUS_TCP_SLAVE (0xFF) can be used in TCP mode to 84 | * restore the default value. */ 85 | ctx->slave = slave; 86 | } else { 87 | errno = EINVAL; 88 | return -1; 89 | } 90 | 91 | return 0; 92 | } 93 | 94 | /* Builds a TCP request header */ 95 | static int _modbus_tcp_build_request_basis(modbus_t *ctx, int function, 96 | int addr, int nb, 97 | uint8_t *req) 98 | { 99 | modbus_tcp_t *ctx_tcp = ctx->backend_data; 100 | 101 | /* Increase transaction ID */ 102 | if (ctx_tcp->t_id < UINT16_MAX) 103 | ctx_tcp->t_id++; 104 | else 105 | ctx_tcp->t_id = 0; 106 | req[0] = ctx_tcp->t_id >> 8; 107 | req[1] = ctx_tcp->t_id & 0x00ff; 108 | 109 | /* Protocol Modbus */ 110 | req[2] = 0; 111 | req[3] = 0; 112 | 113 | /* Length will be defined later by set_req_length_tcp at offsets 4 114 | and 5 */ 115 | 116 | req[6] = ctx->slave; 117 | req[7] = function; 118 | req[8] = addr >> 8; 119 | req[9] = addr & 0x00ff; 120 | req[10] = nb >> 8; 121 | req[11] = nb & 0x00ff; 122 | 123 | return _MODBUS_TCP_PRESET_REQ_LENGTH; 124 | } 125 | 126 | /* Builds a TCP response header */ 127 | static int _modbus_tcp_build_response_basis(sft_t *sft, uint8_t *rsp) 128 | { 129 | /* Extract from MODBUS Messaging on TCP/IP Implementation 130 | Guide V1.0b (page 23/46): 131 | The transaction identifier is used to associate the future 132 | response with the request. */ 133 | rsp[0] = sft->t_id >> 8; 134 | rsp[1] = sft->t_id & 0x00ff; 135 | 136 | /* Protocol Modbus */ 137 | rsp[2] = 0; 138 | rsp[3] = 0; 139 | 140 | /* Length will be set later by send_msg (4 and 5) */ 141 | 142 | /* The slave ID is copied from the indication */ 143 | rsp[6] = sft->slave; 144 | rsp[7] = sft->function; 145 | 146 | return _MODBUS_TCP_PRESET_RSP_LENGTH; 147 | } 148 | 149 | 150 | static int _modbus_tcp_prepare_response_tid(const uint8_t *req, int *req_length) 151 | { 152 | return (req[0] << 8) + req[1]; 153 | } 154 | 155 | static int _modbus_tcp_send_msg_pre(uint8_t *req, int req_length) 156 | { 157 | /* Substract the header length to the message length */ 158 | int mbap_length = req_length - 6; 159 | 160 | req[4] = mbap_length >> 8; 161 | req[5] = mbap_length & 0x00FF; 162 | 163 | return req_length; 164 | } 165 | 166 | static ssize_t _modbus_tcp_send(modbus_t *ctx, const uint8_t *req, int req_length) 167 | { 168 | /* MSG_NOSIGNAL 169 | Requests not to send SIGPIPE on errors on stream oriented 170 | sockets when the other end breaks the connection. The EPIPE 171 | error is still returned. */ 172 | return send(ctx->s, (const char *)req, req_length, MSG_NOSIGNAL); 173 | } 174 | 175 | static int _modbus_tcp_receive(modbus_t *ctx, uint8_t *req) { 176 | return _modbus_receive_msg(ctx, req, MSG_INDICATION); 177 | } 178 | 179 | static ssize_t _modbus_tcp_recv(modbus_t *ctx, uint8_t *rsp, int rsp_length) { 180 | return recv(ctx->s, (char *)rsp, rsp_length, 0); 181 | } 182 | 183 | static int _modbus_tcp_check_integrity(modbus_t *ctx, uint8_t *msg, const int msg_length) 184 | { 185 | return msg_length; 186 | } 187 | 188 | static int _modbus_tcp_pre_check_confirmation(modbus_t *ctx, const uint8_t *req, 189 | const uint8_t *rsp, int rsp_length) 190 | { 191 | /* Check transaction ID */ 192 | if (req[0] != rsp[0] || req[1] != rsp[1]) { 193 | if (ctx->debug) { 194 | fprintf(stderr, "Invalid transaction ID received 0x%X (not 0x%X)\n", 195 | (rsp[0] << 8) + rsp[1], (req[0] << 8) + req[1]); 196 | } 197 | errno = EMBBADDATA; 198 | return -1; 199 | } 200 | 201 | /* Check protocol ID */ 202 | if (rsp[2] != 0x0 && rsp[3] != 0x0) { 203 | if (ctx->debug) { 204 | fprintf(stderr, "Invalid protocol ID received 0x%X (not 0x0)\n", 205 | (rsp[2] << 8) + rsp[3]); 206 | } 207 | errno = EMBBADDATA; 208 | return -1; 209 | } 210 | 211 | return 0; 212 | } 213 | 214 | static int _modbus_tcp_set_ipv4_options(int s) 215 | { 216 | int rc; 217 | int option; 218 | 219 | /* Set the TCP no delay flag */ 220 | /* SOL_TCP = IPPROTO_TCP */ 221 | option = 1; 222 | rc = setsockopt(s, IPPROTO_TCP, TCP_NODELAY, 223 | (const void *)&option, sizeof(int)); 224 | if (rc == -1) { 225 | return -1; 226 | } 227 | 228 | /* If the OS does not offer SOCK_NONBLOCK, fall back to setting FIONBIO to 229 | * make sockets non-blocking */ 230 | /* Do not care about the return value, this is optional */ 231 | #if !defined(SOCK_NONBLOCK) && defined(FIONBIO) 232 | 233 | { 234 | /* Setting FIONBIO expects an unsigned long according to MSDN */ 235 | uint32_t loption = 1; 236 | ioctlsocket(s, FIONBIO, &loption); 237 | } 238 | #endif 239 | 240 | return 0; 241 | } 242 | 243 | static int _connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen, 244 | const struct timeval *ro_tv) 245 | { 246 | int rc = connect(sockfd, addr, addrlen); 247 | 248 | #ifdef OS_WIN32 249 | int wsaError = 0; 250 | if (rc == -1) { 251 | wsaError = WSAGetLastError(); 252 | } 253 | 254 | if (wsaError == WSAEWOULDBLOCK || wsaError == WSAEINPROGRESS) { 255 | #else 256 | if (rc == -1 && errno == EINPROGRESS) { 257 | #endif 258 | fd_set wset; 259 | int optval; 260 | socklen_t optlen = sizeof(optval); 261 | struct timeval tv = *ro_tv; 262 | 263 | /* Wait to be available in writing */ 264 | FD_ZERO(&wset); 265 | FD_SET(sockfd, &wset); 266 | rc = select(sockfd + 1, NULL, &wset, NULL, &tv); 267 | if (rc <= 0) { 268 | /* Timeout or fail */ 269 | return -1; 270 | } 271 | 272 | /* The connection is established if SO_ERROR and optval are set to 0 */ 273 | rc = getsockopt(sockfd, SOL_SOCKET, SO_ERROR, (void *)&optval, &optlen); 274 | if (rc == 0 && optval == 0) { 275 | return 0; 276 | } else { 277 | errno = ECONNREFUSED; 278 | return -1; 279 | } 280 | } 281 | return rc; 282 | } 283 | 284 | /* Establishes a modbus TCP connection with a Modbus server. */ 285 | static int _modbus_tcp_connect(modbus_t *ctx) 286 | { 287 | int rc; 288 | /* Specialized version of sockaddr for Internet socket address (same size) */ 289 | struct sockaddr_in addr; 290 | modbus_tcp_t *ctx_tcp = ctx->backend_data; 291 | int flags = SOCK_STREAM; 292 | 293 | #ifdef OS_WIN32 294 | if (_modbus_tcp_init_win32() == -1) { 295 | return -1; 296 | } 297 | #endif 298 | 299 | #ifdef SOCK_CLOEXEC 300 | flags |= SOCK_CLOEXEC; 301 | #endif 302 | 303 | #ifdef SOCK_NONBLOCK 304 | flags |= SOCK_NONBLOCK; 305 | #endif 306 | 307 | ctx->s = socket(ctx_tcp->domain, flags, 0); 308 | if (ctx->s == -1) { 309 | return -1; 310 | } 311 | 312 | rc = _modbus_tcp_set_ipv4_options(ctx->s); 313 | if (rc == -1) { 314 | close(ctx->s); 315 | ctx->s = -1; 316 | return -1; 317 | } 318 | 319 | if (ctx->debug) { 320 | printf("Connecting to %s:%d\n", ctx_tcp->ip, ctx_tcp->port); 321 | } 322 | 323 | addr.sin_family = ctx_tcp->domain; 324 | addr.sin_port = htons(ctx_tcp->port); 325 | addr.sin_addr.s_addr = inet_addr(ctx_tcp->ip); 326 | rt_memset(&(addr.sin_zero), 0, sizeof(addr.sin_zero)); 327 | rc = _connect(ctx->s, (struct sockaddr *)&addr, sizeof(struct sockaddr), &ctx->response_timeout); 328 | if (rc == -1) { 329 | close(ctx->s); 330 | ctx->s = -1; 331 | return -1; 332 | } 333 | 334 | return 0; 335 | } 336 | 337 | /* Establishes a modbus TCP PI connection with a Modbus server. */ 338 | static int _modbus_tcp_pi_connect(modbus_t *ctx) 339 | { 340 | int rc; 341 | struct addrinfo *ai_list; 342 | struct addrinfo *ai_ptr; 343 | struct addrinfo ai_hints; 344 | modbus_tcp_pi_t *ctx_tcp_pi = ctx->backend_data; 345 | 346 | #ifdef OS_WIN32 347 | if (_modbus_tcp_init_win32() == -1) { 348 | return -1; 349 | } 350 | #endif 351 | 352 | memset(&ai_hints, 0, sizeof(ai_hints)); 353 | #ifdef AI_ADDRCONFIG 354 | ai_hints.ai_flags |= AI_ADDRCONFIG; 355 | #endif 356 | ai_hints.ai_family = AF_UNSPEC; 357 | ai_hints.ai_socktype = SOCK_STREAM; 358 | ai_hints.ai_addr = NULL; 359 | ai_hints.ai_canonname = NULL; 360 | ai_hints.ai_next = NULL; 361 | 362 | ai_list = NULL; 363 | rc = getaddrinfo(ctx_tcp_pi->node, ctx_tcp_pi->service, 364 | &ai_hints, &ai_list); 365 | if (rc != 0) { 366 | if (ctx->debug) { 367 | fprintf(stderr, "Error returned by getaddrinfo: %d\n", rc); 368 | } 369 | errno = ECONNREFUSED; 370 | return -1; 371 | } 372 | 373 | for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) { 374 | int flags = ai_ptr->ai_socktype; 375 | int s; 376 | 377 | #ifdef SOCK_CLOEXEC 378 | flags |= SOCK_CLOEXEC; 379 | #endif 380 | 381 | #ifdef SOCK_NONBLOCK 382 | flags |= SOCK_NONBLOCK; 383 | #endif 384 | 385 | s = socket(ai_ptr->ai_family, flags, ai_ptr->ai_protocol); 386 | if (s < 0) 387 | continue; 388 | 389 | if (ai_ptr->ai_family == AF_INET) 390 | _modbus_tcp_set_ipv4_options(s); 391 | 392 | if (ctx->debug) { 393 | printf("Connecting to [%s]:%s\n", ctx_tcp_pi->node, ctx_tcp_pi->service); 394 | } 395 | 396 | rc = _connect(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen, &ctx->response_timeout); 397 | if (rc == -1) { 398 | close(s); 399 | continue; 400 | } 401 | 402 | ctx->s = s; 403 | break; 404 | } 405 | 406 | freeaddrinfo(ai_list); 407 | 408 | if (ctx->s < 0) { 409 | return -1; 410 | } 411 | 412 | return 0; 413 | } 414 | 415 | /* Closes the network connection and socket in TCP mode */ 416 | static void _modbus_tcp_close(modbus_t *ctx) 417 | { 418 | if (ctx->s != -1) { 419 | close(ctx->s); 420 | ctx->s = -1; 421 | } 422 | } 423 | 424 | static int _modbus_tcp_flush(modbus_t *ctx) 425 | { 426 | int rc; 427 | int rc_sum = 0; 428 | 429 | do { 430 | /* Extract the garbage from the socket */ 431 | char devnull[MODBUS_TCP_MAX_ADU_LENGTH]; 432 | #ifndef OS_WIN32 433 | rc = recv(ctx->s, devnull, MODBUS_TCP_MAX_ADU_LENGTH, MSG_DONTWAIT); 434 | #else 435 | /* On Win32, it's a bit more complicated to not wait */ 436 | fd_set rset; 437 | struct timeval tv; 438 | 439 | tv.tv_sec = 0; 440 | tv.tv_usec = 0; 441 | FD_ZERO(&rset); 442 | FD_SET(ctx->s, &rset); 443 | rc = select(ctx->s+1, &rset, NULL, NULL, &tv); 444 | if (rc == -1) { 445 | return -1; 446 | } 447 | 448 | if (rc == 1) { 449 | /* There is data to flush */ 450 | rc = recv(ctx->s, devnull, MODBUS_TCP_MAX_ADU_LENGTH, 0); 451 | } 452 | #endif 453 | if (rc > 0) { 454 | rc_sum += rc; 455 | } 456 | } while (rc == MODBUS_TCP_MAX_ADU_LENGTH); 457 | 458 | return rc_sum; 459 | } 460 | 461 | /* Listens for any request from one or many modbus masters in TCP */ 462 | int modbus_tcp_listen(modbus_t *ctx, int nb_connection) 463 | { 464 | int new_s; 465 | int enable; 466 | struct sockaddr_in addr; 467 | modbus_tcp_t *ctx_tcp; 468 | 469 | if (ctx == NULL) { 470 | errno = EINVAL; 471 | return -1; 472 | } 473 | 474 | ctx_tcp = ctx->backend_data; 475 | 476 | #ifdef OS_WIN32 477 | if (_modbus_tcp_init_win32() == -1) { 478 | return -1; 479 | } 480 | #endif 481 | 482 | new_s = socket(ctx_tcp->domain, SOCK_STREAM, IPPROTO_TCP); 483 | if (new_s == -1) { 484 | return -1; 485 | } 486 | 487 | enable = 1; 488 | if (setsockopt(new_s, SOL_SOCKET, SO_REUSEADDR, 489 | (char *)&enable, sizeof(enable)) == -1) { 490 | close(new_s); 491 | return -1; 492 | } 493 | 494 | memset(&addr, 0, sizeof(addr)); 495 | addr.sin_family = ctx_tcp->domain; 496 | /* If the modbus port is < to 1024, we need the setuid root. */ 497 | addr.sin_port = htons(ctx_tcp->port); 498 | if (ctx_tcp->ip[0] == '0') { 499 | /* Listen any addresses */ 500 | addr.sin_addr.s_addr = htonl(INADDR_ANY); 501 | } else { 502 | /* Listen only specified IP address */ 503 | addr.sin_addr.s_addr = inet_addr(ctx_tcp->ip); 504 | } 505 | if (bind(new_s, (struct sockaddr *)&addr, sizeof(addr)) == -1) { 506 | close(new_s); 507 | return -1; 508 | } 509 | 510 | if (listen(new_s, nb_connection) == -1) { 511 | close(new_s); 512 | return -1; 513 | } 514 | 515 | return new_s; 516 | } 517 | 518 | int modbus_tcp_pi_listen(modbus_t *ctx, int nb_connection) 519 | { 520 | int rc; 521 | struct addrinfo *ai_list; 522 | struct addrinfo *ai_ptr; 523 | struct addrinfo ai_hints; 524 | const char *node; 525 | const char *service; 526 | int new_s; 527 | modbus_tcp_pi_t *ctx_tcp_pi; 528 | 529 | if (ctx == NULL) { 530 | errno = EINVAL; 531 | return -1; 532 | } 533 | 534 | ctx_tcp_pi = ctx->backend_data; 535 | 536 | #ifdef OS_WIN32 537 | if (_modbus_tcp_init_win32() == -1) { 538 | return -1; 539 | } 540 | #endif 541 | 542 | if (ctx_tcp_pi->node[0] == 0) { 543 | node = NULL; /* == any */ 544 | } else { 545 | node = ctx_tcp_pi->node; 546 | } 547 | 548 | if (ctx_tcp_pi->service[0] == 0) { 549 | service = "502"; 550 | } else { 551 | service = ctx_tcp_pi->service; 552 | } 553 | 554 | memset(&ai_hints, 0, sizeof (ai_hints)); 555 | /* If node is not NULL, than the AI_PASSIVE flag is ignored. */ 556 | ai_hints.ai_flags |= AI_PASSIVE; 557 | #ifdef AI_ADDRCONFIG 558 | ai_hints.ai_flags |= AI_ADDRCONFIG; 559 | #endif 560 | ai_hints.ai_family = AF_UNSPEC; 561 | ai_hints.ai_socktype = SOCK_STREAM; 562 | ai_hints.ai_addr = NULL; 563 | ai_hints.ai_canonname = NULL; 564 | ai_hints.ai_next = NULL; 565 | 566 | ai_list = NULL; 567 | rc = getaddrinfo(node, service, &ai_hints, &ai_list); 568 | if (rc != 0) { 569 | if (ctx->debug) { 570 | fprintf(stderr, "Error returned by getaddrinfo: %d\n", rc); 571 | } 572 | errno = ECONNREFUSED; 573 | return -1; 574 | } 575 | 576 | new_s = -1; 577 | for (ai_ptr = ai_list; ai_ptr != NULL; ai_ptr = ai_ptr->ai_next) { 578 | int s; 579 | 580 | s = socket(ai_ptr->ai_family, ai_ptr->ai_socktype, 581 | ai_ptr->ai_protocol); 582 | if (s < 0) { 583 | if (ctx->debug) { 584 | perror("socket"); 585 | } 586 | continue; 587 | } else { 588 | int enable = 1; 589 | rc = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, 590 | (void *)&enable, sizeof (enable)); 591 | if (rc != 0) { 592 | close(s); 593 | if (ctx->debug) { 594 | perror("setsockopt"); 595 | } 596 | continue; 597 | } 598 | } 599 | 600 | rc = bind(s, ai_ptr->ai_addr, ai_ptr->ai_addrlen); 601 | if (rc != 0) { 602 | close(s); 603 | if (ctx->debug) { 604 | perror("bind"); 605 | } 606 | continue; 607 | } 608 | 609 | rc = listen(s, nb_connection); 610 | if (rc != 0) { 611 | close(s); 612 | if (ctx->debug) { 613 | perror("listen"); 614 | } 615 | continue; 616 | } 617 | 618 | new_s = s; 619 | break; 620 | } 621 | freeaddrinfo(ai_list); 622 | 623 | if (new_s < 0) { 624 | return -1; 625 | } 626 | 627 | return new_s; 628 | } 629 | 630 | int modbus_tcp_accept(modbus_t *ctx, int *s) 631 | { 632 | struct sockaddr_in addr; 633 | socklen_t addrlen; 634 | 635 | if (ctx == NULL) { 636 | errno = EINVAL; 637 | return -1; 638 | } 639 | 640 | addrlen = sizeof(addr); 641 | #ifdef HAVE_ACCEPT4 642 | /* Inherit socket flags and use accept4 call */ 643 | ctx->s = accept4(*s, (struct sockaddr *)&addr, &addrlen, SOCK_CLOEXEC); 644 | #else 645 | ctx->s = accept(*s, (struct sockaddr *)&addr, &addrlen); 646 | #endif 647 | 648 | if (ctx->s == -1) { 649 | close(*s); 650 | *s = -1; 651 | return -1; 652 | } 653 | 654 | if (ctx->debug) { 655 | printf("The client connection from %s is accepted\n", 656 | inet_ntoa(addr.sin_addr)); 657 | } 658 | 659 | return ctx->s; 660 | } 661 | 662 | int modbus_tcp_pi_accept(modbus_t *ctx, int *s) 663 | { 664 | struct sockaddr_storage addr; 665 | socklen_t addrlen; 666 | 667 | if (ctx == NULL) { 668 | errno = EINVAL; 669 | return -1; 670 | } 671 | 672 | addrlen = sizeof(addr); 673 | #ifdef HAVE_ACCEPT4 674 | /* Inherit socket flags and use accept4 call */ 675 | ctx->s = accept4(*s, (struct sockaddr *)&addr, &addrlen, SOCK_CLOEXEC); 676 | #else 677 | ctx->s = accept(*s, (struct sockaddr *)&addr, &addrlen); 678 | #endif 679 | if (ctx->s == -1) { 680 | close(*s); 681 | *s = -1; 682 | } 683 | 684 | if (ctx->debug) { 685 | printf("The client connection is accepted.\n"); 686 | } 687 | 688 | return ctx->s; 689 | } 690 | 691 | static int _modbus_tcp_select(modbus_t *ctx, fd_set *rset, struct timeval *tv, int length_to_read) 692 | { 693 | int s_rc; 694 | 695 | while ((s_rc = select(ctx->s+1, rset, NULL, NULL, tv)) == -1) { 696 | if (errno == EINTR) { 697 | if (ctx->debug) { 698 | fprintf(stderr, "A non blocked signal was caught\n"); 699 | } 700 | /* Necessary after an error */ 701 | FD_ZERO(rset); 702 | FD_SET(ctx->s, rset); 703 | } else { 704 | return -1; 705 | } 706 | } 707 | 708 | if (s_rc == 0) { 709 | errno = ETIMEDOUT; 710 | return -1; 711 | } 712 | 713 | return s_rc; 714 | } 715 | 716 | static void _modbus_tcp_free(modbus_t *ctx) { 717 | free(ctx->backend_data); 718 | free(ctx); 719 | } 720 | 721 | const modbus_backend_t _modbus_tcp_backend = { 722 | _MODBUS_BACKEND_TYPE_TCP, 723 | _MODBUS_TCP_HEADER_LENGTH, 724 | _MODBUS_TCP_CHECKSUM_LENGTH, 725 | MODBUS_TCP_MAX_ADU_LENGTH, 726 | _modbus_set_slave, 727 | _modbus_tcp_build_request_basis, 728 | _modbus_tcp_build_response_basis, 729 | _modbus_tcp_prepare_response_tid, 730 | _modbus_tcp_send_msg_pre, 731 | _modbus_tcp_send, 732 | _modbus_tcp_receive, 733 | _modbus_tcp_recv, 734 | _modbus_tcp_check_integrity, 735 | _modbus_tcp_pre_check_confirmation, 736 | _modbus_tcp_connect, 737 | _modbus_tcp_close, 738 | _modbus_tcp_flush, 739 | _modbus_tcp_select, 740 | _modbus_tcp_free 741 | }; 742 | 743 | 744 | const modbus_backend_t _modbus_tcp_pi_backend = { 745 | _MODBUS_BACKEND_TYPE_TCP, 746 | _MODBUS_TCP_HEADER_LENGTH, 747 | _MODBUS_TCP_CHECKSUM_LENGTH, 748 | MODBUS_TCP_MAX_ADU_LENGTH, 749 | _modbus_set_slave, 750 | _modbus_tcp_build_request_basis, 751 | _modbus_tcp_build_response_basis, 752 | _modbus_tcp_prepare_response_tid, 753 | _modbus_tcp_send_msg_pre, 754 | _modbus_tcp_send, 755 | _modbus_tcp_receive, 756 | _modbus_tcp_recv, 757 | _modbus_tcp_check_integrity, 758 | _modbus_tcp_pre_check_confirmation, 759 | _modbus_tcp_pi_connect, 760 | _modbus_tcp_close, 761 | _modbus_tcp_flush, 762 | _modbus_tcp_select, 763 | _modbus_tcp_free 764 | }; 765 | 766 | modbus_t* modbus_new_tcp(const char *ip, int port, int domain) 767 | { 768 | modbus_t *ctx; 769 | modbus_tcp_t *ctx_tcp; 770 | size_t dest_size; 771 | size_t ret_size; 772 | 773 | #if defined(OS_BSD) 774 | /* MSG_NOSIGNAL is unsupported on *BSD so we install an ignore 775 | handler for SIGPIPE. */ 776 | struct sigaction sa; 777 | 778 | sa.sa_handler = SIG_IGN; 779 | if (sigaction(SIGPIPE, &sa, NULL) < 0) { 780 | /* The debug flag can't be set here... */ 781 | fprintf(stderr, "Coud not install SIGPIPE handler.\n"); 782 | return NULL; 783 | } 784 | #endif 785 | 786 | ctx = (modbus_t *)malloc(sizeof(modbus_t)); 787 | _modbus_init_common(ctx); 788 | 789 | /* Could be changed after to reach a remote serial Modbus device */ 790 | ctx->slave = MODBUS_TCP_SLAVE; 791 | 792 | ctx->backend = &_modbus_tcp_backend; 793 | 794 | ctx->backend_data = (modbus_tcp_t *)malloc(sizeof(modbus_tcp_t)); 795 | ctx_tcp = (modbus_tcp_t *)ctx->backend_data; 796 | ctx_tcp->domain = domain; 797 | 798 | if (ip != NULL) { 799 | dest_size = sizeof(char) * 16; 800 | ret_size = strlcpy(ctx_tcp->ip, ip, dest_size); 801 | if (ret_size == 0) { 802 | fprintf(stderr, "The IP string is empty\n"); 803 | modbus_free(ctx); 804 | errno = EINVAL; 805 | return NULL; 806 | } 807 | 808 | if (ret_size >= dest_size) { 809 | fprintf(stderr, "The IP string has been truncated\n"); 810 | modbus_free(ctx); 811 | errno = EINVAL; 812 | return NULL; 813 | } 814 | } else { 815 | ctx_tcp->ip[0] = '0'; 816 | } 817 | ctx_tcp->port = port; 818 | ctx_tcp->t_id = 0; 819 | 820 | return ctx; 821 | } 822 | 823 | 824 | modbus_t* modbus_new_tcp_pi(const char *node, const char *service) 825 | { 826 | modbus_t *ctx; 827 | modbus_tcp_pi_t *ctx_tcp_pi; 828 | size_t dest_size; 829 | size_t ret_size; 830 | 831 | ctx = (modbus_t *)malloc(sizeof(modbus_t)); 832 | _modbus_init_common(ctx); 833 | 834 | /* Could be changed after to reach a remote serial Modbus device */ 835 | ctx->slave = MODBUS_TCP_SLAVE; 836 | 837 | ctx->backend = &_modbus_tcp_pi_backend; 838 | 839 | ctx->backend_data = (modbus_tcp_pi_t *)malloc(sizeof(modbus_tcp_pi_t)); 840 | ctx_tcp_pi = (modbus_tcp_pi_t *)ctx->backend_data; 841 | 842 | if (node == NULL) { 843 | /* The node argument can be empty to indicate any hosts */ 844 | ctx_tcp_pi->node[0] = 0; 845 | } else { 846 | dest_size = sizeof(char) * _MODBUS_TCP_PI_NODE_LENGTH; 847 | ret_size = strlcpy(ctx_tcp_pi->node, node, dest_size); 848 | if (ret_size == 0) { 849 | fprintf(stderr, "The node string is empty\n"); 850 | modbus_free(ctx); 851 | errno = EINVAL; 852 | return NULL; 853 | } 854 | 855 | if (ret_size >= dest_size) { 856 | fprintf(stderr, "The node string has been truncated\n"); 857 | modbus_free(ctx); 858 | errno = EINVAL; 859 | return NULL; 860 | } 861 | } 862 | 863 | if (service != NULL) { 864 | dest_size = sizeof(char) * _MODBUS_TCP_PI_SERVICE_LENGTH; 865 | ret_size = strlcpy(ctx_tcp_pi->service, service, dest_size); 866 | } else { 867 | /* Empty service is not allowed, error catched below. */ 868 | ret_size = 0; 869 | } 870 | 871 | if (ret_size == 0) { 872 | fprintf(stderr, "The service string is empty\n"); 873 | modbus_free(ctx); 874 | errno = EINVAL; 875 | return NULL; 876 | } 877 | 878 | if (ret_size >= dest_size) { 879 | fprintf(stderr, "The service string has been truncated\n"); 880 | modbus_free(ctx); 881 | errno = EINVAL; 882 | return NULL; 883 | } 884 | 885 | ctx_tcp_pi->t_id = 0; 886 | 887 | return ctx; 888 | } 889 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | (This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.) 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | {description} 474 | Copyright (C) {year} {fullname} 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 489 | USA 490 | 491 | Also add information on how to contact you by electronic and paper mail. 492 | 493 | You should also get your employer (if you work as a programmer) or your 494 | school, if any, to sign a "copyright disclaimer" for the library, if 495 | necessary. Here is a sample; alter the names: 496 | 497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 498 | library `Frob' (a library for tweaking knobs) written by James Random 499 | Hacker. 500 | 501 | {signature of Ty Coon}, 1 April 1990 502 | Ty Coon, President of Vice 503 | 504 | That's all there is to it! 505 | -------------------------------------------------------------------------------- /src/modbus-rtu.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2001-2011 Stéphane Raimbault 3 | * 4 | * SPDX-License-Identifier: LGPL-2.1+ 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #ifndef _MSC_VER 13 | #include 14 | #endif 15 | 16 | #include 17 | #include 18 | #include 19 | 20 | #include "modbus-private.h" 21 | 22 | #include "modbus-rtu.h" 23 | #include "modbus-rtu-private.h" 24 | 25 | #ifndef O_NDELAY 26 | #define O_NDELAY _FNDELAY 27 | #endif 28 | 29 | /* Table of CRC values for high-order byte */ 30 | static const uint8_t table_crc_hi[] = { 31 | 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 32 | 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 33 | 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 34 | 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 35 | 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 36 | 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 37 | 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 38 | 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 39 | 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 40 | 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 41 | 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 42 | 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 43 | 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 44 | 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 45 | 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 46 | 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 47 | 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 48 | 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 49 | 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 50 | 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 51 | 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 52 | 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 53 | 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 54 | 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 55 | 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 56 | 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40 57 | }; 58 | 59 | /* Table of CRC values for low-order byte */ 60 | static const uint8_t table_crc_lo[] = { 61 | 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06, 62 | 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD, 63 | 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 64 | 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A, 65 | 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4, 66 | 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3, 67 | 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 68 | 0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4, 69 | 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A, 70 | 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29, 71 | 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 72 | 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26, 73 | 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60, 74 | 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67, 75 | 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 76 | 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68, 77 | 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E, 78 | 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5, 79 | 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 80 | 0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92, 81 | 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C, 82 | 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B, 83 | 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B, 84 | 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C, 85 | 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42, 86 | 0x43, 0x83, 0x41, 0x81, 0x80, 0x40 87 | }; 88 | 89 | /* Define the slave ID of the remote device to talk in master mode or set the 90 | * internal slave ID in slave mode */ 91 | static int _modbus_set_slave(modbus_t *ctx, int slave) 92 | { 93 | /* Broadcast address is 0 (MODBUS_BROADCAST_ADDRESS) */ 94 | if (slave >= 0 && slave <= 247) { 95 | ctx->slave = slave; 96 | } else { 97 | errno = EINVAL; 98 | return -1; 99 | } 100 | 101 | return 0; 102 | } 103 | 104 | /* Builds a RTU request header */ 105 | static int _modbus_rtu_build_request_basis(modbus_t *ctx, int function, 106 | int addr, int nb, 107 | uint8_t *req) 108 | { 109 | RT_ASSERT(ctx->slave != -1); 110 | req[0] = ctx->slave; 111 | req[1] = function; 112 | req[2] = addr >> 8; 113 | req[3] = addr & 0x00ff; 114 | req[4] = nb >> 8; 115 | req[5] = nb & 0x00ff; 116 | 117 | return _MODBUS_RTU_PRESET_REQ_LENGTH; 118 | } 119 | 120 | /* Builds a RTU response header */ 121 | static int _modbus_rtu_build_response_basis(sft_t *sft, uint8_t *rsp) 122 | { 123 | /* In this case, the slave is certainly valid because a check is already 124 | * done in _modbus_rtu_listen */ 125 | rsp[0] = sft->slave; 126 | rsp[1] = sft->function; 127 | 128 | return _MODBUS_RTU_PRESET_RSP_LENGTH; 129 | } 130 | 131 | static uint16_t crc16(uint8_t *buffer, uint16_t buffer_length) 132 | { 133 | uint8_t crc_hi = 0xFF; /* high CRC byte initialized */ 134 | uint8_t crc_lo = 0xFF; /* low CRC byte initialized */ 135 | unsigned int i; /* will index into CRC lookup */ 136 | 137 | /* pass through message buffer */ 138 | while (buffer_length--) { 139 | i = crc_hi ^ *buffer++; /* calculate the CRC */ 140 | crc_hi = crc_lo ^ table_crc_hi[i]; 141 | crc_lo = table_crc_lo[i]; 142 | } 143 | 144 | return (crc_hi << 8 | crc_lo); 145 | } 146 | 147 | static int _modbus_rtu_prepare_response_tid(const uint8_t *req, int *req_length) 148 | { 149 | (*req_length) -= _MODBUS_RTU_CHECKSUM_LENGTH; 150 | /* No TID */ 151 | return 0; 152 | } 153 | 154 | static int _modbus_rtu_send_msg_pre(uint8_t *req, int req_length) 155 | { 156 | uint16_t crc = crc16(req, req_length); 157 | req[req_length++] = crc >> 8; 158 | req[req_length++] = crc & 0x00FF; 159 | 160 | return req_length; 161 | } 162 | 163 | #if defined(_WIN32) 164 | 165 | /* This simple implementation is sort of a substitute of the select() call, 166 | * working this way: the win32_ser_select() call tries to read some data from 167 | * the serial port, setting the timeout as the select() call would. Data read is 168 | * stored into the receive buffer, that is then consumed by the win32_ser_read() 169 | * call. So win32_ser_select() does both the event waiting and the reading, 170 | * while win32_ser_read() only consumes the receive buffer. 171 | */ 172 | 173 | static void win32_ser_init(struct win32_ser *ws) 174 | { 175 | /* Clear everything */ 176 | memset(ws, 0x00, sizeof(struct win32_ser)); 177 | 178 | /* Set file handle to invalid */ 179 | ws->fd = INVALID_HANDLE_VALUE; 180 | } 181 | 182 | /* FIXME Try to remove length_to_read -> max_len argument, only used by win32 */ 183 | static int win32_ser_select(struct win32_ser *ws, int max_len, 184 | const struct timeval *tv) 185 | { 186 | COMMTIMEOUTS comm_to; 187 | unsigned int msec = 0; 188 | 189 | /* Check if some data still in the buffer to be consumed */ 190 | if (ws->n_bytes > 0) { 191 | return 1; 192 | } 193 | 194 | /* Setup timeouts like select() would do. 195 | FIXME Please someone on Windows can look at this? 196 | Does it possible to use WaitCommEvent? 197 | When tv is NULL, MAXDWORD isn't infinite! 198 | */ 199 | if (tv == NULL) { 200 | msec = MAXDWORD; 201 | } else { 202 | msec = tv->tv_sec * 1000 + tv->tv_usec / 1000; 203 | if (msec < 1) 204 | msec = 1; 205 | } 206 | 207 | comm_to.ReadIntervalTimeout = msec; 208 | comm_to.ReadTotalTimeoutMultiplier = 0; 209 | comm_to.ReadTotalTimeoutConstant = msec; 210 | comm_to.WriteTotalTimeoutMultiplier = 0; 211 | comm_to.WriteTotalTimeoutConstant = 1000; 212 | SetCommTimeouts(ws->fd, &comm_to); 213 | 214 | /* Read some bytes */ 215 | if ((max_len > PY_BUF_SIZE) || (max_len < 0)) { 216 | max_len = PY_BUF_SIZE; 217 | } 218 | 219 | if (ReadFile(ws->fd, &ws->buf, max_len, &ws->n_bytes, NULL)) { 220 | /* Check if some bytes available */ 221 | if (ws->n_bytes > 0) { 222 | /* Some bytes read */ 223 | return 1; 224 | } else { 225 | /* Just timed out */ 226 | return 0; 227 | } 228 | } else { 229 | /* Some kind of error */ 230 | return -1; 231 | } 232 | } 233 | 234 | static int win32_ser_read(struct win32_ser *ws, uint8_t *p_msg, 235 | unsigned int max_len) 236 | { 237 | unsigned int n = ws->n_bytes; 238 | 239 | if (max_len < n) { 240 | n = max_len; 241 | } 242 | 243 | if (n > 0) { 244 | memcpy(p_msg, ws->buf, n); 245 | } 246 | 247 | ws->n_bytes -= n; 248 | 249 | return n; 250 | } 251 | #endif 252 | 253 | #if HAVE_DECL_TIOCM_RTS 254 | static void _modbus_rtu_ioctl_rts(modbus_t *ctx, int on) 255 | { 256 | modbus_rtu_t *ctx_rtu = ctx->backend_data; 257 | if (on) { 258 | rt_pin_write(ctx_rtu->rts_pin, PIN_HIGH); 259 | } else { 260 | rt_pin_write(ctx_rtu->rts_pin, PIN_LOW); 261 | } 262 | } 263 | #endif 264 | 265 | static ssize_t _modbus_rtu_send(modbus_t *ctx, const uint8_t *req, int req_length) 266 | { 267 | #if defined(_WIN32) 268 | modbus_rtu_t *ctx_rtu = ctx->backend_data; 269 | DWORD n_bytes = 0; 270 | return (WriteFile(ctx_rtu->w_ser.fd, req, req_length, &n_bytes, NULL)) ? (ssize_t)n_bytes : -1; 271 | #else 272 | #if HAVE_DECL_TIOCM_RTS 273 | modbus_rtu_t *ctx_rtu = ctx->backend_data; 274 | if (ctx_rtu->rts != MODBUS_RTU_RTS_NONE) { 275 | ssize_t size; 276 | 277 | if (ctx->debug) { 278 | fprintf(stderr, "Sending request using RTS signal\n"); 279 | } 280 | 281 | ctx_rtu->set_rts(ctx, ctx_rtu->rts == MODBUS_RTU_RTS_UP); 282 | rt_int32_t nms = (ctx_rtu->rts_delay/1000) ? (ctx_rtu->rts_delay/1000) : 1; 283 | rt_thread_mdelay(nms); 284 | 285 | size = write(ctx->s, req, req_length); 286 | 287 | ctx_rtu->set_rts(ctx, ctx_rtu->rts != MODBUS_RTU_RTS_UP); 288 | 289 | return size; 290 | } else { 291 | #endif 292 | return write(ctx->s, req, req_length); 293 | #if HAVE_DECL_TIOCM_RTS 294 | } 295 | #endif 296 | #endif 297 | } 298 | 299 | static int _modbus_rtu_receive(modbus_t *ctx, uint8_t *req) 300 | { 301 | return _modbus_receive_msg(ctx, req, MSG_INDICATION); 302 | } 303 | 304 | static ssize_t _modbus_rtu_recv(modbus_t *ctx, uint8_t *rsp, int rsp_length) 305 | { 306 | #if defined(_WIN32) 307 | return win32_ser_read(&((modbus_rtu_t *)ctx->backend_data)->w_ser, rsp, rsp_length); 308 | #else 309 | return read(ctx->s, rsp, rsp_length); 310 | #endif 311 | } 312 | 313 | static int _modbus_rtu_flush(modbus_t *); 314 | 315 | static int _modbus_rtu_pre_check_confirmation(modbus_t *ctx, const uint8_t *req, 316 | const uint8_t *rsp, int rsp_length) 317 | { 318 | /* Check responding slave is the slave we requested (except for broacast 319 | * request) */ 320 | if (req[0] != rsp[0] && req[0] != MODBUS_BROADCAST_ADDRESS) { 321 | if (ctx->debug) { 322 | fprintf(stderr, 323 | "The responding slave %d isn't the requested slave %d\n", 324 | rsp[0], req[0]); 325 | } 326 | errno = EMBBADSLAVE; 327 | return -1; 328 | } else { 329 | return 0; 330 | } 331 | } 332 | 333 | /* The check_crc16 function shall return 0 is the message is ignored and the 334 | message length if the CRC is valid. Otherwise it shall return -1 and set 335 | errno to EMBADCRC. */ 336 | static int _modbus_rtu_check_integrity(modbus_t *ctx, uint8_t *msg, 337 | const int msg_length) 338 | { 339 | uint16_t crc_calculated; 340 | uint16_t crc_received; 341 | 342 | crc_calculated = crc16(msg, msg_length - 2); 343 | crc_received = (msg[msg_length - 2] << 8) | msg[msg_length - 1]; 344 | 345 | /* Check CRC of msg */ 346 | if (crc_calculated == crc_received) { 347 | return msg_length; 348 | } else { 349 | if (ctx->debug) { 350 | fprintf(stderr, "ERROR CRC received 0x%0X != CRC calculated 0x%0X\n", 351 | crc_received, crc_calculated); 352 | } 353 | 354 | if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) { 355 | _modbus_rtu_flush(ctx); 356 | } 357 | errno = EMBBADCRC; 358 | return -1; 359 | } 360 | } 361 | 362 | /* Sets up a serial port for RTU communications */ 363 | static int _modbus_rtu_connect(modbus_t *ctx) 364 | { 365 | #if defined(_WIN32) 366 | DCB dcb; 367 | #else 368 | struct termios tios; 369 | speed_t speed; 370 | int flags; 371 | #endif 372 | modbus_rtu_t *ctx_rtu = ctx->backend_data; 373 | 374 | if (ctx->debug) { 375 | printf("Opening %s at %d bauds (%c, %d, %d)\n", 376 | ctx_rtu->device, ctx_rtu->baud, ctx_rtu->parity, 377 | ctx_rtu->data_bit, ctx_rtu->stop_bit); 378 | } 379 | 380 | #if defined(_WIN32) 381 | /* Some references here: 382 | * http://msdn.microsoft.com/en-us/library/aa450602.aspx 383 | */ 384 | win32_ser_init(&ctx_rtu->w_ser); 385 | 386 | /* ctx_rtu->device should contain a string like "COMxx:" xx being a decimal 387 | * number */ 388 | ctx_rtu->w_ser.fd = CreateFileA(ctx_rtu->device, 389 | GENERIC_READ | GENERIC_WRITE, 390 | 0, 391 | NULL, 392 | OPEN_EXISTING, 393 | 0, 394 | NULL); 395 | 396 | /* Error checking */ 397 | if (ctx_rtu->w_ser.fd == INVALID_HANDLE_VALUE) { 398 | if (ctx->debug) { 399 | fprintf(stderr, "ERROR Can't open the device %s (LastError %d)\n", 400 | ctx_rtu->device, (int)GetLastError()); 401 | } 402 | return -1; 403 | } 404 | 405 | /* Save params */ 406 | ctx_rtu->old_dcb.DCBlength = sizeof(DCB); 407 | if (!GetCommState(ctx_rtu->w_ser.fd, &ctx_rtu->old_dcb)) { 408 | if (ctx->debug) { 409 | fprintf(stderr, "ERROR Error getting configuration (LastError %d)\n", 410 | (int)GetLastError()); 411 | } 412 | CloseHandle(ctx_rtu->w_ser.fd); 413 | ctx_rtu->w_ser.fd = INVALID_HANDLE_VALUE; 414 | return -1; 415 | } 416 | 417 | /* Build new configuration (starting from current settings) */ 418 | dcb = ctx_rtu->old_dcb; 419 | 420 | /* Speed setting */ 421 | switch (ctx_rtu->baud) { 422 | case 110: 423 | dcb.BaudRate = CBR_110; 424 | break; 425 | case 300: 426 | dcb.BaudRate = CBR_300; 427 | break; 428 | case 600: 429 | dcb.BaudRate = CBR_600; 430 | break; 431 | case 1200: 432 | dcb.BaudRate = CBR_1200; 433 | break; 434 | case 2400: 435 | dcb.BaudRate = CBR_2400; 436 | break; 437 | case 4800: 438 | dcb.BaudRate = CBR_4800; 439 | break; 440 | case 9600: 441 | dcb.BaudRate = CBR_9600; 442 | break; 443 | case 14400: 444 | dcb.BaudRate = CBR_14400; 445 | break; 446 | case 19200: 447 | dcb.BaudRate = CBR_19200; 448 | break; 449 | case 38400: 450 | dcb.BaudRate = CBR_38400; 451 | break; 452 | case 57600: 453 | dcb.BaudRate = CBR_57600; 454 | break; 455 | case 115200: 456 | dcb.BaudRate = CBR_115200; 457 | break; 458 | case 230400: 459 | /* CBR_230400 - not defined */ 460 | dcb.BaudRate = 230400; 461 | break; 462 | case 250000: 463 | dcb.BaudRate = 250000; 464 | break; 465 | case 460800: 466 | dcb.BaudRate = 460800; 467 | break; 468 | case 500000: 469 | dcb.BaudRate = 500000; 470 | break; 471 | case 921600: 472 | dcb.BaudRate = 921600; 473 | break; 474 | case 1000000: 475 | dcb.BaudRate = 1000000; 476 | break; 477 | default: 478 | dcb.BaudRate = CBR_9600; 479 | if (ctx->debug) { 480 | fprintf(stderr, "WARNING Unknown baud rate %d for %s (B9600 used)\n", 481 | ctx_rtu->baud, ctx_rtu->device); 482 | } 483 | } 484 | 485 | /* Data bits */ 486 | switch (ctx_rtu->data_bit) { 487 | case 5: 488 | dcb.ByteSize = 5; 489 | break; 490 | case 6: 491 | dcb.ByteSize = 6; 492 | break; 493 | case 7: 494 | dcb.ByteSize = 7; 495 | break; 496 | case 8: 497 | default: 498 | dcb.ByteSize = 8; 499 | break; 500 | } 501 | 502 | /* Stop bits */ 503 | if (ctx_rtu->stop_bit == 1) 504 | dcb.StopBits = ONESTOPBIT; 505 | else /* 2 */ 506 | dcb.StopBits = TWOSTOPBITS; 507 | 508 | /* Parity */ 509 | if (ctx_rtu->parity == 'N') { 510 | dcb.Parity = NOPARITY; 511 | dcb.fParity = FALSE; 512 | } else if (ctx_rtu->parity == 'E') { 513 | dcb.Parity = EVENPARITY; 514 | dcb.fParity = TRUE; 515 | } else { 516 | /* odd */ 517 | dcb.Parity = ODDPARITY; 518 | dcb.fParity = TRUE; 519 | } 520 | 521 | /* Hardware handshaking left as default settings retrieved */ 522 | 523 | /* No software handshaking */ 524 | dcb.fTXContinueOnXoff = TRUE; 525 | dcb.fOutX = FALSE; 526 | dcb.fInX = FALSE; 527 | 528 | /* Binary mode (it's the only supported on Windows anyway) */ 529 | dcb.fBinary = TRUE; 530 | 531 | /* Don't want errors to be blocking */ 532 | dcb.fAbortOnError = FALSE; 533 | 534 | /* Setup port */ 535 | if (!SetCommState(ctx_rtu->w_ser.fd, &dcb)) { 536 | if (ctx->debug) { 537 | fprintf(stderr, "ERROR Error setting new configuration (LastError %d)\n", 538 | (int)GetLastError()); 539 | } 540 | CloseHandle(ctx_rtu->w_ser.fd); 541 | ctx_rtu->w_ser.fd = INVALID_HANDLE_VALUE; 542 | return -1; 543 | } 544 | #else 545 | /* The O_NOCTTY flag tells UNIX that this program doesn't want 546 | to be the "controlling terminal" for that port. If you 547 | don't specify this then any input (such as keyboard abort 548 | signals and so forth) will affect your process 549 | 550 | Timeouts are ignored in canonical input mode or when the 551 | NDELAY option is set on the file via open or fcntl */ 552 | flags = O_RDWR | O_NOCTTY | O_NDELAY | O_EXCL; 553 | #ifdef O_CLOEXEC 554 | flags |= O_CLOEXEC; 555 | #endif 556 | 557 | ctx->s = open(ctx_rtu->device, flags); 558 | if (ctx->s == -1) { 559 | if (ctx->debug) { 560 | fprintf(stderr, "ERROR Can't open the device %s (%s)\n", 561 | ctx_rtu->device, strerror(errno)); 562 | } 563 | return -1; 564 | } 565 | 566 | /* Save */ 567 | tcgetattr(ctx->s, &ctx_rtu->old_tios); 568 | 569 | memset(&tios, 0, sizeof(struct termios)); 570 | 571 | /* C_ISPEED Input baud (new interface) 572 | C_OSPEED Output baud (new interface) 573 | */ 574 | switch (ctx_rtu->baud) { 575 | case 110: 576 | speed = B110; 577 | break; 578 | case 300: 579 | speed = B300; 580 | break; 581 | case 600: 582 | speed = B600; 583 | break; 584 | case 1200: 585 | speed = B1200; 586 | break; 587 | case 2400: 588 | speed = B2400; 589 | break; 590 | case 4800: 591 | speed = B4800; 592 | break; 593 | case 9600: 594 | speed = B9600; 595 | break; 596 | case 19200: 597 | speed = B19200; 598 | break; 599 | case 38400: 600 | speed = B38400; 601 | break; 602 | #ifdef B57600 603 | case 57600: 604 | speed = B57600; 605 | break; 606 | #endif 607 | #ifdef B115200 608 | case 115200: 609 | speed = B115200; 610 | break; 611 | #endif 612 | #ifdef B230400 613 | case 230400: 614 | speed = B230400; 615 | break; 616 | #endif 617 | #ifdef B460800 618 | case 460800: 619 | speed = B460800; 620 | break; 621 | #endif 622 | #ifdef B500000 623 | case 500000: 624 | speed = B500000; 625 | break; 626 | #endif 627 | #ifdef B576000 628 | case 576000: 629 | speed = B576000; 630 | break; 631 | #endif 632 | #ifdef B921600 633 | case 921600: 634 | speed = B921600; 635 | break; 636 | #endif 637 | #ifdef B1000000 638 | case 1000000: 639 | speed = B1000000; 640 | break; 641 | #endif 642 | #ifdef B1152000 643 | case 1152000: 644 | speed = B1152000; 645 | break; 646 | #endif 647 | #ifdef B1500000 648 | case 1500000: 649 | speed = B1500000; 650 | break; 651 | #endif 652 | #ifdef B2500000 653 | case 2500000: 654 | speed = B2500000; 655 | break; 656 | #endif 657 | #ifdef B3000000 658 | case 3000000: 659 | speed = B3000000; 660 | break; 661 | #endif 662 | #ifdef B3500000 663 | case 3500000: 664 | speed = B3500000; 665 | break; 666 | #endif 667 | #ifdef B4000000 668 | case 4000000: 669 | speed = B4000000; 670 | break; 671 | #endif 672 | default: 673 | speed = B9600; 674 | if (ctx->debug) { 675 | fprintf(stderr, 676 | "WARNING Unknown baud rate %d for %s (B9600 used)\n", 677 | ctx_rtu->baud, ctx_rtu->device); 678 | } 679 | } 680 | 681 | /* Set the baud rate */ 682 | if ((cfsetispeed(&tios, speed) < 0) || 683 | (cfsetospeed(&tios, speed) < 0)) { 684 | close(ctx->s); 685 | ctx->s = -1; 686 | return -1; 687 | } 688 | 689 | /* C_CFLAG Control options 690 | CLOCAL Local line - do not change "owner" of port 691 | CREAD Enable receiver 692 | */ 693 | tios.c_cflag |= (CREAD | CLOCAL); 694 | /* CSIZE, HUPCL, CRTSCTS (hardware flow control) */ 695 | 696 | /* Set data bits (5, 6, 7, 8 bits) 697 | CSIZE Bit mask for data bits 698 | */ 699 | tios.c_cflag &= ~CSIZE; 700 | switch (ctx_rtu->data_bit) { 701 | case 5: 702 | tios.c_cflag |= CS5; 703 | break; 704 | case 6: 705 | tios.c_cflag |= CS6; 706 | break; 707 | case 7: 708 | tios.c_cflag |= CS7; 709 | break; 710 | case 8: 711 | default: 712 | tios.c_cflag |= CS8; 713 | break; 714 | } 715 | 716 | /* Stop bit (1 or 2) */ 717 | if (ctx_rtu->stop_bit == 1) 718 | tios.c_cflag &=~ CSTOPB; 719 | else /* 2 */ 720 | tios.c_cflag |= CSTOPB; 721 | 722 | /* PARENB Enable parity bit 723 | PARODD Use odd parity instead of even */ 724 | if (ctx_rtu->parity == 'N') { 725 | /* None */ 726 | tios.c_cflag &=~ PARENB; 727 | } else if (ctx_rtu->parity == 'E') { 728 | /* Even */ 729 | tios.c_cflag |= PARENB; 730 | tios.c_cflag &=~ PARODD; 731 | } else { 732 | /* Odd */ 733 | tios.c_cflag |= PARENB; 734 | tios.c_cflag |= PARODD; 735 | } 736 | 737 | /* Read the man page of termios if you need more information. */ 738 | 739 | /* This field isn't used on POSIX systems 740 | tios.c_line = 0; 741 | */ 742 | 743 | /* C_LFLAG Line options 744 | 745 | ISIG Enable SIGINTR, SIGSUSP, SIGDSUSP, and SIGQUIT signals 746 | ICANON Enable canonical input (else raw) 747 | XCASE Map uppercase \lowercase (obsolete) 748 | ECHO Enable echoing of input characters 749 | ECHOE Echo erase character as BS-SP-BS 750 | ECHOK Echo NL after kill character 751 | ECHONL Echo NL 752 | NOFLSH Disable flushing of input buffers after 753 | interrupt or quit characters 754 | IEXTEN Enable extended functions 755 | ECHOCTL Echo control characters as ^char and delete as ~? 756 | ECHOPRT Echo erased character as character erased 757 | ECHOKE BS-SP-BS entire line on line kill 758 | FLUSHO Output being flushed 759 | PENDIN Retype pending input at next read or input char 760 | TOSTOP Send SIGTTOU for background output 761 | 762 | Canonical input is line-oriented. Input characters are put 763 | into a buffer which can be edited interactively by the user 764 | until a CR (carriage return) or LF (line feed) character is 765 | received. 766 | 767 | Raw input is unprocessed. Input characters are passed 768 | through exactly as they are received, when they are 769 | received. Generally you'll deselect the ICANON, ECHO, 770 | ECHOE, and ISIG options when using raw input 771 | */ 772 | 773 | /* Raw input */ 774 | tios.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); 775 | 776 | /* C_IFLAG Input options 777 | 778 | Constant Description 779 | INPCK Enable parity check 780 | IGNPAR Ignore parity errors 781 | PARMRK Mark parity errors 782 | ISTRIP Strip parity bits 783 | IXON Enable software flow control (outgoing) 784 | IXOFF Enable software flow control (incoming) 785 | IXANY Allow any character to start flow again 786 | IGNBRK Ignore break condition 787 | BRKINT Send a SIGINT when a break condition is detected 788 | INLCR Map NL to CR 789 | IGNCR Ignore CR 790 | ICRNL Map CR to NL 791 | IUCLC Map uppercase to lowercase 792 | IMAXBEL Echo BEL on input line too long 793 | */ 794 | if (ctx_rtu->parity == 'N') { 795 | /* None */ 796 | tios.c_iflag &= ~INPCK; 797 | } else { 798 | tios.c_iflag |= INPCK; 799 | } 800 | 801 | /* Software flow control is disabled */ 802 | tios.c_iflag &= ~(IXON | IXOFF | IXANY); 803 | 804 | /* C_OFLAG Output options 805 | OPOST Postprocess output (not set = raw output) 806 | ONLCR Map NL to CR-NL 807 | 808 | ONCLR ant others needs OPOST to be enabled 809 | */ 810 | 811 | /* Raw ouput */ 812 | tios.c_oflag &=~ OPOST; 813 | 814 | /* C_CC Control characters 815 | VMIN Minimum number of characters to read 816 | VTIME Time to wait for data (tenths of seconds) 817 | 818 | UNIX serial interface drivers provide the ability to 819 | specify character and packet timeouts. Two elements of the 820 | c_cc array are used for timeouts: VMIN and VTIME. Timeouts 821 | are ignored in canonical input mode or when the NDELAY 822 | option is set on the file via open or fcntl. 823 | 824 | VMIN specifies the minimum number of characters to read. If 825 | it is set to 0, then the VTIME value specifies the time to 826 | wait for every character read. Note that this does not mean 827 | that a read call for N bytes will wait for N characters to 828 | come in. Rather, the timeout will apply to the first 829 | character and the read call will return the number of 830 | characters immediately available (up to the number you 831 | request). 832 | 833 | If VMIN is non-zero, VTIME specifies the time to wait for 834 | the first character read. If a character is read within the 835 | time given, any read will block (wait) until all VMIN 836 | characters are read. That is, once the first character is 837 | read, the serial interface driver expects to receive an 838 | entire packet of characters (VMIN bytes total). If no 839 | character is read within the time allowed, then the call to 840 | read returns 0. This method allows you to tell the serial 841 | driver you need exactly N bytes and any read call will 842 | return 0 or N bytes. However, the timeout only applies to 843 | the first character read, so if for some reason the driver 844 | misses one character inside the N byte packet then the read 845 | call could block forever waiting for additional input 846 | characters. 847 | 848 | VTIME specifies the amount of time to wait for incoming 849 | characters in tenths of seconds. If VTIME is set to 0 (the 850 | default), reads will block (wait) indefinitely unless the 851 | NDELAY option is set on the port with open or fcntl. 852 | */ 853 | /* Unused because we use open with the NDELAY option */ 854 | tios.c_cc[VMIN] = 0; 855 | tios.c_cc[VTIME] = 0; 856 | 857 | if (tcsetattr(ctx->s, TCSANOW, &tios) < 0) { 858 | close(ctx->s); 859 | ctx->s = -1; 860 | return -1; 861 | } 862 | #endif 863 | 864 | return 0; 865 | } 866 | 867 | int modbus_rtu_set_serial_mode(modbus_t *ctx, int mode) 868 | { 869 | if (ctx == NULL) { 870 | errno = EINVAL; 871 | return -1; 872 | } 873 | 874 | if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU) { 875 | #if HAVE_DECL_TIOCSRS485 876 | modbus_rtu_t *ctx_rtu = ctx->backend_data; 877 | 878 | if (mode == MODBUS_RTU_RS485) { 879 | ctx_rtu->serial_mode = MODBUS_RTU_RS485; 880 | return 0; 881 | } else if (mode == MODBUS_RTU_RS232) { 882 | /* Turn off RS485 mode only if required */ 883 | if (ctx_rtu->serial_mode == MODBUS_RTU_RS485) { 884 | } 885 | ctx_rtu->serial_mode = MODBUS_RTU_RS232; 886 | return 0; 887 | } 888 | #else 889 | if (ctx->debug) { 890 | fprintf(stderr, "This function isn't supported on your platform\n"); 891 | } 892 | errno = ENOTSUP; 893 | return -1; 894 | #endif 895 | } 896 | 897 | /* Wrong backend and invalid mode specified */ 898 | errno = EINVAL; 899 | return -1; 900 | } 901 | 902 | int modbus_rtu_get_serial_mode(modbus_t *ctx) 903 | { 904 | if (ctx == NULL) { 905 | errno = EINVAL; 906 | return -1; 907 | } 908 | 909 | if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU) { 910 | #if HAVE_DECL_TIOCSRS485 911 | modbus_rtu_t *ctx_rtu = ctx->backend_data; 912 | return ctx_rtu->serial_mode; 913 | #else 914 | if (ctx->debug) { 915 | fprintf(stderr, "This function isn't supported on your platform\n"); 916 | } 917 | errno = ENOTSUP; 918 | return -1; 919 | #endif 920 | } else { 921 | errno = EINVAL; 922 | return -1; 923 | } 924 | } 925 | 926 | int modbus_rtu_get_rts(modbus_t *ctx) 927 | { 928 | if (ctx == NULL) { 929 | errno = EINVAL; 930 | return -1; 931 | } 932 | 933 | if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU) { 934 | #if HAVE_DECL_TIOCM_RTS 935 | modbus_rtu_t *ctx_rtu = ctx->backend_data; 936 | return ctx_rtu->rts; 937 | #else 938 | if (ctx->debug) { 939 | fprintf(stderr, "This function isn't supported on your platform\n"); 940 | } 941 | errno = ENOTSUP; 942 | return -1; 943 | #endif 944 | } else { 945 | errno = EINVAL; 946 | return -1; 947 | } 948 | } 949 | 950 | int modbus_rtu_set_rts(modbus_t *ctx, int rts_pin, int mode) 951 | { 952 | if (ctx == NULL) { 953 | errno = EINVAL; 954 | return -1; 955 | } 956 | 957 | if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU) { 958 | #if HAVE_DECL_TIOCM_RTS 959 | modbus_rtu_t *ctx_rtu = ctx->backend_data; 960 | 961 | if (mode == MODBUS_RTU_RTS_NONE || mode == MODBUS_RTU_RTS_UP || 962 | mode == MODBUS_RTU_RTS_DOWN) { 963 | ctx_rtu->rts_pin = rts_pin; 964 | 965 | ctx_rtu->rts = mode; 966 | 967 | /* Set the RTS bit in order to not reserve the RS485 bus */ 968 | ctx_rtu->set_rts(ctx, ctx_rtu->rts != MODBUS_RTU_RTS_UP); 969 | 970 | return 0; 971 | } else { 972 | errno = EINVAL; 973 | return -1; 974 | } 975 | #else 976 | if (ctx->debug) { 977 | fprintf(stderr, "This function isn't supported on your platform\n"); 978 | } 979 | errno = ENOTSUP; 980 | return -1; 981 | #endif 982 | } 983 | /* Wrong backend or invalid mode specified */ 984 | errno = EINVAL; 985 | return -1; 986 | } 987 | 988 | int modbus_rtu_set_custom_rts(modbus_t *ctx, void (*set_rts) (modbus_t *ctx, int on)) 989 | { 990 | if (ctx == NULL) { 991 | errno = EINVAL; 992 | return -1; 993 | } 994 | 995 | if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU) { 996 | #if HAVE_DECL_TIOCM_RTS 997 | modbus_rtu_t *ctx_rtu = ctx->backend_data; 998 | ctx_rtu->set_rts = set_rts; 999 | return 0; 1000 | #else 1001 | if (ctx->debug) { 1002 | fprintf(stderr, "This function isn't supported on your platform\n"); 1003 | } 1004 | errno = ENOTSUP; 1005 | return -1; 1006 | #endif 1007 | } else { 1008 | errno = EINVAL; 1009 | return -1; 1010 | } 1011 | } 1012 | 1013 | int modbus_rtu_get_rts_delay(modbus_t *ctx) 1014 | { 1015 | if (ctx == NULL) { 1016 | errno = EINVAL; 1017 | return -1; 1018 | } 1019 | 1020 | if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU) { 1021 | #if HAVE_DECL_TIOCM_RTS 1022 | modbus_rtu_t *ctx_rtu; 1023 | ctx_rtu = (modbus_rtu_t *)ctx->backend_data; 1024 | return ctx_rtu->rts_delay; 1025 | #else 1026 | if (ctx->debug) { 1027 | fprintf(stderr, "This function isn't supported on your platform\n"); 1028 | } 1029 | errno = ENOTSUP; 1030 | return -1; 1031 | #endif 1032 | } else { 1033 | errno = EINVAL; 1034 | return -1; 1035 | } 1036 | } 1037 | 1038 | int modbus_rtu_set_rts_delay(modbus_t *ctx, int us) 1039 | { 1040 | if (ctx == NULL || us < 0) { 1041 | errno = EINVAL; 1042 | return -1; 1043 | } 1044 | 1045 | if (ctx->backend->backend_type == _MODBUS_BACKEND_TYPE_RTU) { 1046 | #if HAVE_DECL_TIOCM_RTS 1047 | modbus_rtu_t *ctx_rtu; 1048 | ctx_rtu = (modbus_rtu_t *)ctx->backend_data; 1049 | ctx_rtu->rts_delay = us; 1050 | return 0; 1051 | #else 1052 | if (ctx->debug) { 1053 | fprintf(stderr, "This function isn't supported on your platform\n"); 1054 | } 1055 | errno = ENOTSUP; 1056 | return -1; 1057 | #endif 1058 | } else { 1059 | errno = EINVAL; 1060 | return -1; 1061 | } 1062 | } 1063 | 1064 | static void _modbus_rtu_close(modbus_t *ctx) 1065 | { 1066 | /* Restore line settings and close file descriptor in RTU mode */ 1067 | modbus_rtu_t *ctx_rtu = ctx->backend_data; 1068 | 1069 | #if defined(_WIN32) 1070 | /* Revert settings */ 1071 | if (!SetCommState(ctx_rtu->w_ser.fd, &ctx_rtu->old_dcb) && ctx->debug) { 1072 | fprintf(stderr, "ERROR Couldn't revert to configuration (LastError %d)\n", 1073 | (int)GetLastError()); 1074 | } 1075 | 1076 | if (!CloseHandle(ctx_rtu->w_ser.fd) && ctx->debug) { 1077 | fprintf(stderr, "ERROR Error while closing handle (LastError %d)\n", 1078 | (int)GetLastError()); 1079 | } 1080 | #else 1081 | if (ctx->s != -1) { 1082 | tcsetattr(ctx->s, TCSANOW, &ctx_rtu->old_tios); 1083 | close(ctx->s); 1084 | ctx->s = -1; 1085 | } 1086 | #endif 1087 | } 1088 | 1089 | static int _modbus_rtu_flush(modbus_t *ctx) 1090 | { 1091 | #if defined(_WIN32) 1092 | modbus_rtu_t *ctx_rtu = ctx->backend_data; 1093 | ctx_rtu->w_ser.n_bytes = 0; 1094 | return (PurgeComm(ctx_rtu->w_ser.fd, PURGE_RXCLEAR) == FALSE); 1095 | #else 1096 | return tcflush(ctx->s, TCIOFLUSH); 1097 | #endif 1098 | } 1099 | 1100 | static int _modbus_rtu_select(modbus_t *ctx, fd_set *rset, 1101 | struct timeval *tv, int length_to_read) 1102 | { 1103 | int s_rc; 1104 | #if defined(_WIN32) 1105 | s_rc = win32_ser_select(&((modbus_rtu_t *)ctx->backend_data)->w_ser, 1106 | length_to_read, tv); 1107 | if (s_rc == 0) { 1108 | errno = ETIMEDOUT; 1109 | return -1; 1110 | } 1111 | 1112 | if (s_rc < 0) { 1113 | return -1; 1114 | } 1115 | #else 1116 | while ((s_rc = select(ctx->s+1, rset, NULL, NULL, tv)) == -1) { 1117 | if (errno == EINTR) { 1118 | if (ctx->debug) { 1119 | fprintf(stderr, "A non blocked signal was caught\n"); 1120 | } 1121 | /* Necessary after an error */ 1122 | FD_ZERO(rset); 1123 | FD_SET(ctx->s, rset); 1124 | } else { 1125 | return -1; 1126 | } 1127 | } 1128 | 1129 | if (s_rc == 0) { 1130 | /* Timeout */ 1131 | errno = ETIMEDOUT; 1132 | return -1; 1133 | } 1134 | #endif 1135 | 1136 | return s_rc; 1137 | } 1138 | 1139 | static void _modbus_rtu_free(modbus_t *ctx) { 1140 | free(((modbus_rtu_t*)ctx->backend_data)->device); 1141 | free(ctx->backend_data); 1142 | free(ctx); 1143 | } 1144 | 1145 | const modbus_backend_t _modbus_rtu_backend = { 1146 | _MODBUS_BACKEND_TYPE_RTU, 1147 | _MODBUS_RTU_HEADER_LENGTH, 1148 | _MODBUS_RTU_CHECKSUM_LENGTH, 1149 | MODBUS_RTU_MAX_ADU_LENGTH, 1150 | _modbus_set_slave, 1151 | _modbus_rtu_build_request_basis, 1152 | _modbus_rtu_build_response_basis, 1153 | _modbus_rtu_prepare_response_tid, 1154 | _modbus_rtu_send_msg_pre, 1155 | _modbus_rtu_send, 1156 | _modbus_rtu_receive, 1157 | _modbus_rtu_recv, 1158 | _modbus_rtu_check_integrity, 1159 | _modbus_rtu_pre_check_confirmation, 1160 | _modbus_rtu_connect, 1161 | _modbus_rtu_close, 1162 | _modbus_rtu_flush, 1163 | _modbus_rtu_select, 1164 | _modbus_rtu_free 1165 | }; 1166 | 1167 | modbus_t* modbus_new_rtu(const char *device, 1168 | int baud, char parity, int data_bit, 1169 | int stop_bit) 1170 | { 1171 | modbus_t *ctx; 1172 | modbus_rtu_t *ctx_rtu; 1173 | 1174 | /* Check device argument */ 1175 | if (device == NULL || *device == 0) { 1176 | fprintf(stderr, "The device string is empty\n"); 1177 | errno = EINVAL; 1178 | return NULL; 1179 | } 1180 | 1181 | /* Check baud argument */ 1182 | if (baud == 0) { 1183 | fprintf(stderr, "The baud rate value must not be zero\n"); 1184 | errno = EINVAL; 1185 | return NULL; 1186 | } 1187 | 1188 | ctx = (modbus_t *)malloc(sizeof(modbus_t)); 1189 | _modbus_init_common(ctx); 1190 | ctx->backend = &_modbus_rtu_backend; 1191 | ctx->backend_data = (modbus_rtu_t *)malloc(sizeof(modbus_rtu_t)); 1192 | ctx_rtu = (modbus_rtu_t *)ctx->backend_data; 1193 | ctx_rtu->device = NULL; 1194 | 1195 | /* Device name and \0 */ 1196 | ctx_rtu->device = (char *)malloc((strlen(device) + 1) * sizeof(char)); 1197 | strcpy(ctx_rtu->device, device); 1198 | 1199 | ctx_rtu->baud = baud; 1200 | if (parity == 'N' || parity == 'E' || parity == 'O') { 1201 | ctx_rtu->parity = parity; 1202 | } else { 1203 | modbus_free(ctx); 1204 | errno = EINVAL; 1205 | return NULL; 1206 | } 1207 | ctx_rtu->data_bit = data_bit; 1208 | ctx_rtu->stop_bit = stop_bit; 1209 | 1210 | #if HAVE_DECL_TIOCSRS485 1211 | /* The RS232 mode has been set by default */ 1212 | ctx_rtu->serial_mode = MODBUS_RTU_RS232; 1213 | #endif 1214 | 1215 | #if HAVE_DECL_TIOCM_RTS 1216 | /* The RTS use has been set by default */ 1217 | ctx_rtu->rts = MODBUS_RTU_RTS_NONE; 1218 | 1219 | /* Calculate estimated time in micro second to send one byte */ 1220 | ctx_rtu->onebyte_time = 1000000 * (1 + data_bit + (parity == 'N' ? 0 : 1) + stop_bit) / baud; 1221 | 1222 | ctx_rtu->rts_pin = 0; 1223 | 1224 | /* The internal function is used by default to set RTS */ 1225 | ctx_rtu->set_rts = _modbus_rtu_ioctl_rts; 1226 | 1227 | /* The delay before and after transmission when toggling the RTS pin */ 1228 | ctx_rtu->rts_delay = ctx_rtu->onebyte_time; 1229 | #endif 1230 | 1231 | return ctx; 1232 | } 1233 | -------------------------------------------------------------------------------- /src/modbus.c: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2001-2011 Stéphane Raimbault 3 | * 4 | * SPDX-License-Identifier: LGPL-2.1+ 5 | * 6 | * This library implements the Modbus protocol. 7 | * http://libmodbus.org/ 8 | */ 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #ifndef _MSC_VER 18 | #include 19 | #endif 20 | 21 | #include 22 | #include 23 | 24 | #include "modbus.h" 25 | #include "modbus-private.h" 26 | 27 | /* Internal use */ 28 | #define MSG_LENGTH_UNDEFINED -1 29 | 30 | /* Exported version */ 31 | const unsigned int libmodbus_version_major = LIBMODBUS_VERSION_MAJOR; 32 | const unsigned int libmodbus_version_minor = LIBMODBUS_VERSION_MINOR; 33 | const unsigned int libmodbus_version_micro = LIBMODBUS_VERSION_MICRO; 34 | 35 | /* Max between RTU and TCP max adu length (so TCP) */ 36 | #define MAX_MESSAGE_LENGTH 260 37 | 38 | /* 3 steps are used to parse the query */ 39 | typedef enum { 40 | _STEP_FUNCTION, 41 | _STEP_META, 42 | _STEP_DATA 43 | } _step_t; 44 | 45 | const char *modbus_strerror(int errnum) { 46 | switch (errnum) { 47 | case EMBXILFUN: 48 | return "Illegal function"; 49 | case EMBXILADD: 50 | return "Illegal data address"; 51 | case EMBXILVAL: 52 | return "Illegal data value"; 53 | case EMBXSFAIL: 54 | return "Slave device or server failure"; 55 | case EMBXACK: 56 | return "Acknowledge"; 57 | case EMBXSBUSY: 58 | return "Slave device or server is busy"; 59 | case EMBXNACK: 60 | return "Negative acknowledge"; 61 | case EMBXMEMPAR: 62 | return "Memory parity error"; 63 | case EMBXGPATH: 64 | return "Gateway path unavailable"; 65 | case EMBXGTAR: 66 | return "Target device failed to respond"; 67 | case EMBBADCRC: 68 | return "Invalid CRC"; 69 | case EMBBADDATA: 70 | return "Invalid data"; 71 | case EMBBADEXC: 72 | return "Invalid exception code"; 73 | case EMBMDATA: 74 | return "Too many data"; 75 | case EMBBADSLAVE: 76 | return "Response not from requested slave"; 77 | default: 78 | return strerror(errnum); 79 | } 80 | } 81 | 82 | void _error_print(modbus_t *ctx, const char *context) 83 | { 84 | if (ctx->debug) { 85 | fprintf(stderr, "ERROR %s", modbus_strerror(errno)); 86 | if (context != NULL) { 87 | fprintf(stderr, ": %s\n", context); 88 | } else { 89 | fprintf(stderr, "\n"); 90 | } 91 | } 92 | } 93 | 94 | static void _sleep_response_timeout(modbus_t *ctx) 95 | { 96 | /* Response timeout is always positive */ 97 | #ifdef _WIN32 98 | /* usleep doesn't exist on Windows */ 99 | Sleep((ctx->response_timeout.tv_sec * 1000) + 100 | (ctx->response_timeout.tv_usec / 1000)); 101 | #else 102 | rt_thread_mdelay((ctx->response_timeout.tv_sec * 1000) + 103 | (ctx->response_timeout.tv_usec / 1000)); 104 | #endif 105 | } 106 | 107 | int modbus_flush(modbus_t *ctx) 108 | { 109 | int rc; 110 | 111 | if (ctx == NULL) { 112 | errno = EINVAL; 113 | return -1; 114 | } 115 | 116 | rc = ctx->backend->flush(ctx); 117 | if (rc != -1 && ctx->debug) { 118 | /* Not all backends are able to return the number of bytes flushed */ 119 | printf("Bytes flushed (%d)\n", rc); 120 | } 121 | return rc; 122 | } 123 | 124 | /* Computes the length of the expected response */ 125 | static unsigned int compute_response_length_from_request(modbus_t *ctx, uint8_t *req) 126 | { 127 | int length; 128 | const int offset = ctx->backend->header_length; 129 | 130 | switch (req[offset]) { 131 | case MODBUS_FC_READ_COILS: 132 | case MODBUS_FC_READ_DISCRETE_INPUTS: { 133 | /* Header + nb values (code from write_bits) */ 134 | int nb = (req[offset + 3] << 8) | req[offset + 4]; 135 | length = 2 + (nb / 8) + ((nb % 8) ? 1 : 0); 136 | } 137 | break; 138 | case MODBUS_FC_WRITE_AND_READ_REGISTERS: 139 | case MODBUS_FC_READ_HOLDING_REGISTERS: 140 | case MODBUS_FC_READ_INPUT_REGISTERS: 141 | /* Header + 2 * nb values */ 142 | length = 2 + 2 * (req[offset + 3] << 8 | req[offset + 4]); 143 | break; 144 | case MODBUS_FC_READ_EXCEPTION_STATUS: 145 | length = 3; 146 | break; 147 | case MODBUS_FC_REPORT_SLAVE_ID: 148 | /* The response is device specific (the header provides the 149 | length) */ 150 | return MSG_LENGTH_UNDEFINED; 151 | case MODBUS_FC_MASK_WRITE_REGISTER: 152 | length = 7; 153 | break; 154 | default: 155 | length = 5; 156 | } 157 | 158 | return offset + length + ctx->backend->checksum_length; 159 | } 160 | 161 | /* Sends a request/response */ 162 | static int send_msg(modbus_t *ctx, uint8_t *msg, int msg_length) 163 | { 164 | int rc; 165 | int i; 166 | 167 | msg_length = ctx->backend->send_msg_pre(msg, msg_length); 168 | 169 | if (ctx->debug) { 170 | for (i = 0; i < msg_length; i++) 171 | printf("[%.2X]", msg[i]); 172 | printf("\n"); 173 | } 174 | 175 | /* In recovery mode, the write command will be issued until to be 176 | successful! Disabled by default. */ 177 | do { 178 | rc = ctx->backend->send(ctx, msg, msg_length); 179 | if (rc == -1) { 180 | _error_print(ctx, NULL); 181 | if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) { 182 | int saved_errno = errno; 183 | 184 | if ((errno == EBADF || errno == ECONNRESET || errno == EPIPE)) { 185 | modbus_close(ctx); 186 | _sleep_response_timeout(ctx); 187 | modbus_connect(ctx); 188 | } else { 189 | _sleep_response_timeout(ctx); 190 | modbus_flush(ctx); 191 | } 192 | errno = saved_errno; 193 | } 194 | } 195 | } while ((ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) && 196 | rc == -1); 197 | 198 | if (rc > 0 && rc != msg_length) { 199 | errno = EMBBADDATA; 200 | return -1; 201 | } 202 | 203 | return rc; 204 | } 205 | 206 | int modbus_send_raw_request(modbus_t *ctx, uint8_t *raw_req, int raw_req_length) 207 | { 208 | sft_t sft; 209 | uint8_t req[MAX_MESSAGE_LENGTH]; 210 | int req_length; 211 | 212 | if (ctx == NULL) { 213 | errno = EINVAL; 214 | return -1; 215 | } 216 | 217 | if (raw_req_length < 2 || raw_req_length > (MODBUS_MAX_PDU_LENGTH + 1)) { 218 | /* The raw request must contain function and slave at least and 219 | must not be longer than the maximum pdu length plus the slave 220 | address. */ 221 | errno = EINVAL; 222 | return -1; 223 | } 224 | 225 | sft.slave = raw_req[0]; 226 | sft.function = raw_req[1]; 227 | /* The t_id is left to zero */ 228 | sft.t_id = 0; 229 | /* This response function only set the header so it's convenient here */ 230 | req_length = ctx->backend->build_response_basis(&sft, req); 231 | 232 | if (raw_req_length > 2) { 233 | /* Copy data after function code */ 234 | memcpy(req + req_length, raw_req + 2, raw_req_length - 2); 235 | req_length += raw_req_length - 2; 236 | } 237 | 238 | return send_msg(ctx, req, req_length); 239 | } 240 | 241 | /* 242 | * ---------- Request Indication ---------- 243 | * | Client | ---------------------->| Server | 244 | * ---------- Confirmation Response ---------- 245 | */ 246 | 247 | /* Computes the length to read after the function received */ 248 | static uint8_t compute_meta_length_after_function(int function, 249 | msg_type_t msg_type) 250 | { 251 | int length; 252 | 253 | if (msg_type == MSG_INDICATION) { 254 | if (function <= MODBUS_FC_WRITE_SINGLE_REGISTER) { 255 | length = 4; 256 | } else if (function == MODBUS_FC_WRITE_MULTIPLE_COILS || 257 | function == MODBUS_FC_WRITE_MULTIPLE_REGISTERS) { 258 | length = 5; 259 | } else if (function == MODBUS_FC_MASK_WRITE_REGISTER) { 260 | length = 6; 261 | } else if (function == MODBUS_FC_WRITE_AND_READ_REGISTERS) { 262 | length = 9; 263 | } else { 264 | /* MODBUS_FC_READ_EXCEPTION_STATUS, MODBUS_FC_REPORT_SLAVE_ID */ 265 | length = 0; 266 | } 267 | } else { 268 | /* MSG_CONFIRMATION */ 269 | switch (function) { 270 | case MODBUS_FC_WRITE_SINGLE_COIL: 271 | case MODBUS_FC_WRITE_SINGLE_REGISTER: 272 | case MODBUS_FC_WRITE_MULTIPLE_COILS: 273 | case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: 274 | length = 4; 275 | break; 276 | case MODBUS_FC_MASK_WRITE_REGISTER: 277 | length = 6; 278 | break; 279 | default: 280 | length = 1; 281 | } 282 | } 283 | 284 | return length; 285 | } 286 | 287 | /* Computes the length to read after the meta information (address, count, etc) */ 288 | static int compute_data_length_after_meta(modbus_t *ctx, uint8_t *msg, 289 | msg_type_t msg_type) 290 | { 291 | int function = msg[ctx->backend->header_length]; 292 | int length; 293 | 294 | if (msg_type == MSG_INDICATION) { 295 | switch (function) { 296 | case MODBUS_FC_WRITE_MULTIPLE_COILS: 297 | case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: 298 | length = msg[ctx->backend->header_length + 5]; 299 | break; 300 | case MODBUS_FC_WRITE_AND_READ_REGISTERS: 301 | length = msg[ctx->backend->header_length + 9]; 302 | break; 303 | default: 304 | length = 0; 305 | } 306 | } else { 307 | /* MSG_CONFIRMATION */ 308 | if (function <= MODBUS_FC_READ_INPUT_REGISTERS || 309 | function == MODBUS_FC_REPORT_SLAVE_ID || 310 | function == MODBUS_FC_WRITE_AND_READ_REGISTERS) { 311 | length = msg[ctx->backend->header_length + 1]; 312 | } else { 313 | length = 0; 314 | } 315 | } 316 | 317 | length += ctx->backend->checksum_length; 318 | 319 | return length; 320 | } 321 | 322 | 323 | /* Waits a response from a modbus server or a request from a modbus client. 324 | This function blocks if there is no replies (3 timeouts). 325 | 326 | The function shall return the number of received characters and the received 327 | message in an array of uint8_t if successful. Otherwise it shall return -1 328 | and errno is set to one of the values defined below: 329 | - ECONNRESET 330 | - EMBBADDATA 331 | - EMBUNKEXC 332 | - ETIMEDOUT 333 | - read() or recv() error codes 334 | */ 335 | 336 | int _modbus_receive_msg(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type) 337 | { 338 | int rc; 339 | fd_set rset; 340 | struct timeval tv; 341 | struct timeval *p_tv; 342 | int length_to_read; 343 | int msg_length = 0; 344 | _step_t step; 345 | 346 | if (ctx->debug) { 347 | if (msg_type == MSG_INDICATION) { 348 | printf("Waiting for a indication...\n"); 349 | } else { 350 | printf("Waiting for a confirmation...\n"); 351 | } 352 | } 353 | 354 | /* Add a file descriptor to the set */ 355 | FD_ZERO(&rset); 356 | FD_SET(ctx->s, &rset); 357 | 358 | /* We need to analyse the message step by step. At the first step, we want 359 | * to reach the function code because all packets contain this 360 | * information. */ 361 | step = _STEP_FUNCTION; 362 | length_to_read = ctx->backend->header_length + 1; 363 | 364 | if (msg_type == MSG_INDICATION) { 365 | /* Wait for a message, we don't know when the message will be 366 | * received */ 367 | p_tv = NULL; 368 | } else { 369 | tv.tv_sec = ctx->response_timeout.tv_sec; 370 | tv.tv_usec = ctx->response_timeout.tv_usec; 371 | p_tv = &tv; 372 | } 373 | 374 | while (length_to_read != 0) { 375 | rc = ctx->backend->select(ctx, &rset, p_tv, length_to_read); 376 | if (rc == -1) { 377 | _error_print(ctx, "select"); 378 | if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) { 379 | int saved_errno = errno; 380 | 381 | if (errno == ETIMEDOUT) { 382 | _sleep_response_timeout(ctx); 383 | modbus_flush(ctx); 384 | } else if (errno == EBADF) { 385 | modbus_close(ctx); 386 | modbus_connect(ctx); 387 | } 388 | errno = saved_errno; 389 | } 390 | return -1; 391 | } 392 | 393 | rc = ctx->backend->recv(ctx, msg + msg_length, length_to_read); 394 | if (rc == 0) { 395 | errno = ECONNRESET; 396 | rc = -1; 397 | } 398 | 399 | if (rc == -1) { 400 | _error_print(ctx, "read"); 401 | if ((ctx->error_recovery & MODBUS_ERROR_RECOVERY_LINK) && 402 | (errno == ECONNRESET || errno == ECONNREFUSED || 403 | errno == EBADF)) { 404 | int saved_errno = errno; 405 | modbus_close(ctx); 406 | modbus_connect(ctx); 407 | /* Could be removed by previous calls */ 408 | errno = saved_errno; 409 | } 410 | return -1; 411 | } 412 | 413 | /* Display the hex code of each character received */ 414 | if (ctx->debug) { 415 | int i; 416 | for (i=0; i < rc; i++) 417 | printf("<%.2X>", msg[msg_length + i]); 418 | } 419 | 420 | /* Sums bytes received */ 421 | msg_length += rc; 422 | /* Computes remaining bytes */ 423 | length_to_read -= rc; 424 | 425 | if (length_to_read == 0) { 426 | switch (step) { 427 | case _STEP_FUNCTION: 428 | /* Function code position */ 429 | length_to_read = compute_meta_length_after_function( 430 | msg[ctx->backend->header_length], 431 | msg_type); 432 | if (length_to_read != 0) { 433 | step = _STEP_META; 434 | break; 435 | } /* else switches straight to the next step */ 436 | case _STEP_META: 437 | length_to_read = compute_data_length_after_meta( 438 | ctx, msg, msg_type); 439 | if ((msg_length + length_to_read) > (int)ctx->backend->max_adu_length) { 440 | errno = EMBBADDATA; 441 | _error_print(ctx, "too many data"); 442 | return -1; 443 | } 444 | step = _STEP_DATA; 445 | break; 446 | default: 447 | break; 448 | } 449 | } 450 | 451 | if (length_to_read > 0 && 452 | (ctx->byte_timeout.tv_sec > 0 || ctx->byte_timeout.tv_usec > 0)) { 453 | /* If there is no character in the buffer, the allowed timeout 454 | interval between two consecutive bytes is defined by 455 | byte_timeout */ 456 | tv.tv_sec = ctx->byte_timeout.tv_sec; 457 | tv.tv_usec = ctx->byte_timeout.tv_usec; 458 | p_tv = &tv; 459 | } 460 | /* else timeout isn't set again, the full response must be read before 461 | expiration of response timeout (for CONFIRMATION only) */ 462 | } 463 | 464 | if (ctx->debug) 465 | printf("\n"); 466 | 467 | return ctx->backend->check_integrity(ctx, msg, msg_length); 468 | } 469 | 470 | /* Receive the request from a modbus master */ 471 | int modbus_receive(modbus_t *ctx, uint8_t *req) 472 | { 473 | if (ctx == NULL) { 474 | errno = EINVAL; 475 | return -1; 476 | } 477 | 478 | return ctx->backend->receive(ctx, req); 479 | } 480 | 481 | /* Receives the confirmation. 482 | 483 | The function shall store the read response in rsp and return the number of 484 | values (bits or words). Otherwise, its shall return -1 and errno is set. 485 | 486 | The function doesn't check the confirmation is the expected response to the 487 | initial request. 488 | */ 489 | int modbus_receive_confirmation(modbus_t *ctx, uint8_t *rsp) 490 | { 491 | if (ctx == NULL) { 492 | errno = EINVAL; 493 | return -1; 494 | } 495 | 496 | return _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); 497 | } 498 | 499 | static int check_confirmation(modbus_t *ctx, uint8_t *req, 500 | uint8_t *rsp, int rsp_length) 501 | { 502 | int rc; 503 | int rsp_length_computed; 504 | const int offset = ctx->backend->header_length; 505 | const int function = rsp[offset]; 506 | 507 | if (ctx->backend->pre_check_confirmation) { 508 | rc = ctx->backend->pre_check_confirmation(ctx, req, rsp, rsp_length); 509 | if (rc == -1) { 510 | if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) { 511 | _sleep_response_timeout(ctx); 512 | modbus_flush(ctx); 513 | } 514 | return -1; 515 | } 516 | } 517 | 518 | rsp_length_computed = compute_response_length_from_request(ctx, req); 519 | 520 | /* Exception code */ 521 | if (function >= 0x80) { 522 | if (rsp_length == (offset + 2 + (int)ctx->backend->checksum_length) && 523 | req[offset] == (rsp[offset] - 0x80)) { 524 | /* Valid exception code received */ 525 | 526 | int exception_code = rsp[offset + 1]; 527 | if (exception_code < MODBUS_EXCEPTION_MAX) { 528 | errno = MODBUS_ENOBASE + exception_code; 529 | } else { 530 | errno = EMBBADEXC; 531 | } 532 | _error_print(ctx, NULL); 533 | return -1; 534 | } else { 535 | errno = EMBBADEXC; 536 | _error_print(ctx, NULL); 537 | return -1; 538 | } 539 | } 540 | 541 | /* Check length */ 542 | if ((rsp_length == rsp_length_computed || 543 | rsp_length_computed == MSG_LENGTH_UNDEFINED) && 544 | function < 0x80) { 545 | int req_nb_value; 546 | int rsp_nb_value; 547 | 548 | /* Check function code */ 549 | if (function != req[offset]) { 550 | if (ctx->debug) { 551 | fprintf(stderr, 552 | "Received function not corresponding to the request (0x%X != 0x%X)\n", 553 | function, req[offset]); 554 | } 555 | if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) { 556 | _sleep_response_timeout(ctx); 557 | modbus_flush(ctx); 558 | } 559 | errno = EMBBADDATA; 560 | return -1; 561 | } 562 | 563 | /* Check the number of values is corresponding to the request */ 564 | switch (function) { 565 | case MODBUS_FC_READ_COILS: 566 | case MODBUS_FC_READ_DISCRETE_INPUTS: 567 | /* Read functions, 8 values in a byte (nb 568 | * of values in the request and byte count in 569 | * the response. */ 570 | req_nb_value = (req[offset + 3] << 8) + req[offset + 4]; 571 | req_nb_value = (req_nb_value / 8) + ((req_nb_value % 8) ? 1 : 0); 572 | rsp_nb_value = rsp[offset + 1]; 573 | break; 574 | case MODBUS_FC_WRITE_AND_READ_REGISTERS: 575 | case MODBUS_FC_READ_HOLDING_REGISTERS: 576 | case MODBUS_FC_READ_INPUT_REGISTERS: 577 | /* Read functions 1 value = 2 bytes */ 578 | req_nb_value = (req[offset + 3] << 8) + req[offset + 4]; 579 | rsp_nb_value = (rsp[offset + 1] / 2); 580 | break; 581 | case MODBUS_FC_WRITE_MULTIPLE_COILS: 582 | case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: 583 | /* N Write functions */ 584 | req_nb_value = (req[offset + 3] << 8) + req[offset + 4]; 585 | rsp_nb_value = (rsp[offset + 3] << 8) | rsp[offset + 4]; 586 | break; 587 | case MODBUS_FC_REPORT_SLAVE_ID: 588 | /* Report slave ID (bytes received) */ 589 | req_nb_value = rsp_nb_value = rsp[offset + 1]; 590 | break; 591 | default: 592 | /* 1 Write functions & others */ 593 | req_nb_value = rsp_nb_value = 1; 594 | } 595 | 596 | if (req_nb_value == rsp_nb_value) { 597 | rc = rsp_nb_value; 598 | } else { 599 | if (ctx->debug) { 600 | fprintf(stderr, 601 | "Quantity not corresponding to the request (%d != %d)\n", 602 | rsp_nb_value, req_nb_value); 603 | } 604 | 605 | if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) { 606 | _sleep_response_timeout(ctx); 607 | modbus_flush(ctx); 608 | } 609 | 610 | errno = EMBBADDATA; 611 | rc = -1; 612 | } 613 | } else { 614 | if (ctx->debug) { 615 | fprintf(stderr, 616 | "Message length not corresponding to the computed length (%d != %d)\n", 617 | rsp_length, rsp_length_computed); 618 | } 619 | if (ctx->error_recovery & MODBUS_ERROR_RECOVERY_PROTOCOL) { 620 | _sleep_response_timeout(ctx); 621 | modbus_flush(ctx); 622 | } 623 | errno = EMBBADDATA; 624 | rc = -1; 625 | } 626 | 627 | return rc; 628 | } 629 | 630 | static int response_io_status(uint8_t *tab_io_status, 631 | int address, int nb, 632 | uint8_t *rsp, int offset) 633 | { 634 | int shift = 0; 635 | /* Instead of byte (not allowed in Win32) */ 636 | int one_byte = 0; 637 | int i; 638 | 639 | for (i = address; i < address + nb; i++) { 640 | one_byte |= tab_io_status[i] << shift; 641 | if (shift == 7) { 642 | /* Byte is full */ 643 | rsp[offset++] = one_byte; 644 | one_byte = shift = 0; 645 | } else { 646 | shift++; 647 | } 648 | } 649 | 650 | if (shift != 0) 651 | rsp[offset++] = one_byte; 652 | 653 | return offset; 654 | } 655 | 656 | /* Build the exception response */ 657 | static int response_exception(modbus_t *ctx, sft_t *sft, 658 | int exception_code, uint8_t *rsp, 659 | unsigned int to_flush, 660 | const char* template, ...) 661 | { 662 | int rsp_length; 663 | 664 | /* Print debug message */ 665 | if (ctx->debug) { 666 | va_list ap; 667 | 668 | va_start(ap, template); 669 | vfprintf(stderr, template, ap); 670 | va_end(ap); 671 | } 672 | 673 | /* Flush if required */ 674 | if (to_flush) { 675 | _sleep_response_timeout(ctx); 676 | modbus_flush(ctx); 677 | } 678 | 679 | /* Build exception response */ 680 | sft->function = sft->function + 0x80; 681 | rsp_length = ctx->backend->build_response_basis(sft, rsp); 682 | rsp[rsp_length++] = exception_code; 683 | 684 | return rsp_length; 685 | } 686 | 687 | /* Send a response to the received request. 688 | Analyses the request and constructs a response. 689 | 690 | If an error occurs, this function construct the response 691 | accordingly. 692 | */ 693 | int modbus_reply(modbus_t *ctx, const uint8_t *req, 694 | int req_length, modbus_mapping_t *mb_mapping) 695 | { 696 | int offset; 697 | int slave; 698 | int function; 699 | uint16_t address; 700 | uint8_t rsp[MAX_MESSAGE_LENGTH]; 701 | int rsp_length = 0; 702 | sft_t sft; 703 | 704 | if (ctx == NULL) { 705 | errno = EINVAL; 706 | return -1; 707 | } 708 | 709 | offset = ctx->backend->header_length; 710 | slave = req[offset - 1]; 711 | function = req[offset]; 712 | address = (req[offset + 1] << 8) + req[offset + 2]; 713 | 714 | sft.slave = slave; 715 | sft.function = function; 716 | sft.t_id = ctx->backend->prepare_response_tid(req, &req_length); 717 | 718 | /* Data are flushed on illegal number of values errors. */ 719 | switch (function) { 720 | case MODBUS_FC_READ_COILS: 721 | case MODBUS_FC_READ_DISCRETE_INPUTS: { 722 | unsigned int is_input = (function == MODBUS_FC_READ_DISCRETE_INPUTS); 723 | int start_bits = is_input ? mb_mapping->start_input_bits : mb_mapping->start_bits; 724 | int nb_bits = is_input ? mb_mapping->nb_input_bits : mb_mapping->nb_bits; 725 | uint8_t *tab_bits = is_input ? mb_mapping->tab_input_bits : mb_mapping->tab_bits; 726 | const char * const name = is_input ? "read_input_bits" : "read_bits"; 727 | int nb = (req[offset + 3] << 8) + req[offset + 4]; 728 | /* The mapping can be shifted to reduce memory consumption and it 729 | doesn't always start at address zero. */ 730 | int mapping_address = address - start_bits; 731 | 732 | if (nb < 1 || MODBUS_MAX_READ_BITS < nb) { 733 | rsp_length = response_exception( 734 | ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, 735 | "Illegal nb of values %d in %s (max %d)\n", 736 | nb, name, MODBUS_MAX_READ_BITS); 737 | } else if (mapping_address < 0 || (mapping_address + nb) > nb_bits) { 738 | rsp_length = response_exception( 739 | ctx, &sft, 740 | MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, 741 | "Illegal data address 0x%0X in %s\n", 742 | mapping_address < 0 ? address : address + nb, name); 743 | } else { 744 | rsp_length = ctx->backend->build_response_basis(&sft, rsp); 745 | rsp[rsp_length++] = (nb / 8) + ((nb % 8) ? 1 : 0); 746 | rsp_length = response_io_status(tab_bits, mapping_address, nb, 747 | rsp, rsp_length); 748 | } 749 | } 750 | break; 751 | case MODBUS_FC_READ_HOLDING_REGISTERS: 752 | case MODBUS_FC_READ_INPUT_REGISTERS: { 753 | unsigned int is_input = (function == MODBUS_FC_READ_INPUT_REGISTERS); 754 | int start_registers = is_input ? mb_mapping->start_input_registers : mb_mapping->start_registers; 755 | int nb_registers = is_input ? mb_mapping->nb_input_registers : mb_mapping->nb_registers; 756 | uint16_t *tab_registers = is_input ? mb_mapping->tab_input_registers : mb_mapping->tab_registers; 757 | const char * const name = is_input ? "read_input_registers" : "read_registers"; 758 | int nb = (req[offset + 3] << 8) + req[offset + 4]; 759 | /* The mapping can be shifted to reduce memory consumption and it 760 | doesn't always start at address zero. */ 761 | int mapping_address = address - start_registers; 762 | 763 | if (nb < 1 || MODBUS_MAX_READ_REGISTERS < nb) { 764 | rsp_length = response_exception( 765 | ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, 766 | "Illegal nb of values %d in %s (max %d)\n", 767 | nb, name, MODBUS_MAX_READ_REGISTERS); 768 | } else if (mapping_address < 0 || (mapping_address + nb) > nb_registers) { 769 | rsp_length = response_exception( 770 | ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, 771 | "Illegal data address 0x%0X in %s\n", 772 | mapping_address < 0 ? address : address + nb, name); 773 | } else { 774 | int i; 775 | 776 | rsp_length = ctx->backend->build_response_basis(&sft, rsp); 777 | rsp[rsp_length++] = nb << 1; 778 | for (i = mapping_address; i < mapping_address + nb; i++) { 779 | rsp[rsp_length++] = tab_registers[i] >> 8; 780 | rsp[rsp_length++] = tab_registers[i] & 0xFF; 781 | } 782 | } 783 | } 784 | break; 785 | case MODBUS_FC_WRITE_SINGLE_COIL: { 786 | int mapping_address = address - mb_mapping->start_bits; 787 | 788 | if (mapping_address < 0 || mapping_address >= mb_mapping->nb_bits) { 789 | rsp_length = response_exception( 790 | ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, 791 | "Illegal data address 0x%0X in write_bit\n", 792 | address); 793 | } else { 794 | int data = (req[offset + 3] << 8) + req[offset + 4]; 795 | 796 | if (data == 0xFF00 || data == 0x0) { 797 | mb_mapping->tab_bits[mapping_address] = data ? ON : OFF; 798 | memcpy(rsp, req, req_length); 799 | rsp_length = req_length; 800 | } else { 801 | rsp_length = response_exception( 802 | ctx, &sft, 803 | MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, FALSE, 804 | "Illegal data value 0x%0X in write_bit request at address %0X\n", 805 | data, address); 806 | } 807 | } 808 | } 809 | break; 810 | case MODBUS_FC_WRITE_SINGLE_REGISTER: { 811 | int mapping_address = address - mb_mapping->start_registers; 812 | 813 | if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) { 814 | rsp_length = response_exception( 815 | ctx, &sft, 816 | MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, 817 | "Illegal data address 0x%0X in write_register\n", 818 | address); 819 | } else { 820 | int data = (req[offset + 3] << 8) + req[offset + 4]; 821 | 822 | mb_mapping->tab_registers[mapping_address] = data; 823 | memcpy(rsp, req, req_length); 824 | rsp_length = req_length; 825 | } 826 | } 827 | break; 828 | case MODBUS_FC_WRITE_MULTIPLE_COILS: { 829 | int nb = (req[offset + 3] << 8) + req[offset + 4]; 830 | int mapping_address = address - mb_mapping->start_bits; 831 | 832 | if (nb < 1 || MODBUS_MAX_WRITE_BITS < nb) { 833 | /* May be the indication has been truncated on reading because of 834 | * invalid address (eg. nb is 0 but the request contains values to 835 | * write) so it's necessary to flush. */ 836 | rsp_length = response_exception( 837 | ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, 838 | "Illegal number of values %d in write_bits (max %d)\n", 839 | nb, MODBUS_MAX_WRITE_BITS); 840 | } else if (mapping_address < 0 || 841 | (mapping_address + nb) > mb_mapping->nb_bits) { 842 | rsp_length = response_exception( 843 | ctx, &sft, 844 | MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, 845 | "Illegal data address 0x%0X in write_bits\n", 846 | mapping_address < 0 ? address : address + nb); 847 | } else { 848 | /* 6 = byte count */ 849 | modbus_set_bits_from_bytes(mb_mapping->tab_bits, mapping_address, nb, 850 | &req[offset + 6]); 851 | 852 | rsp_length = ctx->backend->build_response_basis(&sft, rsp); 853 | /* 4 to copy the bit address (2) and the quantity of bits */ 854 | memcpy(rsp + rsp_length, req + rsp_length, 4); 855 | rsp_length += 4; 856 | } 857 | } 858 | break; 859 | case MODBUS_FC_WRITE_MULTIPLE_REGISTERS: { 860 | int nb = (req[offset + 3] << 8) + req[offset + 4]; 861 | int mapping_address = address - mb_mapping->start_registers; 862 | 863 | if (nb < 1 || MODBUS_MAX_WRITE_REGISTERS < nb) { 864 | rsp_length = response_exception( 865 | ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, 866 | "Illegal number of values %d in write_registers (max %d)\n", 867 | nb, MODBUS_MAX_WRITE_REGISTERS); 868 | } else if (mapping_address < 0 || 869 | (mapping_address + nb) > mb_mapping->nb_registers) { 870 | rsp_length = response_exception( 871 | ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, 872 | "Illegal data address 0x%0X in write_registers\n", 873 | mapping_address < 0 ? address : address + nb); 874 | } else { 875 | int i, j; 876 | for (i = mapping_address, j = 6; i < mapping_address + nb; i++, j += 2) { 877 | /* 6 and 7 = first value */ 878 | mb_mapping->tab_registers[i] = 879 | (req[offset + j] << 8) + req[offset + j + 1]; 880 | } 881 | 882 | rsp_length = ctx->backend->build_response_basis(&sft, rsp); 883 | /* 4 to copy the address (2) and the no. of registers */ 884 | memcpy(rsp + rsp_length, req + rsp_length, 4); 885 | rsp_length += 4; 886 | } 887 | } 888 | break; 889 | case MODBUS_FC_REPORT_SLAVE_ID: { 890 | int str_len; 891 | int byte_count_pos; 892 | 893 | rsp_length = ctx->backend->build_response_basis(&sft, rsp); 894 | /* Skip byte count for now */ 895 | byte_count_pos = rsp_length++; 896 | rsp[rsp_length++] = _REPORT_SLAVE_ID; 897 | /* Run indicator status to ON */ 898 | rsp[rsp_length++] = 0xFF; 899 | /* LMB + length of LIBMODBUS_VERSION_STRING */ 900 | str_len = 3 + strlen(LIBMODBUS_VERSION_STRING); 901 | memcpy(rsp + rsp_length, "LMB" LIBMODBUS_VERSION_STRING, str_len); 902 | rsp_length += str_len; 903 | rsp[byte_count_pos] = rsp_length - byte_count_pos - 1; 904 | } 905 | break; 906 | case MODBUS_FC_READ_EXCEPTION_STATUS: 907 | if (ctx->debug) { 908 | fprintf(stderr, "FIXME Not implemented\n"); 909 | } 910 | errno = ENOPROTOOPT; 911 | return -1; 912 | break; 913 | case MODBUS_FC_MASK_WRITE_REGISTER: { 914 | int mapping_address = address - mb_mapping->start_registers; 915 | 916 | if (mapping_address < 0 || mapping_address >= mb_mapping->nb_registers) { 917 | rsp_length = response_exception( 918 | ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, 919 | "Illegal data address 0x%0X in write_register\n", 920 | address); 921 | } else { 922 | uint16_t data = mb_mapping->tab_registers[mapping_address]; 923 | uint16_t and = (req[offset + 3] << 8) + req[offset + 4]; 924 | uint16_t or = (req[offset + 5] << 8) + req[offset + 6]; 925 | 926 | data = (data & and) | (or & (~and)); 927 | mb_mapping->tab_registers[mapping_address] = data; 928 | memcpy(rsp, req, req_length); 929 | rsp_length = req_length; 930 | } 931 | } 932 | break; 933 | case MODBUS_FC_WRITE_AND_READ_REGISTERS: { 934 | int nb = (req[offset + 3] << 8) + req[offset + 4]; 935 | uint16_t address_write = (req[offset + 5] << 8) + req[offset + 6]; 936 | int nb_write = (req[offset + 7] << 8) + req[offset + 8]; 937 | int nb_write_bytes = req[offset + 9]; 938 | int mapping_address = address - mb_mapping->start_registers; 939 | int mapping_address_write = address_write - mb_mapping->start_registers; 940 | 941 | if (nb_write < 1 || MODBUS_MAX_WR_WRITE_REGISTERS < nb_write || 942 | nb < 1 || MODBUS_MAX_WR_READ_REGISTERS < nb || 943 | nb_write_bytes != nb_write * 2) { 944 | rsp_length = response_exception( 945 | ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, rsp, TRUE, 946 | "Illegal nb of values (W%d, R%d) in write_and_read_registers (max W%d, R%d)\n", 947 | nb_write, nb, MODBUS_MAX_WR_WRITE_REGISTERS, MODBUS_MAX_WR_READ_REGISTERS); 948 | } else if (mapping_address < 0 || 949 | (mapping_address + nb) > mb_mapping->nb_registers || 950 | mapping_address < 0 || 951 | (mapping_address_write + nb_write) > mb_mapping->nb_registers) { 952 | rsp_length = response_exception( 953 | ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, rsp, FALSE, 954 | "Illegal data read address 0x%0X or write address 0x%0X write_and_read_registers\n", 955 | mapping_address < 0 ? address : address + nb, 956 | mapping_address_write < 0 ? address_write : address_write + nb_write); 957 | } else { 958 | int i, j; 959 | rsp_length = ctx->backend->build_response_basis(&sft, rsp); 960 | rsp[rsp_length++] = nb << 1; 961 | 962 | /* Write first. 963 | 10 and 11 are the offset of the first values to write */ 964 | for (i = mapping_address_write, j = 10; 965 | i < mapping_address_write + nb_write; i++, j += 2) { 966 | mb_mapping->tab_registers[i] = 967 | (req[offset + j] << 8) + req[offset + j + 1]; 968 | } 969 | 970 | /* and read the data for the response */ 971 | for (i = mapping_address; i < mapping_address + nb; i++) { 972 | rsp[rsp_length++] = mb_mapping->tab_registers[i] >> 8; 973 | rsp[rsp_length++] = mb_mapping->tab_registers[i] & 0xFF; 974 | } 975 | } 976 | } 977 | break; 978 | 979 | default: 980 | rsp_length = response_exception( 981 | ctx, &sft, MODBUS_EXCEPTION_ILLEGAL_FUNCTION, rsp, TRUE, 982 | "Unknown Modbus function code: 0x%0X\n", function); 983 | break; 984 | } 985 | 986 | /* Suppress any responses when the request was a broadcast */ 987 | return (slave == MODBUS_BROADCAST_ADDRESS) ? 0 : send_msg(ctx, rsp, rsp_length); 988 | } 989 | 990 | int modbus_reply_exception(modbus_t *ctx, const uint8_t *req, 991 | unsigned int exception_code) 992 | { 993 | int offset; 994 | int slave; 995 | int function; 996 | uint8_t rsp[MAX_MESSAGE_LENGTH]; 997 | int rsp_length; 998 | int dummy_length = 99; 999 | sft_t sft; 1000 | 1001 | if (ctx == NULL) { 1002 | errno = EINVAL; 1003 | return -1; 1004 | } 1005 | 1006 | offset = ctx->backend->header_length; 1007 | slave = req[offset - 1]; 1008 | function = req[offset]; 1009 | 1010 | sft.slave = slave; 1011 | sft.function = function + 0x80;; 1012 | sft.t_id = ctx->backend->prepare_response_tid(req, &dummy_length); 1013 | rsp_length = ctx->backend->build_response_basis(&sft, rsp); 1014 | 1015 | /* Positive exception code */ 1016 | if (exception_code < MODBUS_EXCEPTION_MAX) { 1017 | rsp[rsp_length++] = exception_code; 1018 | return send_msg(ctx, rsp, rsp_length); 1019 | } else { 1020 | errno = EINVAL; 1021 | return -1; 1022 | } 1023 | } 1024 | 1025 | /* Reads IO status */ 1026 | static int read_io_status(modbus_t *ctx, int function, 1027 | int addr, int nb, uint8_t *dest) 1028 | { 1029 | int rc; 1030 | int req_length; 1031 | 1032 | uint8_t req[_MIN_REQ_LENGTH]; 1033 | uint8_t rsp[MAX_MESSAGE_LENGTH]; 1034 | 1035 | req_length = ctx->backend->build_request_basis(ctx, function, addr, nb, req); 1036 | 1037 | rc = send_msg(ctx, req, req_length); 1038 | if (rc > 0) { 1039 | int i, temp, bit; 1040 | int pos = 0; 1041 | int offset; 1042 | int offset_end; 1043 | 1044 | rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); 1045 | if (rc == -1) 1046 | return -1; 1047 | 1048 | rc = check_confirmation(ctx, req, rsp, rc); 1049 | if (rc == -1) 1050 | return -1; 1051 | 1052 | offset = ctx->backend->header_length + 2; 1053 | offset_end = offset + rc; 1054 | for (i = offset; i < offset_end; i++) { 1055 | /* Shift reg hi_byte to temp */ 1056 | temp = rsp[i]; 1057 | 1058 | for (bit = 0x01; (bit & 0xff) && (pos < nb);) { 1059 | dest[pos++] = (temp & bit) ? TRUE : FALSE; 1060 | bit = bit << 1; 1061 | } 1062 | 1063 | } 1064 | } 1065 | 1066 | return rc; 1067 | } 1068 | 1069 | /* Reads the boolean status of bits and sets the array elements 1070 | in the destination to TRUE or FALSE (single bits). */ 1071 | int modbus_read_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest) 1072 | { 1073 | int rc; 1074 | 1075 | if (ctx == NULL) { 1076 | errno = EINVAL; 1077 | return -1; 1078 | } 1079 | 1080 | if (nb > MODBUS_MAX_READ_BITS) { 1081 | if (ctx->debug) { 1082 | fprintf(stderr, 1083 | "ERROR Too many bits requested (%d > %d)\n", 1084 | nb, MODBUS_MAX_READ_BITS); 1085 | } 1086 | errno = EMBMDATA; 1087 | return -1; 1088 | } 1089 | 1090 | rc = read_io_status(ctx, MODBUS_FC_READ_COILS, addr, nb, dest); 1091 | 1092 | if (rc == -1) 1093 | return -1; 1094 | else 1095 | return nb; 1096 | } 1097 | 1098 | 1099 | /* Same as modbus_read_bits but reads the remote device input table */ 1100 | int modbus_read_input_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest) 1101 | { 1102 | int rc; 1103 | 1104 | if (ctx == NULL) { 1105 | errno = EINVAL; 1106 | return -1; 1107 | } 1108 | 1109 | if (nb > MODBUS_MAX_READ_BITS) { 1110 | if (ctx->debug) { 1111 | fprintf(stderr, 1112 | "ERROR Too many discrete inputs requested (%d > %d)\n", 1113 | nb, MODBUS_MAX_READ_BITS); 1114 | } 1115 | errno = EMBMDATA; 1116 | return -1; 1117 | } 1118 | 1119 | rc = read_io_status(ctx, MODBUS_FC_READ_DISCRETE_INPUTS, addr, nb, dest); 1120 | 1121 | if (rc == -1) 1122 | return -1; 1123 | else 1124 | return nb; 1125 | } 1126 | 1127 | /* Reads the data from a remove device and put that data into an array */ 1128 | static int read_registers(modbus_t *ctx, int function, int addr, int nb, 1129 | uint16_t *dest) 1130 | { 1131 | int rc; 1132 | int req_length; 1133 | uint8_t req[_MIN_REQ_LENGTH]; 1134 | uint8_t rsp[MAX_MESSAGE_LENGTH]; 1135 | 1136 | if (nb > MODBUS_MAX_READ_REGISTERS) { 1137 | if (ctx->debug) { 1138 | fprintf(stderr, 1139 | "ERROR Too many registers requested (%d > %d)\n", 1140 | nb, MODBUS_MAX_READ_REGISTERS); 1141 | } 1142 | errno = EMBMDATA; 1143 | return -1; 1144 | } 1145 | 1146 | req_length = ctx->backend->build_request_basis(ctx, function, addr, nb, req); 1147 | 1148 | rc = send_msg(ctx, req, req_length); 1149 | if (rc > 0) { 1150 | int offset; 1151 | int i; 1152 | 1153 | rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); 1154 | if (rc == -1) 1155 | return -1; 1156 | 1157 | rc = check_confirmation(ctx, req, rsp, rc); 1158 | if (rc == -1) 1159 | return -1; 1160 | 1161 | offset = ctx->backend->header_length; 1162 | 1163 | for (i = 0; i < rc; i++) { 1164 | /* shift reg hi_byte to temp OR with lo_byte */ 1165 | dest[i] = (rsp[offset + 2 + (i << 1)] << 8) | 1166 | rsp[offset + 3 + (i << 1)]; 1167 | } 1168 | } 1169 | 1170 | return rc; 1171 | } 1172 | 1173 | /* Reads the holding registers of remote device and put the data into an 1174 | array */ 1175 | int modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest) 1176 | { 1177 | int status; 1178 | 1179 | if (ctx == NULL) { 1180 | errno = EINVAL; 1181 | return -1; 1182 | } 1183 | 1184 | if (nb > MODBUS_MAX_READ_REGISTERS) { 1185 | if (ctx->debug) { 1186 | fprintf(stderr, 1187 | "ERROR Too many registers requested (%d > %d)\n", 1188 | nb, MODBUS_MAX_READ_REGISTERS); 1189 | } 1190 | errno = EMBMDATA; 1191 | return -1; 1192 | } 1193 | 1194 | status = read_registers(ctx, MODBUS_FC_READ_HOLDING_REGISTERS, 1195 | addr, nb, dest); 1196 | return status; 1197 | } 1198 | 1199 | /* Reads the input registers of remote device and put the data into an array */ 1200 | int modbus_read_input_registers(modbus_t *ctx, int addr, int nb, 1201 | uint16_t *dest) 1202 | { 1203 | int status; 1204 | 1205 | if (ctx == NULL) { 1206 | errno = EINVAL; 1207 | return -1; 1208 | } 1209 | 1210 | if (nb > MODBUS_MAX_READ_REGISTERS) { 1211 | fprintf(stderr, 1212 | "ERROR Too many input registers requested (%d > %d)\n", 1213 | nb, MODBUS_MAX_READ_REGISTERS); 1214 | errno = EMBMDATA; 1215 | return -1; 1216 | } 1217 | 1218 | status = read_registers(ctx, MODBUS_FC_READ_INPUT_REGISTERS, 1219 | addr, nb, dest); 1220 | 1221 | return status; 1222 | } 1223 | 1224 | /* Write a value to the specified register of the remote device. 1225 | Used by write_bit and write_register */ 1226 | static int write_single(modbus_t *ctx, int function, int addr, int value) 1227 | { 1228 | int rc; 1229 | int req_length; 1230 | uint8_t req[_MIN_REQ_LENGTH]; 1231 | 1232 | if (ctx == NULL) { 1233 | errno = EINVAL; 1234 | return -1; 1235 | } 1236 | 1237 | req_length = ctx->backend->build_request_basis(ctx, function, addr, value, req); 1238 | 1239 | rc = send_msg(ctx, req, req_length); 1240 | if (rc > 0) { 1241 | /* Used by write_bit and write_register */ 1242 | uint8_t rsp[MAX_MESSAGE_LENGTH]; 1243 | 1244 | rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); 1245 | if (rc == -1) 1246 | return -1; 1247 | 1248 | rc = check_confirmation(ctx, req, rsp, rc); 1249 | } 1250 | 1251 | return rc; 1252 | } 1253 | 1254 | /* Turns ON or OFF a single bit of the remote device */ 1255 | int modbus_write_bit(modbus_t *ctx, int addr, int status) 1256 | { 1257 | if (ctx == NULL) { 1258 | errno = EINVAL; 1259 | return -1; 1260 | } 1261 | 1262 | return write_single(ctx, MODBUS_FC_WRITE_SINGLE_COIL, addr, 1263 | status ? 0xFF00 : 0); 1264 | } 1265 | 1266 | /* Writes a value in one register of the remote device */ 1267 | int modbus_write_register(modbus_t *ctx, int addr, int value) 1268 | { 1269 | if (ctx == NULL) { 1270 | errno = EINVAL; 1271 | return -1; 1272 | } 1273 | 1274 | return write_single(ctx, MODBUS_FC_WRITE_SINGLE_REGISTER, addr, value); 1275 | } 1276 | 1277 | /* Write the bits of the array in the remote device */ 1278 | int modbus_write_bits(modbus_t *ctx, int addr, int nb, const uint8_t *src) 1279 | { 1280 | int rc; 1281 | int i; 1282 | int byte_count; 1283 | int req_length; 1284 | int bit_check = 0; 1285 | int pos = 0; 1286 | uint8_t req[MAX_MESSAGE_LENGTH]; 1287 | 1288 | if (ctx == NULL) { 1289 | errno = EINVAL; 1290 | return -1; 1291 | } 1292 | 1293 | if (nb > MODBUS_MAX_WRITE_BITS) { 1294 | if (ctx->debug) { 1295 | fprintf(stderr, "ERROR Writing too many bits (%d > %d)\n", 1296 | nb, MODBUS_MAX_WRITE_BITS); 1297 | } 1298 | errno = EMBMDATA; 1299 | return -1; 1300 | } 1301 | 1302 | req_length = ctx->backend->build_request_basis(ctx, 1303 | MODBUS_FC_WRITE_MULTIPLE_COILS, 1304 | addr, nb, req); 1305 | byte_count = (nb / 8) + ((nb % 8) ? 1 : 0); 1306 | req[req_length++] = byte_count; 1307 | 1308 | for (i = 0; i < byte_count; i++) { 1309 | int bit; 1310 | 1311 | bit = 0x01; 1312 | req[req_length] = 0; 1313 | 1314 | while ((bit & 0xFF) && (bit_check++ < nb)) { 1315 | if (src[pos++]) 1316 | req[req_length] |= bit; 1317 | else 1318 | req[req_length] &=~ bit; 1319 | 1320 | bit = bit << 1; 1321 | } 1322 | req_length++; 1323 | } 1324 | 1325 | rc = send_msg(ctx, req, req_length); 1326 | if (rc > 0) { 1327 | uint8_t rsp[MAX_MESSAGE_LENGTH]; 1328 | 1329 | rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); 1330 | if (rc == -1) 1331 | return -1; 1332 | 1333 | rc = check_confirmation(ctx, req, rsp, rc); 1334 | } 1335 | 1336 | 1337 | return rc; 1338 | } 1339 | 1340 | /* Write the values from the array to the registers of the remote device */ 1341 | int modbus_write_registers(modbus_t *ctx, int addr, int nb, const uint16_t *src) 1342 | { 1343 | int rc; 1344 | int i; 1345 | int req_length; 1346 | int byte_count; 1347 | uint8_t req[MAX_MESSAGE_LENGTH]; 1348 | 1349 | if (ctx == NULL) { 1350 | errno = EINVAL; 1351 | return -1; 1352 | } 1353 | 1354 | if (nb > MODBUS_MAX_WRITE_REGISTERS) { 1355 | if (ctx->debug) { 1356 | fprintf(stderr, 1357 | "ERROR Trying to write to too many registers (%d > %d)\n", 1358 | nb, MODBUS_MAX_WRITE_REGISTERS); 1359 | } 1360 | errno = EMBMDATA; 1361 | return -1; 1362 | } 1363 | 1364 | req_length = ctx->backend->build_request_basis(ctx, 1365 | MODBUS_FC_WRITE_MULTIPLE_REGISTERS, 1366 | addr, nb, req); 1367 | byte_count = nb * 2; 1368 | req[req_length++] = byte_count; 1369 | 1370 | for (i = 0; i < nb; i++) { 1371 | req[req_length++] = src[i] >> 8; 1372 | req[req_length++] = src[i] & 0x00FF; 1373 | } 1374 | 1375 | rc = send_msg(ctx, req, req_length); 1376 | if (rc > 0) { 1377 | uint8_t rsp[MAX_MESSAGE_LENGTH]; 1378 | 1379 | rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); 1380 | if (rc == -1) 1381 | return -1; 1382 | 1383 | rc = check_confirmation(ctx, req, rsp, rc); 1384 | } 1385 | 1386 | return rc; 1387 | } 1388 | 1389 | int modbus_mask_write_register(modbus_t *ctx, int addr, uint16_t and_mask, uint16_t or_mask) 1390 | { 1391 | int rc; 1392 | int req_length; 1393 | /* The request length can not exceed _MIN_REQ_LENGTH - 2 and 4 bytes to 1394 | * store the masks. The ugly substraction is there to remove the 'nb' value 1395 | * (2 bytes) which is not used. */ 1396 | uint8_t req[_MIN_REQ_LENGTH + 2]; 1397 | 1398 | req_length = ctx->backend->build_request_basis(ctx, 1399 | MODBUS_FC_MASK_WRITE_REGISTER, 1400 | addr, 0, req); 1401 | 1402 | /* HACKISH, count is not used */ 1403 | req_length -= 2; 1404 | 1405 | req[req_length++] = and_mask >> 8; 1406 | req[req_length++] = and_mask & 0x00ff; 1407 | req[req_length++] = or_mask >> 8; 1408 | req[req_length++] = or_mask & 0x00ff; 1409 | 1410 | rc = send_msg(ctx, req, req_length); 1411 | if (rc > 0) { 1412 | /* Used by write_bit and write_register */ 1413 | uint8_t rsp[MAX_MESSAGE_LENGTH]; 1414 | 1415 | rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); 1416 | if (rc == -1) 1417 | return -1; 1418 | 1419 | rc = check_confirmation(ctx, req, rsp, rc); 1420 | } 1421 | 1422 | return rc; 1423 | } 1424 | 1425 | /* Write multiple registers from src array to remote device and read multiple 1426 | registers from remote device to dest array. */ 1427 | int modbus_write_and_read_registers(modbus_t *ctx, 1428 | int write_addr, int write_nb, 1429 | const uint16_t *src, 1430 | int read_addr, int read_nb, 1431 | uint16_t *dest) 1432 | 1433 | { 1434 | int rc; 1435 | int req_length; 1436 | int i; 1437 | int byte_count; 1438 | uint8_t req[MAX_MESSAGE_LENGTH]; 1439 | uint8_t rsp[MAX_MESSAGE_LENGTH]; 1440 | 1441 | if (ctx == NULL) { 1442 | errno = EINVAL; 1443 | return -1; 1444 | } 1445 | 1446 | if (write_nb > MODBUS_MAX_WR_WRITE_REGISTERS) { 1447 | if (ctx->debug) { 1448 | fprintf(stderr, 1449 | "ERROR Too many registers to write (%d > %d)\n", 1450 | write_nb, MODBUS_MAX_WR_WRITE_REGISTERS); 1451 | } 1452 | errno = EMBMDATA; 1453 | return -1; 1454 | } 1455 | 1456 | if (read_nb > MODBUS_MAX_WR_READ_REGISTERS) { 1457 | if (ctx->debug) { 1458 | fprintf(stderr, 1459 | "ERROR Too many registers requested (%d > %d)\n", 1460 | read_nb, MODBUS_MAX_WR_READ_REGISTERS); 1461 | } 1462 | errno = EMBMDATA; 1463 | return -1; 1464 | } 1465 | req_length = ctx->backend->build_request_basis(ctx, 1466 | MODBUS_FC_WRITE_AND_READ_REGISTERS, 1467 | read_addr, read_nb, req); 1468 | 1469 | req[req_length++] = write_addr >> 8; 1470 | req[req_length++] = write_addr & 0x00ff; 1471 | req[req_length++] = write_nb >> 8; 1472 | req[req_length++] = write_nb & 0x00ff; 1473 | byte_count = write_nb * 2; 1474 | req[req_length++] = byte_count; 1475 | 1476 | for (i = 0; i < write_nb; i++) { 1477 | req[req_length++] = src[i] >> 8; 1478 | req[req_length++] = src[i] & 0x00FF; 1479 | } 1480 | 1481 | rc = send_msg(ctx, req, req_length); 1482 | if (rc > 0) { 1483 | int offset; 1484 | 1485 | rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); 1486 | if (rc == -1) 1487 | return -1; 1488 | 1489 | rc = check_confirmation(ctx, req, rsp, rc); 1490 | if (rc == -1) 1491 | return -1; 1492 | 1493 | offset = ctx->backend->header_length; 1494 | for (i = 0; i < rc; i++) { 1495 | /* shift reg hi_byte to temp OR with lo_byte */ 1496 | dest[i] = (rsp[offset + 2 + (i << 1)] << 8) | 1497 | rsp[offset + 3 + (i << 1)]; 1498 | } 1499 | } 1500 | 1501 | return rc; 1502 | } 1503 | 1504 | /* Send a request to get the slave ID of the device (only available in serial 1505 | communication). */ 1506 | int modbus_report_slave_id(modbus_t *ctx, int max_dest, uint8_t *dest) 1507 | { 1508 | int rc; 1509 | int req_length; 1510 | uint8_t req[_MIN_REQ_LENGTH]; 1511 | 1512 | if (ctx == NULL || max_dest <= 0) { 1513 | errno = EINVAL; 1514 | return -1; 1515 | } 1516 | 1517 | req_length = ctx->backend->build_request_basis(ctx, MODBUS_FC_REPORT_SLAVE_ID, 1518 | 0, 0, req); 1519 | 1520 | /* HACKISH, addr and count are not used */ 1521 | req_length -= 4; 1522 | 1523 | rc = send_msg(ctx, req, req_length); 1524 | if (rc > 0) { 1525 | int i; 1526 | int offset; 1527 | uint8_t rsp[MAX_MESSAGE_LENGTH]; 1528 | 1529 | rc = _modbus_receive_msg(ctx, rsp, MSG_CONFIRMATION); 1530 | if (rc == -1) 1531 | return -1; 1532 | 1533 | rc = check_confirmation(ctx, req, rsp, rc); 1534 | if (rc == -1) 1535 | return -1; 1536 | 1537 | offset = ctx->backend->header_length + 2; 1538 | 1539 | /* Byte count, slave id, run indicator status and 1540 | additional data. Truncate copy to max_dest. */ 1541 | for (i=0; i < rc && i < max_dest; i++) { 1542 | dest[i] = rsp[offset + i]; 1543 | } 1544 | } 1545 | 1546 | return rc; 1547 | } 1548 | 1549 | void _modbus_init_common(modbus_t *ctx) 1550 | { 1551 | /* Slave and socket are initialized to -1 */ 1552 | ctx->slave = -1; 1553 | ctx->s = -1; 1554 | 1555 | ctx->debug = FALSE; 1556 | ctx->error_recovery = MODBUS_ERROR_RECOVERY_NONE; 1557 | 1558 | ctx->response_timeout.tv_sec = 0; 1559 | ctx->response_timeout.tv_usec = _RESPONSE_TIMEOUT; 1560 | 1561 | ctx->byte_timeout.tv_sec = 0; 1562 | ctx->byte_timeout.tv_usec = _BYTE_TIMEOUT; 1563 | } 1564 | 1565 | /* Define the slave number */ 1566 | int modbus_set_slave(modbus_t *ctx, int slave) 1567 | { 1568 | if (ctx == NULL) { 1569 | errno = EINVAL; 1570 | return -1; 1571 | } 1572 | 1573 | return ctx->backend->set_slave(ctx, slave); 1574 | } 1575 | 1576 | int modbus_set_error_recovery(modbus_t *ctx, 1577 | modbus_error_recovery_mode error_recovery) 1578 | { 1579 | if (ctx == NULL) { 1580 | errno = EINVAL; 1581 | return -1; 1582 | } 1583 | 1584 | /* The type of modbus_error_recovery_mode is unsigned enum */ 1585 | ctx->error_recovery = (uint8_t) error_recovery; 1586 | return 0; 1587 | } 1588 | 1589 | int modbus_set_socket(modbus_t *ctx, int s) 1590 | { 1591 | if (ctx == NULL) { 1592 | errno = EINVAL; 1593 | return -1; 1594 | } 1595 | 1596 | ctx->s = s; 1597 | return 0; 1598 | } 1599 | 1600 | int modbus_get_socket(modbus_t *ctx) 1601 | { 1602 | if (ctx == NULL) { 1603 | errno = EINVAL; 1604 | return -1; 1605 | } 1606 | 1607 | return ctx->s; 1608 | } 1609 | 1610 | /* Get the timeout interval used to wait for a response */ 1611 | int modbus_get_response_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec) 1612 | { 1613 | if (ctx == NULL) { 1614 | errno = EINVAL; 1615 | return -1; 1616 | } 1617 | 1618 | *to_sec = ctx->response_timeout.tv_sec; 1619 | *to_usec = ctx->response_timeout.tv_usec; 1620 | return 0; 1621 | } 1622 | 1623 | int modbus_set_response_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec) 1624 | { 1625 | if (ctx == NULL || 1626 | (to_sec == 0 && to_usec == 0) || to_usec > 999999) { 1627 | errno = EINVAL; 1628 | return -1; 1629 | } 1630 | 1631 | ctx->response_timeout.tv_sec = to_sec; 1632 | ctx->response_timeout.tv_usec = to_usec; 1633 | return 0; 1634 | } 1635 | 1636 | /* Get the timeout interval between two consecutive bytes of a message */ 1637 | int modbus_get_byte_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec) 1638 | { 1639 | if (ctx == NULL) { 1640 | errno = EINVAL; 1641 | return -1; 1642 | } 1643 | 1644 | *to_sec = ctx->byte_timeout.tv_sec; 1645 | *to_usec = ctx->byte_timeout.tv_usec; 1646 | return 0; 1647 | } 1648 | 1649 | int modbus_set_byte_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec) 1650 | { 1651 | /* Byte timeout can be disabled when both values are zero */ 1652 | if (ctx == NULL || to_usec > 999999) { 1653 | errno = EINVAL; 1654 | return -1; 1655 | } 1656 | 1657 | ctx->byte_timeout.tv_sec = to_sec; 1658 | ctx->byte_timeout.tv_usec = to_usec; 1659 | return 0; 1660 | } 1661 | 1662 | int modbus_get_header_length(modbus_t *ctx) 1663 | { 1664 | if (ctx == NULL) { 1665 | errno = EINVAL; 1666 | return -1; 1667 | } 1668 | 1669 | return ctx->backend->header_length; 1670 | } 1671 | 1672 | int modbus_connect(modbus_t *ctx) 1673 | { 1674 | if (ctx == NULL) { 1675 | errno = EINVAL; 1676 | return -1; 1677 | } 1678 | 1679 | return ctx->backend->connect(ctx); 1680 | } 1681 | 1682 | void modbus_close(modbus_t *ctx) 1683 | { 1684 | if (ctx == NULL) 1685 | return; 1686 | 1687 | ctx->backend->close(ctx); 1688 | } 1689 | 1690 | void modbus_free(modbus_t *ctx) 1691 | { 1692 | if (ctx == NULL) 1693 | return; 1694 | 1695 | ctx->backend->free(ctx); 1696 | } 1697 | 1698 | int modbus_set_debug(modbus_t *ctx, int flag) 1699 | { 1700 | if (ctx == NULL) { 1701 | errno = EINVAL; 1702 | return -1; 1703 | } 1704 | 1705 | ctx->debug = flag; 1706 | return 0; 1707 | } 1708 | 1709 | /* Allocates 4 arrays to store bits, input bits, registers and inputs 1710 | registers. The pointers are stored in modbus_mapping structure. 1711 | 1712 | The modbus_mapping_new_ranges() function shall return the new allocated 1713 | structure if successful. Otherwise it shall return NULL and set errno to 1714 | ENOMEM. */ 1715 | modbus_mapping_t* modbus_mapping_new_start_address( 1716 | unsigned int start_bits, unsigned int nb_bits, 1717 | unsigned int start_input_bits, unsigned int nb_input_bits, 1718 | unsigned int start_registers, unsigned int nb_registers, 1719 | unsigned int start_input_registers, unsigned int nb_input_registers) 1720 | { 1721 | modbus_mapping_t *mb_mapping; 1722 | 1723 | mb_mapping = (modbus_mapping_t *)malloc(sizeof(modbus_mapping_t)); 1724 | if (mb_mapping == NULL) { 1725 | return NULL; 1726 | } 1727 | 1728 | /* 0X */ 1729 | mb_mapping->nb_bits = nb_bits; 1730 | mb_mapping->start_bits = start_bits; 1731 | if (nb_bits == 0) { 1732 | mb_mapping->tab_bits = NULL; 1733 | } else { 1734 | /* Negative number raises a POSIX error */ 1735 | mb_mapping->tab_bits = 1736 | (uint8_t *) malloc(nb_bits * sizeof(uint8_t)); 1737 | if (mb_mapping->tab_bits == NULL) { 1738 | free(mb_mapping); 1739 | return NULL; 1740 | } 1741 | memset(mb_mapping->tab_bits, 0, nb_bits * sizeof(uint8_t)); 1742 | } 1743 | 1744 | /* 1X */ 1745 | mb_mapping->nb_input_bits = nb_input_bits; 1746 | mb_mapping->start_input_bits = start_input_bits; 1747 | if (nb_input_bits == 0) { 1748 | mb_mapping->tab_input_bits = NULL; 1749 | } else { 1750 | mb_mapping->tab_input_bits = 1751 | (uint8_t *) malloc(nb_input_bits * sizeof(uint8_t)); 1752 | if (mb_mapping->tab_input_bits == NULL) { 1753 | free(mb_mapping->tab_bits); 1754 | free(mb_mapping); 1755 | return NULL; 1756 | } 1757 | memset(mb_mapping->tab_input_bits, 0, nb_input_bits * sizeof(uint8_t)); 1758 | } 1759 | 1760 | /* 4X */ 1761 | mb_mapping->nb_registers = nb_registers; 1762 | mb_mapping->start_registers = start_registers; 1763 | if (nb_registers == 0) { 1764 | mb_mapping->tab_registers = NULL; 1765 | } else { 1766 | mb_mapping->tab_registers = 1767 | (uint16_t *) malloc(nb_registers * sizeof(uint16_t)); 1768 | if (mb_mapping->tab_registers == NULL) { 1769 | free(mb_mapping->tab_input_bits); 1770 | free(mb_mapping->tab_bits); 1771 | free(mb_mapping); 1772 | return NULL; 1773 | } 1774 | memset(mb_mapping->tab_registers, 0, nb_registers * sizeof(uint16_t)); 1775 | } 1776 | 1777 | /* 3X */ 1778 | mb_mapping->nb_input_registers = nb_input_registers; 1779 | mb_mapping->start_input_registers = start_input_registers; 1780 | if (nb_input_registers == 0) { 1781 | mb_mapping->tab_input_registers = NULL; 1782 | } else { 1783 | mb_mapping->tab_input_registers = 1784 | (uint16_t *) malloc(nb_input_registers * sizeof(uint16_t)); 1785 | if (mb_mapping->tab_input_registers == NULL) { 1786 | free(mb_mapping->tab_registers); 1787 | free(mb_mapping->tab_input_bits); 1788 | free(mb_mapping->tab_bits); 1789 | free(mb_mapping); 1790 | return NULL; 1791 | } 1792 | memset(mb_mapping->tab_input_registers, 0, 1793 | nb_input_registers * sizeof(uint16_t)); 1794 | } 1795 | 1796 | return mb_mapping; 1797 | } 1798 | 1799 | modbus_mapping_t* modbus_mapping_new(int nb_bits, int nb_input_bits, 1800 | int nb_registers, int nb_input_registers) 1801 | { 1802 | return modbus_mapping_new_start_address( 1803 | 0, nb_bits, 0, nb_input_bits, 0, nb_registers, 0, nb_input_registers); 1804 | } 1805 | 1806 | /* Frees the 4 arrays */ 1807 | void modbus_mapping_free(modbus_mapping_t *mb_mapping) 1808 | { 1809 | if (mb_mapping == NULL) { 1810 | return; 1811 | } 1812 | 1813 | free(mb_mapping->tab_input_registers); 1814 | free(mb_mapping->tab_registers); 1815 | free(mb_mapping->tab_input_bits); 1816 | free(mb_mapping->tab_bits); 1817 | free(mb_mapping); 1818 | } 1819 | 1820 | #ifndef HAVE_STRLCPY 1821 | /* 1822 | * Function strlcpy was originally developed by 1823 | * Todd C. Miller to simplify writing secure code. 1824 | * See ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/strlcpy.3 1825 | * for more information. 1826 | * 1827 | * Thank you Ulrich Drepper... not! 1828 | * 1829 | * Copy src to string dest of size dest_size. At most dest_size-1 characters 1830 | * will be copied. Always NUL terminates (unless dest_size == 0). Returns 1831 | * strlen(src); if retval >= dest_size, truncation occurred. 1832 | */ 1833 | size_t strlcpy(char *dest, const char *src, size_t dest_size) 1834 | { 1835 | register char *d = dest; 1836 | register const char *s = src; 1837 | register size_t n = dest_size; 1838 | 1839 | /* Copy as many bytes as will fit */ 1840 | if (n != 0 && --n != 0) { 1841 | do { 1842 | if ((*d++ = *s++) == 0) 1843 | break; 1844 | } while (--n != 0); 1845 | } 1846 | 1847 | /* Not enough room in dest, add NUL and traverse rest of src */ 1848 | if (n == 0) { 1849 | if (dest_size != 0) 1850 | *d = '\0'; /* NUL-terminate dest */ 1851 | while (*s++) 1852 | ; 1853 | } 1854 | 1855 | return (s - src - 1); /* count does not include NUL */ 1856 | } 1857 | #endif 1858 | --------------------------------------------------------------------------------