Add socket timeout

When reading data through a device called 'chargee sparky' I noticed that every time the wireless connection of the device is lost it stops transmitting data.
dsmr_parser based on the example in the README doesn't do anything and will simply sit there for hours waiting for the next telegram.
Adding a 1 minute timeout and breaking allows something upstream to notice, in my case my python runs as systemd service and once it exits it's restarted.
This commit is contained in:
Ido Szargel 2024-05-13 23:45:00 +02:00 committed by GitHub
parent 3cf627eedc
commit 9ebcfe9cf4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -31,12 +31,16 @@ class SocketReader(object):
buffer = b"" buffer = b""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socket_handle: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socket_handle:
socket_handle.settimeout(60)
socket_handle.connect((self.host, self.port)) socket_handle.connect((self.host, self.port))
while True: while True:
buffer += socket_handle.recv(self.BUFFER_SIZE) try:
buffer += socket_handle.recv(self.BUFFER_SIZE)
except socket.timeout::
logger.error("Socket timeout occurred, exiting")
break
lines = buffer.splitlines(keepends=True) lines = buffer.splitlines(keepends=True)
if len(lines) == 0: if len(lines) == 0: