diff --git a/mbus/mbus-serial.c b/mbus/mbus-serial.c index ec6b112..34e1e8b 100644 --- a/mbus/mbus-serial.c +++ b/mbus/mbus-serial.c @@ -223,7 +223,7 @@ int mbus_serial_recv_frame(mbus_serial_handle *handle, mbus_frame *frame) { char buff[PACKET_BUFF_SIZE]; - int len, remaining, nread; + int len, remaining, nread, timeouts; if (handle == NULL || frame == NULL) { @@ -238,6 +238,7 @@ mbus_serial_recv_frame(mbus_serial_handle *handle, mbus_frame *frame) // remaining = 1; // start by reading 1 byte len = 0; + timeouts = 0; do { //printf("%s: Attempt to read %d bytes [len = %d]\n", __PRETTY_FUNCTION__, remaining, len); @@ -249,7 +250,19 @@ mbus_serial_recv_frame(mbus_serial_handle *handle, mbus_frame *frame) return -1; } -// printf("%s: Got %d byte [remaining %d, len %d]\n", __PRETTY_FUNCTION__, nread, remaining, len); +// printf("%s: Got %d byte [remaining %d, len %d]\n", __PRETTY_FUNCTION__, nread, remaining, len); + + if (nread == 0) + { + timeouts++; + + if (timeouts >= 3) + { + // abort to avoid endless loop + fprintf(stderr, "%s: Timeout\n", __PRETTY_FUNCTION__); + break; + } + } len += nread; diff --git a/mbus/mbus-tcp.c b/mbus/mbus-tcp.c index 17150fb..53cfbd1 100644 --- a/mbus/mbus-tcp.c +++ b/mbus/mbus-tcp.c @@ -165,7 +165,7 @@ int mbus_tcp_recv_frame(mbus_tcp_handle *handle, mbus_frame *frame) { char buff[PACKET_BUFF_SIZE]; - int len, remaining, nread; + int len, remaining, nread, timeouts; if (handle == NULL || frame == NULL) { @@ -180,6 +180,7 @@ mbus_tcp_recv_frame(mbus_tcp_handle *handle, mbus_frame *frame) // remaining = 1; // start by reading 1 byte len = 0; + timeouts = 0; do { @@ -188,6 +189,18 @@ mbus_tcp_recv_frame(mbus_tcp_handle *handle, mbus_frame *frame) mbus_error_str_set("M-Bus tcp transport layer failed to read data."); return -1; } + + if (nread == 0) + { + timeouts++; + + if (timeouts >= 3) + { + // abort to avoid endless loop + fprintf(stderr, "%s: Timeout\n", __PRETTY_FUNCTION__); + break; + } + } len += nread;