@@ -17,7 +17,7 @@ namespace TCP {
17
17
18
18
static constexpr int MAX_REGS = 0x10000 ;
19
19
20
- Slave::Slave (const std::string &ip, unsigned short port, modbus_mapping_t *mapping) {
20
+ Slave::Slave (const std::string &ip, unsigned short port, modbus_mapping_t *mapping, std:: size_t tcp_timeout ) {
21
21
// create modbus object
22
22
modbus = modbus_new_tcp (ip.c_str (), static_cast <int >(port));
23
23
if (modbus == nullptr ) {
@@ -54,10 +54,30 @@ Slave::Slave(const std::string &ip, unsigned short port, modbus_mapping_t *mappi
54
54
throw std::system_error (errno, std::generic_category (), " Failed to set socket option SO_KEEPALIVE" );
55
55
}
56
56
57
- unsigned user_timeout = 5000 ;
58
- tmp = setsockopt (socket, IPPROTO_TCP, TCP_USER_TIMEOUT, &keepalive, sizeof (user_timeout));
59
- if (tmp != 0 ) {
60
- throw std::system_error (errno, std::generic_category (), " Failed to set socket option SO_KEEPALIVE" );
57
+ if (tcp_timeout) {
58
+ unsigned user_timeout = static_cast <unsigned >(tcp_timeout) * 1000 ;
59
+ tmp = setsockopt (socket, IPPROTO_TCP, TCP_USER_TIMEOUT, &user_timeout, sizeof (keepalive));
60
+ if (tmp != 0 ) {
61
+ throw std::system_error (errno, std::generic_category (), " Failed to set socket option TCP_USER_TIMEOUT" );
62
+ }
63
+
64
+ unsigned keepidle = 1 ;
65
+ tmp = setsockopt (socket, IPPROTO_TCP, TCP_KEEPIDLE, &keepidle, sizeof (keepidle));
66
+ if (tmp != 0 ) {
67
+ throw std::system_error (errno, std::generic_category (), " Failed to set socket option TCP_KEEPIDLE" );
68
+ }
69
+
70
+ unsigned keepintvl = 1 ;
71
+ tmp = setsockopt (socket, IPPROTO_TCP, TCP_KEEPINTVL, &keepintvl, sizeof (keepintvl));
72
+ if (tmp != 0 ) {
73
+ throw std::system_error (errno, std::generic_category (), " Failed to set socket option TCP_KEEPINTVL" );
74
+ }
75
+
76
+ unsigned keepcnt = static_cast <unsigned >(tcp_timeout);
77
+ tmp = setsockopt (socket, IPPROTO_TCP, TCP_KEEPCNT, &keepcnt, sizeof (keepcnt));
78
+ if (tmp != 0 ) {
79
+ throw std::system_error (errno, std::generic_category (), " Failed to set socket option TCP_KEEPCNT" );
80
+ }
61
81
}
62
82
}
63
83
0 commit comments