Skip to content

Commit b6e4437

Browse files
gijzelaerrclaude
andcommitted
Mark connection as disconnected on TCP errors
Set self.connected = False in send_data(), receive_data(), and _recv_exact() when TCP errors or timeouts occur. This ensures get_connected() returns False after a network failure, preventing stale data from being returned on subsequent operations. After a TCP error, users must reconnect to the PLC, which is the correct behavior per the original snap7 documentation. Fixes #70 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent 68af88d commit b6e4437

1 file changed

Lines changed: 6 additions & 0 deletions

File tree

snap7/connection.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ def send_data(self, data: bytes) -> None:
129129
self.socket.sendall(tpkt_frame)
130130
logger.debug(f"Sent {len(tpkt_frame)} bytes")
131131
except socket.error as e:
132+
self.connected = False
132133
raise S7ConnectionError(f"Send failed: {e}")
133134

134135
def receive_data(self) -> bytes:
@@ -162,8 +163,10 @@ def receive_data(self) -> bytes:
162163
return self._parse_cotp_data(payload)
163164

164165
except socket.timeout:
166+
self.connected = False
165167
raise S7TimeoutError("Receive timeout")
166168
except socket.error as e:
169+
self.connected = False
167170
raise S7ConnectionError(f"Receive failed: {e}")
168171

169172
def _tcp_connect(self) -> None:
@@ -373,11 +376,14 @@ def _recv_exact(self, size: int) -> bytes:
373376
try:
374377
chunk = self.socket.recv(size - len(data))
375378
if not chunk:
379+
self.connected = False
376380
raise S7ConnectionError("Connection closed by peer")
377381
data.extend(chunk)
378382
except socket.timeout:
383+
self.connected = False
379384
raise S7TimeoutError("Receive timeout")
380385
except socket.error as e:
386+
self.connected = False
381387
raise S7ConnectionError(f"Receive error: {e}")
382388

383389
return bytes(data)

0 commit comments

Comments
 (0)