Skip to content

Commit

Permalink
NADReceiverTCP: use context handler to close socket
Browse files Browse the repository at this point in the history
This makes sure that the socket is closed in all code paths and
removes a bit of the special case handling making the code
slightly simpler.
  • Loading branch information
gladhorn committed May 24, 2020
1 parent c44a865 commit fc75a00
Showing 1 changed file with 15 additions and 18 deletions.
33 changes: 15 additions & 18 deletions nad_receiver/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,24 +222,21 @@ def _send(self, message: str, read_reply: bool =False) -> Optional[str]:
sleep(0.1)
if not sock:
return None
sock.send(codecs.decode(message.encode(), encoding='hex_codec'))
if read_reply:
sleep(0.1)
reply = ''
tries = 0
max_tries = 20
while len(reply) < len(message) and tries < max_tries:
try:
reply += codecs.encode(sock.recv(self.BUFFERSIZE), 'hex')\
.decode("utf-8")
except (ConnectionError, BrokenPipeError):
pass
tries += 1
sock.close()
if tries >= max_tries:
return None
return reply
sock.close()
with sock:
sock.send(codecs.decode(message.encode(), encoding='hex_codec'))
if read_reply:
sleep(0.1)
reply = ''
tries = 0
max_tries = 20
while len(reply) < len(message) and tries < max_tries:
try:
reply += codecs.encode(sock.recv(self.BUFFERSIZE), 'hex')\
.decode("utf-8")
return reply
except (ConnectionError, BrokenPipeError):
pass
tries += 1
return None

def status(self) -> Optional[Dict[str, Any]]:
Expand Down

0 comments on commit fc75a00

Please sign in to comment.