From d33fff5986a49295f935f095068e920d9ba3ee2e Mon Sep 17 00:00:00 2001 From: hxy7yx <1595670487@qq.com> Date: Mon, 23 Dec 2024 15:06:34 +0800 Subject: [PATCH] fix(modbus):clear recv buf before sending --- include/neuron/connection/neu_connection.h | 2 ++ plugins/modbus/modbus_req.c | 2 ++ src/connection/connection.c | 34 ++++++++++++++++++++++ 3 files changed, 38 insertions(+) diff --git a/include/neuron/connection/neu_connection.h b/include/neuron/connection/neu_connection.h index d12ac7305..59f153a85 100644 --- a/include/neuron/connection/neu_connection.h +++ b/include/neuron/connection/neu_connection.h @@ -254,6 +254,8 @@ ssize_t neu_conn_recv(neu_conn_t *conn, uint8_t *buf, ssize_t len); ssize_t neu_conn_udp_recvfrom(neu_conn_t *conn, uint8_t *buf, ssize_t len, void *src); +void neu_conn_clear_recv_buffer(neu_conn_t *conn); + /** * @brief Specify the client to send data. * diff --git a/plugins/modbus/modbus_req.c b/plugins/modbus/modbus_req.c index 59db14a05..6de0b6b81 100644 --- a/plugins/modbus/modbus_req.c +++ b/plugins/modbus/modbus_req.c @@ -113,6 +113,8 @@ int modbus_send_msg(void *ctx, uint16_t n_byte, uint8_t *bytes) neu_plugin_t *plugin = (neu_plugin_t *) ctx; int ret = 0; + neu_conn_clear_recv_buffer(plugin->conn); + plog_send_protocol(plugin, bytes, n_byte); if (plugin->is_server) { diff --git a/src/connection/connection.c b/src/connection/connection.c index c862d9246..38d312b66 100644 --- a/src/connection/connection.c +++ b/src/connection/connection.c @@ -407,6 +407,40 @@ ssize_t neu_conn_send(neu_conn_t *conn, uint8_t *buf, ssize_t len) return ret; } +void neu_conn_clear_recv_buffer(neu_conn_t *conn) +{ + if (!conn->is_connected) { + return; + } + + uint8_t temp_buf[256]; + ssize_t ret; + + switch (conn->param.type) { + case NEU_CONN_TCP_CLIENT: + do { + ret = recv(conn->fd, temp_buf, sizeof(temp_buf), MSG_DONTWAIT); + + if (ret > 0) { + continue; + } else if (ret == 0) { + zlog_info(conn->param.log, + "Connection closed while clearing buffer."); + break; + } else if (errno == EAGAIN || errno == EWOULDBLOCK) { + break; + } else { + zlog_error(conn->param.log, "Error clearing buffer: %s", + strerror(errno)); + break; + } + } while (ret > 0); + break; + default: + break; + } +} + ssize_t neu_conn_recv(neu_conn_t *conn, uint8_t *buf, ssize_t len) { ssize_t ret = 0;