diff --git a/socs/common/moxa_serial.py b/socs/common/moxa_serial.py index 8e5f6021c..95129a0ee 100644 --- a/socs/common/moxa_serial.py +++ b/socs/common/moxa_serial.py @@ -87,8 +87,11 @@ def readexactly(self, n): self.settimeout(newtimeout) try: msg = self.sock.recv(n, socket.MSG_PEEK) - except BaseException: + except (TimeoutError, BlockingIOError): pass + except Exception as e: + print(f"Caught unexpected {type(e).__name__} exception:") + print(f" {e}") # Flush the message out if you got everything if len(msg) == n: if self.encoded: @@ -114,13 +117,16 @@ def readbuf_slow(self, n): try: for i in range(n): msg += self.sock.recv(1) - except BaseException: + except (TimeoutError, BlockingIOError): pass + except Exception as e: + print(f"Caught unexpected {type(e).__name__} exception:") + print(f" {e}") self.sock.setblocking(1) # belt and suspenders self.settimeout(self.__timeout) return msg - def readbuf(self, n): + def readbuf(self, n, max_loop=10): """Returns whatever is currently in the buffer. Suitable for large buffers. @@ -128,14 +134,23 @@ def readbuf(self, n): n: Number of bytes to read. """ - if n == 0: - return '' - try: - msg = self.sock.recv(n) - except BaseException: - msg = '' - n2 = min(n - len(msg), n / 2) - return msg + self.readbuf(n2) + n_current = n + msg = b'' + for i in range(max_loop): + if n_current <= 0: + return msg + try: + msg_current = self.sock.recv(n) + except (TimeoutError, BlockingIOError): + msg_current = b'' + except Exception as e: + print(f"Caught unexpected {type(e).__name__} exception:") + print(f" {e}") + msg_current = b'' + msg += msg_current + n_current -= len(msg_current) + + return msg def readpacket(self, n): """Like ``read()``, but may not return everything if the moxa box @@ -147,7 +162,11 @@ def readpacket(self, n): """ try: msg = self.sock.recv(n) - except BaseException: + except (TimeoutError, BlockingIOError): + msg = '' + except Exception as e: + print(f"Caught unexpected {type(e).__name__} exception:") + print(f" {e}") msg = '' return msg @@ -221,8 +240,11 @@ def flushInput(self): try: while len(self.sock.recv(1)) > 0: pass - except BaseException: + except (TimeoutError, BlockingIOError): pass + except Exception as e: + print(f"Caught unexpected {type(e).__name__} exception:") + print(f" {e}") self.sock.setblocking(1) self.sock.settimeout(self.__timeout)