2 * Copyright © Stéphane Raimbault <stephane.raimbault@gmail.com>
4 * SPDX-License-Identifier: LGPL-2.1-or-later
7 #ifndef MODBUS_PRIVATE_H
8 #define MODBUS_PRIVATE_H
13 # include <sys/time.h>
21 #include <sys/types.h>
27 /* It's not really the minimal length (the real one is report slave ID
28 * in RTU (4 bytes)) but it's a convenient size to use in RTU or TCP
29 * communications to read many values or write a single one.
31 * - HEADER_LENGTH_TCP (7) + function (1) + address (2) + number (2)
32 * - HEADER_LENGTH_RTU (1) + function (1) + address (2) + number (2) + CRC (2)
34 #define _MIN_REQ_LENGTH 12
36 #define _REPORT_SLAVE_ID 180
38 #define _MODBUS_EXCEPTION_RSP_LENGTH 5
40 /* Timeouts in microsecond (0.5 s) */
41 #define _RESPONSE_TIMEOUT 500000
42 #define _BYTE_TIMEOUT 500000
45 _MODBUS_BACKEND_TYPE_RTU
= 0,
46 _MODBUS_BACKEND_TYPE_TCP
47 } modbus_backend_type_t
;
50 * ---------- Request Indication ----------
51 * | Client | ---------------------->| Server |
52 * ---------- Confirmation Response ----------
55 /* Request message on the server side */
57 /* Request message on the client side */
61 /* This structure reduces the number of params in functions and so
62 * optimizes the speed of execution (~ 37%). */
69 typedef struct _modbus_backend
{
70 unsigned int backend_type
;
71 unsigned int header_length
;
72 unsigned int checksum_length
;
73 unsigned int max_adu_length
;
74 int (*set_slave
)(modbus_t
*ctx
, int slave
);
75 int (*build_request_basis
)(
76 modbus_t
*ctx
, int function
, int addr
, int nb
, uint8_t *req
);
77 int (*build_response_basis
)(sft_t
*sft
, uint8_t *rsp
);
78 int (*get_response_tid
)(const uint8_t *req
);
79 int (*send_msg_pre
)(uint8_t *req
, int req_length
);
80 ssize_t (*send
)(modbus_t
*ctx
, const uint8_t *req
, int req_length
);
81 int (*receive
)(modbus_t
*ctx
, uint8_t *req
);
82 ssize_t (*recv
)(modbus_t
*ctx
, uint8_t *rsp
, int rsp_length
);
83 int (*check_integrity
)(modbus_t
*ctx
, uint8_t *msg
, const int msg_length
);
84 int (*pre_check_confirmation
)(modbus_t
*ctx
,
88 int (*connect
)(modbus_t
*ctx
);
89 unsigned int (*is_connected
)(modbus_t
*ctx
);
90 void (*close
)(modbus_t
*ctx
);
91 int (*flush
)(modbus_t
*ctx
);
92 int (*select
)(modbus_t
*ctx
, fd_set
*rset
, struct timeval
*tv
, int msg_length
);
93 void (*free
)(modbus_t
*ctx
);
99 /* Socket or file descriptor */
104 struct timeval response_timeout
;
105 struct timeval byte_timeout
;
106 struct timeval indication_timeout
;
107 const modbus_backend_t
*backend
;
111 void _modbus_init_common(modbus_t
*ctx
);
112 void _error_print(modbus_t
*ctx
, const char *context
);
113 int _modbus_receive_msg(modbus_t
*ctx
, uint8_t *msg
, msg_type_t msg_type
);
116 size_t strlcpy(char *dest
, const char *src
, size_t dest_size
);
121 #endif /* MODBUS_PRIVATE_H */