From 9ebcfe9cf4afe75d5aa669926a462e14612d6623 Mon Sep 17 00:00:00 2001
From: Ido Szargel <78739764+ido-szargel@users.noreply.github.com>
Date: Mon, 13 May 2024 23:45:00 +0200
Subject: [PATCH] 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.
---
 dsmr_parser/clients/socket_.py | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/dsmr_parser/clients/socket_.py b/dsmr_parser/clients/socket_.py
index 968a582..fddee61 100644
--- a/dsmr_parser/clients/socket_.py
+++ b/dsmr_parser/clients/socket_.py
@@ -31,12 +31,16 @@ class SocketReader(object):
         buffer = b""
 
         with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as socket_handle:
-
+            socket_handle.settimeout(60)
             socket_handle.connect((self.host, self.port))
 
             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)
 
                 if len(lines) == 0: