Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 35 additions & 13 deletions socs/common/moxa_serial.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -114,28 +117,40 @@ 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.

Args:
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
Expand All @@ -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

Expand Down Expand Up @@ -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)

Expand Down