diff --git a/CMakeLists.txt b/CMakeLists.txt index 979d485..251780f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,6 +42,10 @@ set(DRV_SOURCE ${PROJECT_SOURCE_DIR}/drv/drv_can.c # TCP驱动源文件 ${PROJECT_SOURCE_DIR}/drv/drv_tcp.c + # 4G驱动源文件 + ${PROJECT_SOURCE_DIR}/drv/drv_4g.c + # CAN驱动源文件 + ${PROJECT_SOURCE_DIR}/drv/drv_can.c ) # 添加KIT源文件 @@ -71,6 +75,7 @@ include_directories( lib/libxml2/include lib/libssl/include lib/libcjson/include + lib/libmodbus/include # /usr/include ) @@ -83,6 +88,7 @@ NAMES ssl PATHS lib/libssl/lib crypto PATHS lib/libssl/lib cjson PATHS lib/libcjson/lib + modbus PATHS lib/libmodbus/lib ) target_link_libraries(${ProjectName} PRIVATE ${MY_LIBRARY_PATH}) diff --git a/drv/drv_4g.c b/drv/drv_4g.c index e69de29..6375189 100644 --- a/drv/drv_4g.c +++ b/drv/drv_4g.c @@ -0,0 +1,125 @@ +#include "drv_4g.h" + +#define BUFFER_SIZE 1024 +#define LOCAL "10.244.216.42" + +void client(char interface[], char server_addr[], int server_port) { + int sock = 0; + struct ifreq ifr; + + char buffer[BUFFER_SIZE]; + + + // 创建套接字 + if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == 0) { + perror("套接字创建失败"); + exit(EXIT_FAILURE); + } + + //************如果只绑定网卡名不能连接服务端,可以同时绑定ip和网卡尝试一下************* */ + // //local ip + // struct sockaddr_in local_addr; + // local_addr.sin_family = AF_INET; + // local_addr.sin_port = htons(0); + // local_addr.sin_addr.s_addr = inet_addr("10.232.226.30"); + + // // if (inet_pton(AF_INET, "192.168.2.190", &local_addr.sin_addr) <= 0) { + // // perror("无效的地址"); + // // exit(EXIT_FAILURE); + // // } + + // if (bind(sock, (struct sockaddr *)&local_addr, sizeof(local_addr)) < 0) { + // perror("bind失败"); + // exit(EXIT_FAILURE); + // } + // else + // { + // printf("bind success\n"); + // } + // else { + // printf("bind success!\n"); + // } + + + + // if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == 0) { + // perror("套接字创建失败"); + // exit(EXIT_FAILURE); + // } + + // 设置要绑定的网卡接口名称 + strcpy(ifr.ifr_name, interface); + + // 将套接字绑定到指定的网卡 + if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr)) < 0) { + perror("setsockopt"); + close(sock); + exit(1); + } + else{ + printf("connect the local interface:%s\n", ifr.ifr_name); + } + + //绑定服务端的ip + // 设置服务器地址结构体 + struct sockaddr_in serv_addr; + serv_addr.sin_family = AF_INET; + serv_addr.sin_port = htons(server_port); + serv_addr.sin_addr.s_addr = inet_addr(server_addr); + + // 连接服务器 + if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { + perror("connect失败"); + exit(EXIT_FAILURE); + } + else { + printf("connect success!\n"); + } + + + // // 将服务器IP地址从点分十进制字符串转换为网络字节序 + // if (inet_pton(AF_INET, "47.120.14.45", &serv_addr.sin_addr) <= 0) { + // perror("无效的地址"); + // exit(EXIT_FAILURE); + // } + + while (1) + { + // 输入要发送的数据 + printf("请输入要发送的数据(输入'quit'退出):"); + fgets(buffer, BUFFER_SIZE, stdin); + + // 去除换行符 + buffer[strcspn(buffer, "\n")] = 0; + + if (strcmp(buffer, "quit") == 0) { + break; + } + + // 向服务器发送数据 + if (send(sock, buffer, strlen(buffer), 0) < 0) { + perror("发送数据失败"); + break; + } + + printf("已向服务端发送数据\n"); + + // 接收服务器返回的回复数据 + memset(buffer, 0, BUFFER_SIZE); + if (recv(sock, buffer, BUFFER_SIZE, 0) < 0) { + perror("接收数据失败"); + break; + } + + if (strlen(buffer) == 0) { + // 服务器断开连接 + printf("服务器已断开连接\n"); + break; + } + + printf("收到服务端回复:%s\n", buffer); + } + + // 关闭套接字 + close(sock); +} diff --git a/drv/drv_4g.h b/drv/drv_4g.h index e69de29..bc2e63c 100644 --- a/drv/drv_4g.h +++ b/drv/drv_4g.h @@ -0,0 +1,21 @@ +#ifndef __DRV_4G_H_ +#define __DRV_4G_H_ + +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/socket.h> +#include <arpa/inet.h> +#include <unistd.h> +#include <net/if.h> +#include <sys/ioctl.h> +#include <netinet/in.h> +#include <arpa/inet.h> +#include <netdb.h> +#include <errno.h> +#include <pthread.h> +#include <sys/ioctl.h> + +void client(char interface[], char server_addr[], int server_port); + +#endif diff --git a/drv/drv_can.c b/drv/drv_can.c index fce1c04..6e85e4c 100644 --- a/drv/drv_can.c +++ b/drv/drv_can.c @@ -1,287 +1,123 @@ #include "drv_can.h" -/* - * @description : 字符串按格式输出 - * @param - *destpoint : 字符串格式缓冲区 - * @param - *fmt : 多个参数 - * @return : 按格式输出字符串缓冲区首指针 - */ -char func_dprintf(char *destpoint, char *fmt, ...) +void can_recv(char cannum[], unsigned int canID[], int canIDnum, int dataLength) { - va_list arg_ptr; - char ulen, *tmpBuf; - - tmpBuf = destpoint; - va_start(arg_ptr, fmt); - ulen = vsprintf(tmpBuf, fmt, arg_ptr); - - va_end(arg_ptr); - return ulen; -} - -/* - * @description : 打开can外设,设置波特率,创建文件描述符 - * @param - *device : 设备名称 - * @param - para : can应用参数 - * @return : 打开设备执成功返回文件描述符,失败返回-1 - */ -int func_open_can(char *device, struct_can_param para) -{ - FILE *fstream = NULL; - char buff[300] = {0}, command[50] = {0}; - int fd = -1; struct sockaddr_can addr; - struct ifreq ifr; + struct can_frame frame; + struct can_frame frame_send; + int s; + int nbytes; + struct can_filter filters[canIDnum]; - /*关闭can设备 ifconfig can0 down*/ - memset(buff, 0, sizeof(buff)); - memset(command, 0, sizeof(command)); - func_dprintf(command, "ifconfig %s down", device); - printf("%s \n", command); + s = socket(PF_CAN, SOCK_RAW, CAN_RAW); + if (s < 0) { + perror("Socket creation failed"); + exit(EXIT_FAILURE); + } + printf("创建Can_recv_Socket sucess\n"); - if (NULL == (fstream = popen(command, "w"))) - { - fprintf(stderr, "execute command failed: %s", strerror(errno)); - } - while (NULL != fgets(buff, sizeof(buff), fstream)) - { - printf("%s\n", buff); - if (strstr(buff, "No such device") || strstr(buff, "Cannot find device")) - return -1; - } - pclose(fstream); - sleep(1); - - /*设置can波特率 ip link set can0 up type can bitrate 250000 triple-sampling on*/ - memset(buff, 0, sizeof(buff)); - memset(command, 0, sizeof(command)); - if (para.loopback_mode == 1) - { - func_dprintf(command, "ip link set %s up type can bitrate %d triple-sampling on loopback on", device, para.baudrate); - } - else - { - func_dprintf(command, "ip link set %s up type can bitrate %d triple-sampling on loopback off", device, para.baudrate); - } - printf("%s \n", command); - - if (NULL == (fstream = popen(command, "w"))) - { - fprintf(stderr, "execute command failed: %s", strerror(errno)); - } - while (NULL != fgets(buff, sizeof(buff), fstream)) - { - printf("%s\n", buff); - if (strstr(buff, "No such device") || strstr(buff, "Cannot find device")) - return -1; - } - pclose(fstream); - sleep(1); - - /*打开can设备 ifconfig can0 up*/ - memset(buff, 0, sizeof(buff)); - memset(command, 0, sizeof(command)); - func_dprintf(command, "ifconfig %s up", device); - printf("%s \n", command); - - if (NULL == (fstream = popen(command, "w"))) - { - fprintf(stderr, "execute command failed: %s", strerror(errno)); - } - while (NULL != fgets(buff, sizeof(buff), fstream)) - { - printf("%s\n", buff); - if (strstr(buff, "No such device") || strstr(buff, "Cannot find device")) - return -1; - } - pclose(fstream); - sleep(3); - - /* 创建 socket */ - fd = socket(PF_CAN, SOCK_RAW, CAN_RAW); - if (fd < 0) - { - printf("socket:%s", strerror(errno)); - return -1; - } - /* 设置接口设备名称 */ - strcpy(ifr.ifr_name, device); - /* 确定接口 index */ - if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) - { - printf("SIOCGIFINDEX:%s\n", strerror(errno)); - return -1; - } - - memset(&addr, 0, sizeof(addr)); + memset(&addr, 0, sizeof(struct sockaddr_can)); addr.can_family = AF_CAN; - addr.can_ifindex = ifr.ifr_ifindex; - /* 绑定 socket到 CAN 接口 */ - if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) + addr.can_ifindex = if_nametoindex(cannum); // 设置can接口 + + if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + perror("Binding failed"); + exit(EXIT_FAILURE); + } + printf("连接CAN设备 sucess\n"); + + // 设置发送帧的参数,使用传入的canID和数据长度 + frame_send.can_id = 0x123456; + frame_send.can_dlc = dataLength; + memset(frame_send.data, 0, dataLength); + frame_send.data[0] = 0x11; + frame_send.data[1] = 0x22; + + // 设置过滤规则,只接收指定canID的帧 + for(int i = 0; i < canIDnum; i++) { - printf("bind:%s\n", strerror(errno)); - return -1; + filters[i].can_id = canID[i]; + filters[i].can_mask = 0x7FF; // 这里的掩码根据实际需求设置,0x7FF表示只匹配canID的低11位 } - return fd; + if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, filters, sizeof(filters)) < 0) { + perror("Setting filter failed"); + exit(EXIT_FAILURE); + } + + nbytes = read(s, &frame, sizeof(struct can_frame)); + if (nbytes < 0) { + perror("Read failed"); + exit(EXIT_FAILURE); + } + int match_found = 0; + for (int i = 0; i < canIDnum; i++) { + if ((frame.can_id & filters[i].can_mask) == filters[i].can_id) { + match_found = 1; + break; + } + } + if (match_found) { + printf("Received %d bytes: CAN ID 0x%X, Data: ", nbytes, frame.can_id); + for (int i = 0; i < frame.can_dlc; i++) { + printf("%02X ", frame.data[i]); + } + printf("\n"); + // nbytes = write(s, &frame_send, sizeof(struct can_frame)); + // if (nbytes < 0) { + // perror("Send failed"); + // exit(EXIT_FAILURE); + // } + // printf("Sent %d bytes: CAN ID 0x%X, Data: ", nbytes, frame_send.can_id); + // for (int i = 0; i < frame_send.can_dlc; i++) { + // printf("%02X ", frame_send.data[i]); + // } + // printf("\n"); + } + close(s); } -/* - * @description : 设置can回环模式和过滤规则 - * @param - fd : 文件描述符 - * @param - para: can应用参数 - * @return : 设置成功返回1,失败返回-1 - */ -int func_set_can(int fd, struct_can_param para) +void can_send(char cannum[], unsigned int canID, char* dataToSend, int dataLength) { - int loopback = 1; - int reciveown = 1; + struct sockaddr_can addr; + struct can_frame frame_send; + int s; - if (para.loopback_mode == 1) - { - //回环设置 0 关闭回环 1 打开回环 - setsockopt(fd, SOL_CAN_RAW, CAN_RAW_LOOPBACK, &loopback, sizeof(loopback)); - //接收自己的帧 0 不接收自己帧 1 接收自己帧 - setsockopt(fd, SOL_CAN_RAW, CAN_RAW_RECV_OWN_MSGS, &reciveown, sizeof(reciveown)); + s = socket(PF_CAN, SOCK_RAW, CAN_RAW); + if (s < 0) { + perror("Socket creation failed for sending"); + exit(EXIT_FAILURE); + } + printf("create the can_send socket success!\n"); + + memset(&addr, 0, sizeof(struct sockaddr_can)); + addr.can_family = AF_CAN; + addr.can_ifindex = if_nametoindex(cannum); + + if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + perror("Binding failed for sending"); + exit(EXIT_FAILURE); } - /* 设置过滤规则 */ - if (setsockopt(fd, SOL_CAN_RAW, CAN_RAW_FILTER, ¶.filter, sizeof(para.filter)) < 0) - { - printf("error when set filter\n"); - return -1; - } - return 1; -} - -/* - * @description : can接收一个can帧 - * @param - fd : 文件描述符 - * @param - *pframe: 一个can帧结构体指针 - * @return : 接收数据长度 - */ -int func_receive_can_frame(int fd, struct can_frame *pframe) -{ - int rx_count = 0; - - rx_count = recv(fd, pframe, sizeof(*pframe), 0); - if (rx_count <= 0) - { - return rx_count; - } - else - { - if (pframe->can_id & CAN_EFF_FLAG) /*如果是扩展帧,清除扩展帧标识*/ - { - pframe->can_id &= (~CAN_EFF_FLAG); - } - else - { - pframe->can_id &= (~CAN_SFF_MASK); - } + // 设置发送帧的参数 + frame_send.can_id = canID; + frame_send.can_dlc = dataLength; + memset(frame_send.data, 0, dataLength); + for (int i = 0; i < dataLength; i++) { + frame_send.data[i] = dataToSend[i]; } - return pframe->can_dlc; -} - -/* - * @description : can接收一组数据包 - * @param - fd : 文件描述符 - * @param - *buff: 要接收can一组数据的缓冲区首指针 - * @param - len : 接收到一组数据的长度 - * @return : 接收数据长度 - */ -int func_receive_can_buff(int fd, unsigned char *buff, int len) -{ - int receive_len = 0, total_receive_len = 0; - struct can_frame frame; - int i = 0; - - while (1) - { - receive_len = func_receive_can_frame(fd, &frame); - for (i = 0; i < receive_len; i++) - { - *(buff + total_receive_len) = frame.data[i]; - total_receive_len++; - } - if ((receive_len < 8) || (total_receive_len > (len - 8))) - { - return total_receive_len; - } + int nbytes = write(s, &frame_send, sizeof(struct can_frame)); + if (nbytes < 0) { + perror("Send failed"); + exit(EXIT_FAILURE); } - return total_receive_len; -} -/* - * @description : can发送一个can帧 - * @param - fd : 文件描述符 - * @param - *pframe: 一个can帧结构体指针 - * @param - param : can应用参数 - * @return : 发送数据长度,发送失败返回-1 - */ -int func_send_can_frame(int fd, struct can_frame *pframe, struct_can_param param) -{ - int result = 0; - - if (param.extend == 1) /*扩展帧增加扩展帧标志*/ - { - pframe->can_id &= CAN_EFF_MASK; - pframe->can_id |= CAN_EFF_FLAG; + printf("Sent %d bytes: CAN ID 0x%X, Data: ", nbytes, frame_send.can_id); + for (int i = 0; i < frame_send.can_dlc; i++) { + printf("%02X ", frame_send.data[i]); } - else - { - pframe->can_id &= CAN_SFF_MASK; - } - result = send(fd, pframe, sizeof(struct can_frame), 0); - if (result == -1) - { - printf("send:%s\n", strerror(errno)); - return -1; - } - return result; -} + printf("\n"); -/* - * @description : can发送一组数据包 - * @param - fd : 文件描述符 - * @param - *buff: 要发送can一组数据的缓冲区首指针 - * @param - len : 发送数据的长度 - * @param - param: can应用参数 - * @return : 实际发送数据长度 - */ -int func_send_can_buff(int fd, unsigned char *buff, int len, struct_can_param param) -{ - int remain_frame_len = 0, frame_numb = 0; - struct can_frame frame; - int i = 0; - - remain_frame_len = len; - while (1) - { - if (remain_frame_len >= 8) - { - frame.can_dlc = 8; /*填充发送长度*/ - remain_frame_len -= 8; /*剩余数据长度*/ - } - else - { - frame.can_dlc = remain_frame_len; /*填充发送长度*/ - remain_frame_len = 0; // - } - - frame.can_id = param.id; /*填充发送id*/ - - for (i = 0; i < frame.can_dlc; i++) - { - frame.data[i] = buff[frame_numb * 8 + i]; /*填充发送数据*/ - } - func_send_can_frame(fd, &frame, param); - frame_numb++; - if (remain_frame_len == 0) - { - return len; - } - } - return len; + close(s); } \ No newline at end of file diff --git a/drv/drv_can.h b/drv/drv_can.h index bf7a1cc..331fa2c 100644 --- a/drv/drv_can.h +++ b/drv/drv_can.h @@ -1,47 +1,19 @@ -#ifndef __DRV_CAN_H_ -#define __DRV_CAN_H_ +#ifndef __DEV_CAN_H_ +#define __DEV_CAN_H_ -#define _DEFAULT_SOURCE - -#include <linux/can.h> -#include <errno.h> #include <stdio.h> -#include <stdarg.h> #include <stdlib.h> #include <string.h> #include <unistd.h> -#include <fcntl.h> -#include <net/if.h> -#include <sys/ioctl.h> #include <sys/socket.h> +#include <sys/ioctl.h> #include <linux/can.h> #include <linux/can/raw.h> -#include <termios.h> /*PPSIX 终端控制定义*/ +#include <arpa/inet.h> +#include <net/if.h> -#define CAN_MODE 0 -#define CAN_FD_MODE 1 +void can_recv(char cannum[], unsigned int canID[], int canIDnum, int dataLength); -/*CAN口参数结构体 */ -typedef struct -{ - unsigned long baudrate; /*波特率 5k~1000k*/ - unsigned int id; /*设备ID*/ - struct can_filter filter; /*接收设备过滤ID*/ - unsigned char extend; /*扩展ID*/ - unsigned char loopback_mode; /*回环模式*/ - - unsigned char canfd_mode; /*CANFD模式*/ - unsigned long data_baudrate; /*CANFD模式下需要单独设置数据波特率*/ -} struct_can_param; - -int func_open_can(char *device, struct_can_param para); -int func_set_can(int fd, struct_can_param para); -int func_receive_can_buff(int fd, unsigned char *buff, int len); -int func_send_can_buff(int fd, unsigned char *buff, int len, struct_can_param param); - -// int func_open_canfd(char *device, struct_can_param para); -// int func_set_canfd(int fd, struct_can_param para); -// int func_receive_canfd_buff(int fd, unsigned char *buff, int len); -// int func_send_canfd_buff(int fd, unsigned char *buff, int len, struct_can_param param); +void can_send(char cannum[], unsigned int canID, char* dataToSend, int dataLength); #endif \ No newline at end of file diff --git a/drv/drv_tcp.h b/drv/drv_tcp.h index c1e422d..749aba3 100644 --- a/drv/drv_tcp.h +++ b/drv/drv_tcp.h @@ -1,8 +1,6 @@ #ifndef __DRV_TCP_H_ #define __DRV_TCP_H_ -#define _DEFAULT_SOURCE - #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -13,9 +11,9 @@ #include <sys/ioctl.h> #include <pthread.h> -void getInterfacesAndIPs(char *interfaces[], char *ips[], int *numInterfaces); +void getInterfacesAndIPs(char *interfaces[], char *ips[], int *count); void closeAndFree(int server_fd, int new_socket, char *interface, char *ip); -void *tcpServeThread(void *arg); void tcpServe(int port); +void *tcpServeThread(void *arg); #endif \ No newline at end of file diff --git a/lib/libmodbus/include/config.h b/lib/libmodbus/include/config.h new file mode 100644 index 0000000..3d77a65 --- /dev/null +++ b/lib/libmodbus/include/config.h @@ -0,0 +1,292 @@ +/* config.h. Generated from config.h.in by configure. */ +/* config.h.in. Generated from configure.ac by autoheader. */ + +/* Define to 1 if you have the `accept4' function. */ +/* #undef HAVE_ACCEPT4 */ + +/* Define to 1 if you have the <arpa/inet.h> header file. */ +/* #undef HAVE_ARPA_INET_H */ + +/* Define to 1 if you have the <byteswap.h> header file. */ +/* #undef HAVE_BYTESWAP_H */ + +/* Define to 1 if you have the declaration of `TIOCM_RTS', and to 0 if you + don't. */ +#define HAVE_DECL_TIOCM_RTS 0 + +/* Define to 1 if you have the declaration of `TIOCSRS485', and to 0 if you + don't. */ +#define HAVE_DECL_TIOCSRS485 0 + +/* Define to 1 if you have the declaration of `__CYGWIN__', and to 0 if you + don't. */ +#define HAVE_DECL___CYGWIN__ 0 + +/* Define to 1 if you have the <dlfcn.h> header file. */ +/* #undef HAVE_DLFCN_H */ + +/* Define to 1 if you have the <errno.h> header file. */ +#define HAVE_ERRNO_H 1 + +/* Define to 1 if you have the <fcntl.h> header file. */ +#define HAVE_FCNTL_H 1 + +/* Define to 1 if you have the `getaddrinfo' function. */ +/* #undef HAVE_GETADDRINFO */ + +/* Define to 1 if you have the `gettimeofday' function. */ +#define HAVE_GETTIMEOFDAY 1 + +/* Define to 1 if you have the `inet_ntop' function. */ +/* #undef HAVE_INET_NTOP */ + +/* Define to 1 if you have the `inet_pton' function. */ +/* #undef HAVE_INET_PTON */ + +/* Define to 1 if you have the <inttypes.h> header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the <limits.h> header file. */ +#define HAVE_LIMITS_H 1 + +/* Define to 1 if you have the <linux/serial.h> header file. */ +/* #undef HAVE_LINUX_SERIAL_H */ + +/* Define to 1 if you have the <minix/config.h> header file. */ +/* #undef HAVE_MINIX_CONFIG_H */ + +/* Define to 1 if you have the <netdb.h> header file. */ +/* #undef HAVE_NETDB_H */ + +/* Define to 1 if you have the <netinet/in.h> header file. */ +/* #undef HAVE_NETINET_IN_H */ + +/* Define to 1 if you have the <netinet/tcp.h> header file. */ +/* #undef HAVE_NETINET_TCP_H */ + +/* Define to 1 if you have the `select' function. */ +/* #undef HAVE_SELECT */ + +/* Define to 1 if you have the `socket' function. */ +/* #undef HAVE_SOCKET */ + +/* Define to 1 if you have the <stdint.h> header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if you have the <stdio.h> header file. */ +#define HAVE_STDIO_H 1 + +/* Define to 1 if you have the <stdlib.h> header file. */ +#define HAVE_STDLIB_H 1 + +/* Define to 1 if you have the `strerror' function. */ +#define HAVE_STRERROR 1 + +/* Define to 1 if you have the <strings.h> header file. */ +#define HAVE_STRINGS_H 1 + +/* Define to 1 if you have the <string.h> header file. */ +#define HAVE_STRING_H 1 + +/* Define to 1 if you have the `strlcpy' function. */ +/* #undef HAVE_STRLCPY */ + +/* Define to 1 if you have the <sys/ioctl.h> header file. */ +/* #undef HAVE_SYS_IOCTL_H */ + +/* Define to 1 if you have the <sys/params.h> header file. */ +/* #undef HAVE_SYS_PARAMS_H */ + +/* Define to 1 if you have the <sys/socket.h> header file. */ +/* #undef HAVE_SYS_SOCKET_H */ + +/* Define to 1 if you have the <sys/stat.h> header file. */ +#define HAVE_SYS_STAT_H 1 + +/* Define to 1 if you have the <sys/time.h> header file. */ +#define HAVE_SYS_TIME_H 1 + +/* Define to 1 if you have the <sys/types.h> header file. */ +#define HAVE_SYS_TYPES_H 1 + +/* Define to 1 if you have the <termios.h> header file. */ +/* #undef HAVE_TERMIOS_H */ + +/* Define to 1 if you have the <time.h> header file. */ +#define HAVE_TIME_H 1 + +/* Define to 1 if you have the <unistd.h> header file. */ +#define HAVE_UNISTD_H 1 + +/* Define to 1 if you have the <wchar.h> header file. */ +#define HAVE_WCHAR_H 1 + +/* Define to 1 if you have the <winsock2.h> header file. */ +#define HAVE_WINSOCK2_H 1 + +/* Define to the sub-directory where libtool stores uninstalled libraries. */ +#define LT_OBJDIR ".libs/" + +/* Name of package */ +#define PACKAGE "libmodbus" + +/* Define to the address where bug reports for this package should be sent. */ +#define PACKAGE_BUGREPORT "https://github.com/stephane/libmodbus/issues" + +/* Define to the full name of this package. */ +#define PACKAGE_NAME "libmodbus" + +/* Define to the full name and version of this package. */ +#define PACKAGE_STRING "libmodbus 3.1.10" + +/* Define to the one symbol short name of this package. */ +#define PACKAGE_TARNAME "libmodbus" + +/* Define to the home page for this package. */ +#define PACKAGE_URL "http://libmodbus.org/" + +/* Define to the version of this package. */ +#define PACKAGE_VERSION "3.1.10" + +/* Define to 1 if all of the C90 standard headers exist (not just the ones + required in a freestanding environment). This macro is provided for + backward compatibility; new code need not use it. */ +#define STDC_HEADERS 1 + +/* Enable extensions on AIX 3, Interix. */ +#ifndef _ALL_SOURCE +# define _ALL_SOURCE 1 +#endif +/* Enable general extensions on macOS. */ +#ifndef _DARWIN_C_SOURCE +# define _DARWIN_C_SOURCE 1 +#endif +/* Enable general extensions on Solaris. */ +#ifndef __EXTENSIONS__ +# define __EXTENSIONS__ 1 +#endif +/* Enable GNU extensions on systems that have them. */ +#ifndef _GNU_SOURCE +# define _GNU_SOURCE 1 +#endif +/* Enable X/Open compliant socket functions that do not require linking + with -lxnet on HP-UX 11.11. */ +#ifndef _HPUX_ALT_XOPEN_SOCKET_API +# define _HPUX_ALT_XOPEN_SOCKET_API 1 +#endif +/* Identify the host operating system as Minix. + This macro does not affect the system headers' behavior. + A future release of Autoconf may stop defining this macro. */ +#ifndef _MINIX +/* # undef _MINIX */ +#endif +/* Enable general extensions on NetBSD. + Enable NetBSD compatibility extensions on Minix. */ +#ifndef _NETBSD_SOURCE +# define _NETBSD_SOURCE 1 +#endif +/* Enable OpenBSD compatibility extensions on NetBSD. + Oddly enough, this does nothing on OpenBSD. */ +#ifndef _OPENBSD_SOURCE +# define _OPENBSD_SOURCE 1 +#endif +/* Define to 1 if needed for POSIX-compatible behavior. */ +#ifndef _POSIX_SOURCE +/* # undef _POSIX_SOURCE */ +#endif +/* Define to 2 if needed for POSIX-compatible behavior. */ +#ifndef _POSIX_1_SOURCE +/* # undef _POSIX_1_SOURCE */ +#endif +/* Enable POSIX-compatible threading on Solaris. */ +#ifndef _POSIX_PTHREAD_SEMANTICS +# define _POSIX_PTHREAD_SEMANTICS 1 +#endif +/* Enable extensions specified by ISO/IEC TS 18661-5:2014. */ +#ifndef __STDC_WANT_IEC_60559_ATTRIBS_EXT__ +# define __STDC_WANT_IEC_60559_ATTRIBS_EXT__ 1 +#endif +/* Enable extensions specified by ISO/IEC TS 18661-1:2014. */ +#ifndef __STDC_WANT_IEC_60559_BFP_EXT__ +# define __STDC_WANT_IEC_60559_BFP_EXT__ 1 +#endif +/* Enable extensions specified by ISO/IEC TS 18661-2:2015. */ +#ifndef __STDC_WANT_IEC_60559_DFP_EXT__ +# define __STDC_WANT_IEC_60559_DFP_EXT__ 1 +#endif +/* Enable extensions specified by ISO/IEC TS 18661-4:2015. */ +#ifndef __STDC_WANT_IEC_60559_FUNCS_EXT__ +# define __STDC_WANT_IEC_60559_FUNCS_EXT__ 1 +#endif +/* Enable extensions specified by ISO/IEC TS 18661-3:2015. */ +#ifndef __STDC_WANT_IEC_60559_TYPES_EXT__ +# define __STDC_WANT_IEC_60559_TYPES_EXT__ 1 +#endif +/* Enable extensions specified by ISO/IEC TR 24731-2:2010. */ +#ifndef __STDC_WANT_LIB_EXT2__ +# define __STDC_WANT_LIB_EXT2__ 1 +#endif +/* Enable extensions specified by ISO/IEC 24747:2009. */ +#ifndef __STDC_WANT_MATH_SPEC_FUNCS__ +# define __STDC_WANT_MATH_SPEC_FUNCS__ 1 +#endif +/* Enable extensions on HP NonStop. */ +#ifndef _TANDEM_SOURCE +# define _TANDEM_SOURCE 1 +#endif +/* Enable X/Open extensions. Define to 500 only if necessary + to make mbstate_t available. */ +#ifndef _XOPEN_SOURCE +/* # undef _XOPEN_SOURCE */ +#endif + + +/* Version number of package */ +#define VERSION "3.1.10" + +/* _ */ +#define WINVER 0x0501 + +/* Number of bits in a file offset, on hosts where this is settable. */ +#define _FILE_OFFSET_BITS 64 + +/* Define for large files, on AIX-style hosts. */ +/* #undef _LARGE_FILES */ + +/* Define for Solaris 2.5.1 so the uint32_t typedef from <sys/synch.h>, + <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the + #define below would cause a syntax error. */ +/* #undef _UINT32_T */ + +/* Define for Solaris 2.5.1 so the uint8_t typedef from <sys/synch.h>, + <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the + #define below would cause a syntax error. */ +/* #undef _UINT8_T */ + +/* Define to `__inline__' or `__inline' if that's what the C compiler + calls it, or to nothing if 'inline' is not supported under any name. */ +#ifndef __cplusplus +/* #undef inline */ +#endif + +/* Define to the type of a signed integer type of width exactly 64 bits if + such a type exists and the standard includes do not define it. */ +/* #undef int64_t */ + +/* Define to `unsigned int' if <sys/types.h> does not define. */ +/* #undef size_t */ + +/* Define to `int' if <sys/types.h> does not define. */ +/* #undef ssize_t */ + +/* Define to the type of an unsigned integer type of width exactly 16 bits if + such a type exists and the standard includes do not define it. */ +/* #undef uint16_t */ + +/* Define to the type of an unsigned integer type of width exactly 32 bits if + such a type exists and the standard includes do not define it. */ +/* #undef uint32_t */ + +/* Define to the type of an unsigned integer type of width exactly 8 bits if + such a type exists and the standard includes do not define it. */ +/* #undef uint8_t */ diff --git a/lib/libmodbus/include/modbus-private.h b/lib/libmodbus/include/modbus-private.h new file mode 100644 index 0000000..4beab96 --- /dev/null +++ b/lib/libmodbus/include/modbus-private.h @@ -0,0 +1,125 @@ +/* + * Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com> + * + * SPDX-License-Identifier: LGPL-2.1-or-later + */ + +#ifndef MODBUS_PRIVATE_H +#define MODBUS_PRIVATE_H + +// clang-format off +#ifndef _MSC_VER +# include <stdint.h> +# include <sys/time.h> +#else +# include "stdint.h" +# include <time.h> +typedef int ssize_t; +#endif +// clang-format on +#include <config.h> +#include <sys/types.h> + +#include "modbus.h" + +MODBUS_BEGIN_DECLS + +/* It's not really the minimal length (the real one is report slave ID + * in RTU (4 bytes)) but it's a convenient size to use in RTU or TCP + * communications to read many values or write a single one. + * Maximum between : + * - HEADER_LENGTH_TCP (7) + function (1) + address (2) + number (2) + * - HEADER_LENGTH_RTU (1) + function (1) + address (2) + number (2) + CRC (2) + */ +#define _MIN_REQ_LENGTH 12 + +#define _REPORT_SLAVE_ID 180 + +#define _MODBUS_EXCEPTION_RSP_LENGTH 5 + +/* Timeouts in microsecond (0.5 s) */ +#define _RESPONSE_TIMEOUT 500000 +#define _BYTE_TIMEOUT 500000 + +typedef enum { + _MODBUS_BACKEND_TYPE_RTU = 0, + _MODBUS_BACKEND_TYPE_TCP +} modbus_backend_type_t; + +/* + * ---------- Request Indication ---------- + * | Client | ---------------------->| Server | + * ---------- Confirmation Response ---------- + */ +typedef enum { + /* Request message on the server side */ + MSG_INDICATION, + /* Request message on the client side */ + MSG_CONFIRMATION +} msg_type_t; + +/* This structure reduces the number of params in functions and so + * optimizes the speed of execution (~ 37%). */ +typedef struct _sft { + int slave; + int function; + int t_id; +} sft_t; + +typedef struct _modbus_backend { + unsigned int backend_type; + unsigned int header_length; + unsigned int checksum_length; + unsigned int max_adu_length; + int (*set_slave)(modbus_t *ctx, int slave); + int (*build_request_basis)( + modbus_t *ctx, int function, int addr, int nb, uint8_t *req); + int (*build_response_basis)(sft_t *sft, uint8_t *rsp); + int (*prepare_response_tid)(const uint8_t *req, int *req_length); + int (*send_msg_pre)(uint8_t *req, int req_length); + ssize_t (*send)(modbus_t *ctx, const uint8_t *req, int req_length); + int (*receive)(modbus_t *ctx, uint8_t *req); + ssize_t (*recv)(modbus_t *ctx, uint8_t *rsp, int rsp_length); + int (*check_integrity)(modbus_t *ctx, uint8_t *msg, const int msg_length); + int (*pre_check_confirmation)(modbus_t *ctx, + const uint8_t *req, + const uint8_t *rsp, + int rsp_length); + int (*connect)(modbus_t *ctx); + unsigned int (*is_connected)(modbus_t *ctx); + void (*close)(modbus_t *ctx); + int (*flush)(modbus_t *ctx); + int (*select)(modbus_t *ctx, fd_set *rset, struct timeval *tv, int msg_length); + void (*free)(modbus_t *ctx); +} modbus_backend_t; + +struct _modbus { + /* Slave address */ + int slave; + /* Socket or file descriptor */ + int s; + int debug; + int error_recovery; + int quirks; + struct timeval response_timeout; + struct timeval byte_timeout; + struct timeval indication_timeout; + const modbus_backend_t *backend; + void *backend_data; + uint8_t *sendMsg; + int sendMsgLen; + uint8_t *recvMsg; + int recvMsgLen; +}; + +void _modbus_init_common(modbus_t *ctx); +void _error_print(modbus_t *ctx, const char *context); +int _modbus_receive_msg(modbus_t *ctx, uint8_t *msg, msg_type_t msg_type); + +#ifndef HAVE_STRLCPY +size_t strlcpy(char *dest, const char *src, size_t dest_size); +#endif + +MODBUS_END_DECLS + +#endif /* MODBUS_PRIVATE_H */ diff --git a/lib/libmodbus/include/modbus-rtu-private.h b/lib/libmodbus/include/modbus-rtu-private.h new file mode 100644 index 0000000..01e6a91 --- /dev/null +++ b/lib/libmodbus/include/modbus-rtu-private.h @@ -0,0 +1,77 @@ +/* + * Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com> + * + * SPDX-License-Identifier: LGPL-2.1-or-later + */ + +#ifndef MODBUS_RTU_PRIVATE_H +#define MODBUS_RTU_PRIVATE_H + +#ifndef _MSC_VER +#include <stdint.h> +#else +#include "stdint.h" +#endif + +#if defined(_WIN32) +#include <windows.h> +#else +#include <termios.h> +#endif + +#define _MODBUS_RTU_HEADER_LENGTH 1 +#define _MODBUS_RTU_PRESET_REQ_LENGTH 6 +#define _MODBUS_RTU_PRESET_RSP_LENGTH 2 + +#define _MODBUS_RTU_CHECKSUM_LENGTH 2 + +#if defined(_WIN32) +#if !defined(ENOTSUP) +#define ENOTSUP WSAEOPNOTSUPP +#endif + +/* WIN32: struct containing serial handle and a receive buffer */ +#define PY_BUF_SIZE 512 + +struct win32_ser { + /* File handle */ + HANDLE fd; + /* Receive buffer */ + uint8_t buf[PY_BUF_SIZE]; + /* Received chars */ + DWORD n_bytes; +}; +#endif /* _WIN32 */ + +typedef struct _modbus_rtu { + /* Device: "/dev/ttyS0", "/dev/ttyUSB0" or "/dev/tty.USA19*" on Mac OS X. */ + char *device; + /* Bauds: 9600, 19200, 57600, 115200, etc */ + int baud; + /* Data bit */ + uint8_t data_bit; + /* Stop bit */ + uint8_t stop_bit; + /* Parity: 'N', 'O', 'E' */ + char parity; +#if defined(_WIN32) + struct win32_ser w_ser; + DCB old_dcb; +#else + /* Save old termios settings */ + struct termios old_tios; +#endif +#if HAVE_DECL_TIOCSRS485 + int serial_mode; +#endif +#if HAVE_DECL_TIOCM_RTS + int rts; + int rts_delay; + int onebyte_time; + void (*set_rts)(modbus_t *ctx, int on); +#endif + /* To handle many slaves on the same link */ + int confirmation_to_ignore; +} modbus_rtu_t; + +#endif /* MODBUS_RTU_PRIVATE_H */ diff --git a/lib/libmodbus/include/modbus-rtu.h b/lib/libmodbus/include/modbus-rtu.h new file mode 100644 index 0000000..8e89e73 --- /dev/null +++ b/lib/libmodbus/include/modbus-rtu.h @@ -0,0 +1,43 @@ +/* + * Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com> + * + * SPDX-License-Identifier: LGPL-2.1-or-later + */ + +#ifndef MODBUS_RTU_H +#define MODBUS_RTU_H + +#include "modbus.h" + +MODBUS_BEGIN_DECLS + +/* Modbus_Application_Protocol_V1_1b.pdf Chapter 4 Section 1 Page 5 + * RS232 / RS485 ADU = 253 bytes + slave (1 byte) + CRC (2 bytes) = 256 bytes + */ +#define MODBUS_RTU_MAX_ADU_LENGTH 256 + +MODBUS_API modbus_t * +modbus_new_rtu(const char *device, int baud, char parity, int data_bit, int stop_bit); + +#define MODBUS_RTU_RS232 0 +#define MODBUS_RTU_RS485 1 + +MODBUS_API int modbus_rtu_set_serial_mode(modbus_t *ctx, int mode); +MODBUS_API int modbus_rtu_get_serial_mode(modbus_t *ctx); + +#define MODBUS_RTU_RTS_NONE 0 +#define MODBUS_RTU_RTS_UP 1 +#define MODBUS_RTU_RTS_DOWN 2 + +MODBUS_API int modbus_rtu_set_rts(modbus_t *ctx, int mode); +MODBUS_API int modbus_rtu_get_rts(modbus_t *ctx); + +MODBUS_API int modbus_rtu_set_custom_rts(modbus_t *ctx, + void (*set_rts)(modbus_t *ctx, int on)); + +MODBUS_API int modbus_rtu_set_rts_delay(modbus_t *ctx, int us); +MODBUS_API int modbus_rtu_get_rts_delay(modbus_t *ctx); + +MODBUS_END_DECLS + +#endif /* MODBUS_RTU_H */ diff --git a/lib/libmodbus/include/modbus-tcp-private.h b/lib/libmodbus/include/modbus-tcp-private.h new file mode 100644 index 0000000..faffc21 --- /dev/null +++ b/lib/libmodbus/include/modbus-tcp-private.h @@ -0,0 +1,41 @@ +/* + * Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com> + * + * SPDX-License-Identifier: LGPL-2.1-or-later + */ + +#ifndef MODBUS_TCP_PRIVATE_H +#define MODBUS_TCP_PRIVATE_H + +#define _MODBUS_TCP_HEADER_LENGTH 7 +#define _MODBUS_TCP_PRESET_REQ_LENGTH 12 +#define _MODBUS_TCP_PRESET_RSP_LENGTH 8 + +#define _MODBUS_TCP_CHECKSUM_LENGTH 0 + +/* In both structures, the transaction ID must be placed on first position + to have a quick access not dependent of the TCP backend */ +typedef struct _modbus_tcp { + /* Extract from MODBUS Messaging on TCP/IP Implementation Guide V1.0b + (page 23/46): + The transaction identifier is used to associate the future response + with the request. This identifier is unique on each TCP connection. */ + uint16_t t_id; + /* TCP port */ + int port; + /* IP address */ + char ip[16]; +} modbus_tcp_t; + +typedef struct _modbus_tcp_pi { + /* Transaction ID */ + uint16_t t_id; + /* TCP port */ + int port; + /* Node */ + char *node; + /* Service */ + char *service; +} modbus_tcp_pi_t; + +#endif /* MODBUS_TCP_PRIVATE_H */ diff --git a/lib/libmodbus/include/modbus-tcp.h b/lib/libmodbus/include/modbus-tcp.h new file mode 100644 index 0000000..768d38c --- /dev/null +++ b/lib/libmodbus/include/modbus-tcp.h @@ -0,0 +1,52 @@ +/* + * Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com> + * + * SPDX-License-Identifier: LGPL-2.1-or-later + */ + +#ifndef MODBUS_TCP_H +#define MODBUS_TCP_H + +#include "modbus.h" + +MODBUS_BEGIN_DECLS + +#if defined(_WIN32) && !defined(__CYGWIN__) +/* Win32 with MinGW, supplement to <errno.h> */ +#include <winsock2.h> +#if !defined(ECONNRESET) +#define ECONNRESET WSAECONNRESET +#endif +#if !defined(ECONNREFUSED) +#define ECONNREFUSED WSAECONNREFUSED +#endif +#if !defined(ETIMEDOUT) +#define ETIMEDOUT WSAETIMEDOUT +#endif +#if !defined(ENOPROTOOPT) +#define ENOPROTOOPT WSAENOPROTOOPT +#endif +#if !defined(EINPROGRESS) +#define EINPROGRESS WSAEINPROGRESS +#endif +#endif + +#define MODBUS_TCP_DEFAULT_PORT 502 +#define MODBUS_TCP_SLAVE 0xFF + +/* Modbus_Application_Protocol_V1_1b.pdf Chapter 4 Section 1 Page 5 + * TCP MODBUS ADU = 253 bytes + MBAP (7 bytes) = 260 bytes + */ +#define MODBUS_TCP_MAX_ADU_LENGTH 260 + +MODBUS_API modbus_t *modbus_new_tcp(const char *ip_address, int port); +MODBUS_API int modbus_tcp_listen(modbus_t *ctx, int nb_connection); +MODBUS_API int modbus_tcp_accept(modbus_t *ctx, int *s); + +MODBUS_API modbus_t *modbus_new_tcp_pi(const char *node, const char *service); +MODBUS_API int modbus_tcp_pi_listen(modbus_t *ctx, int nb_connection); +MODBUS_API int modbus_tcp_pi_accept(modbus_t *ctx, int *s); + +MODBUS_END_DECLS + +#endif /* MODBUS_TCP_H */ diff --git a/lib/libmodbus/include/modbus-version.h b/lib/libmodbus/include/modbus-version.h new file mode 100644 index 0000000..16a34da --- /dev/null +++ b/lib/libmodbus/include/modbus-version.h @@ -0,0 +1,51 @@ +/* + * Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#ifndef MODBUS_VERSION_H +#define MODBUS_VERSION_H + +/* The major version, (1, if %LIBMODBUS_VERSION is 1.2.3) */ +#define LIBMODBUS_VERSION_MAJOR (3) + +/* The minor version (2, if %LIBMODBUS_VERSION is 1.2.3) */ +#define LIBMODBUS_VERSION_MINOR (1) + +/* The micro version (3, if %LIBMODBUS_VERSION is 1.2.3) */ +#define LIBMODBUS_VERSION_MICRO (10) + +/* The full version, like 1.2.3 */ +#define LIBMODBUS_VERSION 3.1.10 + +/* The full version, in string form (suited for string concatenation) + */ +#define LIBMODBUS_VERSION_STRING "3.1.10" + +/* Numerically encoded version, eg. v1.2.3 is 0x010203 */ +#define LIBMODBUS_VERSION_HEX \ + ((LIBMODBUS_VERSION_MAJOR << 16) | (LIBMODBUS_VERSION_MINOR << 8) | \ + (LIBMODBUS_VERSION_MICRO << 0)) + +/* Evaluates to True if the version is greater than @major, @minor and @micro + */ +#define LIBMODBUS_VERSION_CHECK(major, minor, micro) \ + (LIBMODBUS_VERSION_MAJOR > (major) || \ + (LIBMODBUS_VERSION_MAJOR == (major) && LIBMODBUS_VERSION_MINOR > (minor)) || \ + (LIBMODBUS_VERSION_MAJOR == (major) && LIBMODBUS_VERSION_MINOR == (minor) && \ + LIBMODBUS_VERSION_MICRO >= (micro))) + +#endif /* MODBUS_VERSION_H */ diff --git a/lib/libmodbus/include/modbus.h b/lib/libmodbus/include/modbus.h new file mode 100644 index 0000000..55ef08a --- /dev/null +++ b/lib/libmodbus/include/modbus.h @@ -0,0 +1,329 @@ +/* + * Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com> + * + * SPDX-License-Identifier: LGPL-2.1-or-later + */ + +#ifndef MODBUS_H +#define MODBUS_H + +// clang-format off +/* Add this for macros that defined unix flavor */ +#if (defined(__unix__) || defined(unix)) && !defined(USG) +# include <sys/param.h> +#endif + +#ifndef _MSC_VER +# include <stdint.h> +#else +# include "stdint.h" +#endif + +#include "modbus-version.h" + +#if defined(_MSC_VER) +# if defined(DLLBUILD) +/* define DLLBUILD when building the DLL */ +# define MODBUS_API __declspec(dllexport) +# else +# define MODBUS_API __declspec(dllimport) +# endif +#else +# define MODBUS_API +#endif + +#ifdef __cplusplus +# define MODBUS_BEGIN_DECLS extern "C" { +# define MODBUS_END_DECLS } +#else +# define MODBUS_BEGIN_DECLS +# define MODBUS_END_DECLS +#endif +// clang-format on + +MODBUS_BEGIN_DECLS + +#ifndef FALSE +#define FALSE 0 +#endif + +#ifndef TRUE +#define TRUE 1 +#endif + +#ifndef OFF +#define OFF 0 +#endif + +#ifndef ON +#define ON 1 +#endif + +/* Modbus function codes */ +#define MODBUS_FC_READ_COILS 0x01 +#define MODBUS_FC_READ_DISCRETE_INPUTS 0x02 +#define MODBUS_FC_READ_HOLDING_REGISTERS 0x03 +#define MODBUS_FC_READ_INPUT_REGISTERS 0x04 +#define MODBUS_FC_WRITE_SINGLE_COIL 0x05 +#define MODBUS_FC_WRITE_SINGLE_REGISTER 0x06 +#define MODBUS_FC_READ_EXCEPTION_STATUS 0x07 +#define MODBUS_FC_WRITE_MULTIPLE_COILS 0x0F +#define MODBUS_FC_WRITE_MULTIPLE_REGISTERS 0x10 +#define MODBUS_FC_REPORT_SLAVE_ID 0x11 +#define MODBUS_FC_MASK_WRITE_REGISTER 0x16 +#define MODBUS_FC_WRITE_AND_READ_REGISTERS 0x17 + +#define MODBUS_BROADCAST_ADDRESS 0 + +/* Modbus_Application_Protocol_V1_1b.pdf (chapter 6 section 1 page 12) + * Quantity of Coils to read (2 bytes): 1 to 2000 (0x7D0) + * (chapter 6 section 11 page 29) + * Quantity of Coils to write (2 bytes): 1 to 1968 (0x7B0) + */ +#define MODBUS_MAX_READ_BITS 2000 +#define MODBUS_MAX_WRITE_BITS 1968 + +/* Modbus_Application_Protocol_V1_1b.pdf (chapter 6 section 3 page 15) + * Quantity of Registers to read (2 bytes): 1 to 125 (0x7D) + * (chapter 6 section 12 page 31) + * Quantity of Registers to write (2 bytes) 1 to 123 (0x7B) + * (chapter 6 section 17 page 38) + * Quantity of Registers to write in R/W registers (2 bytes) 1 to 121 (0x79) + */ +#define MODBUS_MAX_READ_REGISTERS 125 +#define MODBUS_MAX_WRITE_REGISTERS 123 +#define MODBUS_MAX_WR_WRITE_REGISTERS 121 +#define MODBUS_MAX_WR_READ_REGISTERS 125 + +/* The size of the MODBUS PDU is limited by the size constraint inherited from + * the first MODBUS implementation on Serial Line network (max. RS485 ADU = 256 + * bytes). Therefore, MODBUS PDU for serial line communication = 256 - Server + * address (1 byte) - CRC (2 bytes) = 253 bytes. + */ +#define MODBUS_MAX_PDU_LENGTH 253 + +/* Consequently: + * - RTU MODBUS ADU = 253 bytes + Server address (1 byte) + CRC (2 bytes) = 256 + * bytes. + * - TCP MODBUS ADU = 253 bytes + MBAP (7 bytes) = 260 bytes. + * so the maximum of both backend in 260 bytes. This size can used to allocate + * an array of bytes to store responses and it will be compatible with the two + * backends. + */ +#define MODBUS_MAX_ADU_LENGTH 260 + +/* Random number to avoid errno conflicts */ +#define MODBUS_ENOBASE 112345678 + +/* Protocol exceptions */ +enum { + MODBUS_EXCEPTION_ILLEGAL_FUNCTION = 0x01, + MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS, + MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE, + MODBUS_EXCEPTION_SLAVE_OR_SERVER_FAILURE, + MODBUS_EXCEPTION_ACKNOWLEDGE, + MODBUS_EXCEPTION_SLAVE_OR_SERVER_BUSY, + MODBUS_EXCEPTION_NEGATIVE_ACKNOWLEDGE, + MODBUS_EXCEPTION_MEMORY_PARITY, + MODBUS_EXCEPTION_NOT_DEFINED, + MODBUS_EXCEPTION_GATEWAY_PATH, + MODBUS_EXCEPTION_GATEWAY_TARGET, + MODBUS_EXCEPTION_MAX +}; + +#define EMBXILFUN (MODBUS_ENOBASE + MODBUS_EXCEPTION_ILLEGAL_FUNCTION) +#define EMBXILADD (MODBUS_ENOBASE + MODBUS_EXCEPTION_ILLEGAL_DATA_ADDRESS) +#define EMBXILVAL (MODBUS_ENOBASE + MODBUS_EXCEPTION_ILLEGAL_DATA_VALUE) +#define EMBXSFAIL (MODBUS_ENOBASE + MODBUS_EXCEPTION_SLAVE_OR_SERVER_FAILURE) +#define EMBXACK (MODBUS_ENOBASE + MODBUS_EXCEPTION_ACKNOWLEDGE) +#define EMBXSBUSY (MODBUS_ENOBASE + MODBUS_EXCEPTION_SLAVE_OR_SERVER_BUSY) +#define EMBXNACK (MODBUS_ENOBASE + MODBUS_EXCEPTION_NEGATIVE_ACKNOWLEDGE) +#define EMBXMEMPAR (MODBUS_ENOBASE + MODBUS_EXCEPTION_MEMORY_PARITY) +#define EMBXGPATH (MODBUS_ENOBASE + MODBUS_EXCEPTION_GATEWAY_PATH) +#define EMBXGTAR (MODBUS_ENOBASE + MODBUS_EXCEPTION_GATEWAY_TARGET) + +/* Native libmodbus error codes */ +#define EMBBADCRC (EMBXGTAR + 1) +#define EMBBADDATA (EMBXGTAR + 2) +#define EMBBADEXC (EMBXGTAR + 3) +#define EMBUNKEXC (EMBXGTAR + 4) +#define EMBMDATA (EMBXGTAR + 5) +#define EMBBADSLAVE (EMBXGTAR + 6) + +extern const unsigned int libmodbus_version_major; +extern const unsigned int libmodbus_version_minor; +extern const unsigned int libmodbus_version_micro; + +typedef struct _modbus modbus_t; + +typedef struct _modbus_mapping_t { + int nb_bits; + int start_bits; + int nb_input_bits; + int start_input_bits; + int nb_input_registers; + int start_input_registers; + int nb_registers; + int start_registers; + uint8_t *tab_bits; + uint8_t *tab_input_bits; + uint16_t *tab_input_registers; + uint16_t *tab_registers; +} modbus_mapping_t; + +typedef enum { + MODBUS_ERROR_RECOVERY_NONE = 0, + MODBUS_ERROR_RECOVERY_LINK = (1 << 1), + MODBUS_ERROR_RECOVERY_PROTOCOL = (1 << 2) +} modbus_error_recovery_mode; + +typedef enum { + MODBUS_QUIRK_NONE = 0, + MODBUS_QUIRK_MAX_SLAVE = (1 << 1), + MODBUS_QUIRK_REPLY_TO_BROADCAST = (1 << 2), + MODBUS_QUIRK_ALL = 0xFF +} modbus_quirks; + +MODBUS_API int modbus_set_slave(modbus_t *ctx, int slave); +MODBUS_API int modbus_get_slave(modbus_t *ctx); +MODBUS_API int modbus_set_error_recovery(modbus_t *ctx, + modbus_error_recovery_mode error_recovery); +MODBUS_API int modbus_set_socket(modbus_t *ctx, int s); +MODBUS_API int modbus_get_socket(modbus_t *ctx); + +MODBUS_API int +modbus_get_response_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec); +MODBUS_API int +modbus_set_response_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec); + +MODBUS_API int +modbus_get_byte_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec); +MODBUS_API int modbus_set_byte_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec); + +MODBUS_API int +modbus_get_indication_timeout(modbus_t *ctx, uint32_t *to_sec, uint32_t *to_usec); +MODBUS_API int +modbus_set_indication_timeout(modbus_t *ctx, uint32_t to_sec, uint32_t to_usec); + +MODBUS_API int modbus_get_header_length(modbus_t *ctx); + +MODBUS_API int modbus_connect(modbus_t *ctx); +MODBUS_API void modbus_close(modbus_t *ctx); + +MODBUS_API void modbus_free(modbus_t *ctx); + +MODBUS_API int modbus_flush(modbus_t *ctx); +MODBUS_API int modbus_set_debug(modbus_t *ctx, int flag); + +MODBUS_API const char *modbus_strerror(int errnum); + +MODBUS_API int modbus_read_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest); +MODBUS_API int modbus_read_input_bits(modbus_t *ctx, int addr, int nb, uint8_t *dest); +MODBUS_API int modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest); +MODBUS_API int +modbus_read_input_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest); +MODBUS_API int modbus_write_bit(modbus_t *ctx, int coil_addr, int status); +MODBUS_API int modbus_write_register(modbus_t *ctx, int reg_addr, const uint16_t value); +MODBUS_API int modbus_write_bits(modbus_t *ctx, int addr, int nb, const uint8_t *data); +MODBUS_API int +modbus_write_registers(modbus_t *ctx, int addr, int nb, const uint16_t *data); +MODBUS_API int +modbus_mask_write_register(modbus_t *ctx, int addr, uint16_t and_mask, uint16_t or_mask); +MODBUS_API int modbus_write_and_read_registers(modbus_t *ctx, + int write_addr, + int write_nb, + const uint16_t *src, + int read_addr, + int read_nb, + uint16_t *dest); +MODBUS_API int modbus_report_slave_id(modbus_t *ctx, int max_dest, uint8_t *dest); + +MODBUS_API modbus_mapping_t * +modbus_mapping_new_start_address(unsigned int start_bits, + unsigned int nb_bits, + unsigned int start_input_bits, + unsigned int nb_input_bits, + unsigned int start_registers, + unsigned int nb_registers, + unsigned int start_input_registers, + unsigned int nb_input_registers); + +MODBUS_API modbus_mapping_t *modbus_mapping_new(int nb_bits, + int nb_input_bits, + int nb_registers, + int nb_input_registers); +MODBUS_API void modbus_mapping_free(modbus_mapping_t *mb_mapping); + +MODBUS_API int +modbus_send_raw_request(modbus_t *ctx, const uint8_t *raw_req, int raw_req_length); + +MODBUS_API int modbus_receive(modbus_t *ctx, uint8_t *req); + +MODBUS_API int modbus_receive_confirmation(modbus_t *ctx, uint8_t *rsp); + +MODBUS_API int modbus_reply(modbus_t *ctx, + const uint8_t *req, + int req_length, + modbus_mapping_t *mb_mapping); +MODBUS_API int +modbus_reply_exception(modbus_t *ctx, const uint8_t *req, unsigned int exception_code); +MODBUS_API int modbus_enable_quirks(modbus_t *ctx, unsigned int quirks_mask); +MODBUS_API int modbus_disable_quirks(modbus_t *ctx, unsigned int quirks_mask); + +/** + * UTILS FUNCTIONS + **/ + +#define MODBUS_GET_HIGH_BYTE(data) (((data) >> 8) & 0xFF) +#define MODBUS_GET_LOW_BYTE(data) ((data) &0xFF) +#define MODBUS_GET_INT64_FROM_INT16(tab_int16, index) \ + (((int64_t) tab_int16[(index)] << 48) | ((int64_t) tab_int16[(index) + 1] << 32) | \ + ((int64_t) tab_int16[(index) + 2] << 16) | (int64_t) tab_int16[(index) + 3]) +#define MODBUS_GET_INT32_FROM_INT16(tab_int16, index) \ + (((int32_t) tab_int16[(index)] << 16) | (int32_t) tab_int16[(index) + 1]) +#define MODBUS_GET_INT16_FROM_INT8(tab_int8, index) \ + (((int16_t) tab_int8[(index)] << 8) | (int16_t) tab_int8[(index) + 1]) +#define MODBUS_SET_INT16_TO_INT8(tab_int8, index, value) \ + do { \ + ((int8_t *) (tab_int8))[(index)] = (int8_t) ((value) >> 8); \ + ((int8_t *) (tab_int8))[(index) + 1] = (int8_t) (value); \ + } while (0) +#define MODBUS_SET_INT32_TO_INT16(tab_int16, index, value) \ + do { \ + ((int16_t *) (tab_int16))[(index)] = (int16_t) ((value) >> 16); \ + ((int16_t *) (tab_int16))[(index) + 1] = (int16_t) (value); \ + } while (0) +#define MODBUS_SET_INT64_TO_INT16(tab_int16, index, value) \ + do { \ + ((int16_t *) (tab_int16))[(index)] = (int16_t) ((value) >> 48); \ + ((int16_t *) (tab_int16))[(index) + 1] = (int16_t) ((value) >> 32); \ + ((int16_t *) (tab_int16))[(index) + 2] = (int16_t) ((value) >> 16); \ + ((int16_t *) (tab_int16))[(index) + 3] = (int16_t) (value); \ + } while (0) + +MODBUS_API void modbus_set_bits_from_byte(uint8_t *dest, int idx, const uint8_t value); +MODBUS_API void modbus_set_bits_from_bytes(uint8_t *dest, + int idx, + unsigned int nb_bits, + const uint8_t *tab_byte); +MODBUS_API uint8_t modbus_get_byte_from_bits(const uint8_t *src, + int idx, + unsigned int nb_bits); +MODBUS_API float modbus_get_float(const uint16_t *src); +MODBUS_API float modbus_get_float_abcd(const uint16_t *src); +MODBUS_API float modbus_get_float_dcba(const uint16_t *src); +MODBUS_API float modbus_get_float_badc(const uint16_t *src); +MODBUS_API float modbus_get_float_cdab(const uint16_t *src); + +MODBUS_API void modbus_set_float(float f, uint16_t *dest); +MODBUS_API void modbus_set_float_abcd(float f, uint16_t *dest); +MODBUS_API void modbus_set_float_dcba(float f, uint16_t *dest); +MODBUS_API void modbus_set_float_badc(float f, uint16_t *dest); +MODBUS_API void modbus_set_float_cdab(float f, uint16_t *dest); + +#include "modbus-rtu.h" +#include "modbus-tcp.h" + +MODBUS_END_DECLS + +#endif /* MODBUS_H */ diff --git a/lib/libmodbus/lib/libmodbus.so b/lib/libmodbus/lib/libmodbus.so new file mode 100644 index 0000000..6d70657 Binary files /dev/null and b/lib/libmodbus/lib/libmodbus.so differ diff --git a/test/test.c b/test/test.c index 5e472c5..3b29277 100644 --- a/test/test.c +++ b/test/test.c @@ -23,7 +23,7 @@ void testCreatThreadTask() { printf("testThreadTask\n"); logger_init("./log"); - pthread_t tTestLogger, tTestDIDetect, tTestUart, tTestTcp; + pthread_t tTestLogger, tTestDIDetect, tTestUart, tTestTcp, tTest4G, tTestCanSend, tTestCanRecv; // pthread_create(&tTestLogger, NULL, testLoggerThread, "testLoggerThread"); // pthread_join(tTestLogger, NULL); // int ret = pthread_create(&tTestDIDetect, NULL, testDIDetectThread, "testDIDetectThread"); @@ -31,8 +31,14 @@ void testCreatThreadTask() // pthread_join(tTestDIDetect, NULL); // pthread_create(&tTestUart, NULL, testUartThread, "testUartThread"); // pthread_join(tTestUart, NULL); - pthread_create(&tTestTcp, NULL, testTcpThread, "testTcpThread"); - pthread_join(tTestTcp, NULL); + // pthread_create(&tTestTcp, NULL, testTcpThread, "testTcpThread"); + // pthread_join(tTestTcp, NULL); + // pthread_create(&tTest4G, NULL, test4GThread, "test4GThread"); + // pthread_join(tTest4G, NULL); + pthread_create(&tTestCanSend, NULL, testCanSendThread, "testCanSendhread"); + pthread_join(tTestCanSend, NULL); + // pthread_create(&tTestCanRecv, NULL, testCanRecvThread, "testCanRecvhread"); + // pthread_join(tTestCanRecv, NULL); logger_destroy(); } @@ -118,11 +124,47 @@ void testUart() write(devFd, test, strlen(test) + 1); } +//服务端功能测试 void *testTcpThread(void *arg) { logger_level_printf(LOGGER_DEBUG_LEVEL, arg); printf("TCP Serve Start\n"); // getInterfacesAndIPs(); - tcpServe(8888); + tcpServe(8888); +} + +//客户端功能测试 +void *test4GThread(void *arg) +{ + logger_level_printf(LOGGER_DEBUG_LEVEL, arg); + printf("client test!\n"); + client(INTERFACE, SERVER_ADDR, PORT); +} + +//Can接收功能测试 +void *testCanRecvThread(void *arg) +{ + logger_level_printf(LOGGER_DEBUG_LEVEL, arg); + printf("Can Recv test!\n"); + unsigned int canIDs[] = {0x123, 0x456, 0x789}; + while(1) { + printf("enter the can recv loop\n"); + can_recv(CANNUM_RECV, canIDs, CANIDNUM, CANDLC_RECV); + sleep(1); + } +} + +//Can发送功能测试 +void *testCanSendThread(void *arg) +{ + logger_level_printf(LOGGER_DEBUG_LEVEL, arg); + printf("Can Send test!\n"); + unsigned int canID_send = 0x112233; + char * can_send_data = "01 02 03 04 05 06 07 08 09 10"; + while(1) { + printf("enter the can send loop\n"); + can_send(CANNUM_SEND, canID_send, can_send_data, CANDLC_SEND); + sleep(1); + } } diff --git a/test/test.h b/test/test.h index f13465e..8fa8875 100644 --- a/test/test.h +++ b/test/test.h @@ -1,8 +1,6 @@ #ifndef __TEST_H_ #define __TEST_H_ -#define _DEFAULT_SOURCE - void runTest(); void testDI(); void testDO(); @@ -11,4 +9,8 @@ void testCreatThreadTask(); void *testLoggerThread(void *arg); void *testDIDetectThread(void *arg); void *testUartThread(void *arg); -#endif \ No newline at end of file +void *testTcpThread(void *arg); +void *test4GThread(void *arg); +void *testCanSendThread(void *arg); +void *testCanRecvThread(void *arg); +#endif