Skip to content
Open
Show file tree
Hide file tree
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
9 changes: 9 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ Unreleased
* data_3: Received data from u_send transmissions
* data_4: Received data from u_send transmissions
* datablock_count: 0 for b_send or 1-4 for u_send transmissions.
* `set_s5time()` writes an `S5TIME` value from a `timedelta`, or from the string that `get_s5time()` returns. It picks
the smallest time base that holds the value and truncates to that base's resolution, as STEP 7 does for an `S5T#`
constant. `S5TIME` tags can now be written with `write_tag` and `encode_tag`, and `Row` sets `S5TIME` fields.
Previously writing an `S5TIME` tag raised `ValueError` (#1002).

### Bug fixes

Expand All @@ -25,6 +29,11 @@ Unreleased
connection that way. A CP 343-1 answered the disconnect request with a reset and kept the connection's resource
until the PLC restarted. The reporter confirmed on a CPU 313C behind a CP 343-1 that the resource is now
released (#972, #987).
* get_status(): A lost connection drops the status from 2 (connected) to 1 (started). Previously, the status remained
at 2. (#1000).
* `b_recv()` returns 1 and not -1 on a timeout, as documented. The read timeout no longer drops the connection (#1000).
* `ISOTCPConnection._recv_exact()`: If a timeout occurs before the first byte of a frame, the connection remains
intact. If a frame is incomplete, an S7ConnectionError is raised and the connection state is reset (#1000).

3.6.0
-----
Expand Down
12 changes: 10 additions & 2 deletions snap7/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,14 +219,21 @@ def receive_data(self) -> bytes:
version, reserved, length = struct.unpack(">BBH", tpkt_header)

if version != 3:
self.connected = False
raise S7ConnectionError(f"Invalid TPKT version: {version}")

# Receive remaining data
remaining = length - 4
if length < 7:
self.connected = False
raise S7ConnectionError("Invalid TPKT length")

payload = self._recv_exact(remaining)
try:
payload = self._recv_exact(remaining)

except S7TimeoutError:
self.connected = False
raise S7ConnectionError("Timeout receiving payload data")

# Parse COTP header and extract data
logger.debug(f"Received TPKT: version={version} length={length} payload ({len(payload)} bytes): {payload.hex(' ')}")
Expand Down Expand Up @@ -491,7 +498,8 @@ def _recv_exact(self, size: int) -> bytes:
raise S7ConnectionError("Connection closed by peer")
data.extend(chunk)
except socket.timeout:
self.connected = False
if len(data) > 0:
self.connected = False
raise S7TimeoutError("Receive timeout")
except socket.error as e:
self.connected = False
Expand Down
10 changes: 4 additions & 6 deletions snap7/partner.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import logging
import sys
import threading
import time
from typing import Optional, Tuple, Callable, Type
from queue import Queue, Empty
from typing import Any
Expand Down Expand Up @@ -478,7 +479,7 @@ def b_recv(self) -> int:
logger.debug(f"Received {bytes_rcv} bytes synchronously")
return 0

except socket.timeout:
except (S7TimeoutError, socket.timeout):
self._recv_data = None
return 1 # Timeout
except Exception as e:
Expand Down Expand Up @@ -730,7 +731,7 @@ def get_status(self) -> c_int32:
Returns:
Status code (0=stopped, 1=running, 2=connected)
"""
if self.connected:
if self.connected and self._connection is not None and self._connection.connected:
return c_int32(PartnerStatus.CONNECTED)
elif self.running:
return c_int32(PartnerStatus.RUNNING)
Expand Down Expand Up @@ -1060,10 +1061,7 @@ def _recv_listener(self) -> None:
except OSError:
pass
except (S7TimeoutError, socket.timeout):
# Timeout is expected — restore connected flag since
# ISOTCPConnection.receive_data() sets it to False on timeout
if conn is not None:
conn.connected = True
time.sleep(0.001)
continue
except Exception as e:
self.recv_errors += 1
Expand Down
2 changes: 1 addition & 1 deletion tests/test_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ def test_receive_timeout(self) -> None:
mock_socket.recv.side_effect = socket.timeout("timeout")
with pytest.raises(S7TimeoutError, match="Receive timeout"):
conn.receive_data()
assert conn.connected is False
assert conn.connected is True

def test_receive_socket_error(self) -> None:
conn = ISOTCPConnection("1.2.3.4")
Expand Down
48 changes: 47 additions & 1 deletion tests/test_partner.py
Original file line number Diff line number Diff line change
Expand Up @@ -973,6 +973,19 @@ def test_status_after_stop(self) -> None:
pa.stop()
pb.stop()

def test_status_after_peer_closes(self) -> None:
sock_a, sock_b = _make_socket_pair()
pa, pb = Partner(), Partner()
try:
_wire_partner(pa, sock_a)
_wire_partner(pb, sock_b)
sock_b.close()
pa.b_recv()
assert pa.get_status().value == PartnerStatus.RUNNING
finally:
pa.stop()
pb.stop()

def test_recv_callback_fires(self) -> None:
sock_a, sock_b = _make_socket_pair()
pa, pb = Partner(), Partner()
Expand Down Expand Up @@ -1287,7 +1300,7 @@ def do_send() -> None:
pb.stop()

def test_b_recv_error_returns_negative(self) -> None:
"""b_recv returns -1 on receive error when no data arrives."""
"""b_recv returns -1 on receive error after the peer closes."""
sock_a, sock_b = _make_socket_pair()
pa, pb = Partner(), Partner()
try:
Expand All @@ -1301,6 +1314,39 @@ def test_b_recv_error_returns_negative(self) -> None:
pa.stop()
pb.stop()

def test_b_recv_timeout_returns_1(self) -> None:
"""b_recv returns 1 on timeout error when no data arrives."""
sock_a, sock_b = _make_socket_pair()
sock_b.settimeout(0.1)
pa, pb = Partner(), Partner()
try:
_wire_partner(pa, sock_a)
_wire_partner(pb, sock_b)
result = pb.b_recv()
assert result == 1
assert pb.get_status().value == PartnerStatus.CONNECTED
finally:
pa.stop()
pb.stop()

def test_status_after_as_b_recv(self) -> None:
"""Async receive without data - the status staying 2 = connected."""
sock_a, sock_b = _make_socket_pair()
pa, pb = Partner(), Partner()
try:
_wire_partner(pa, sock_a)
_wire_partner(pb, sock_b)

assert pb.as_b_recv() == 0

result = pb.wait_as_b_recv_completion(timeout=1000)

assert result == -1
assert pb.get_status().value == PartnerStatus.CONNECTED
finally:
pa.stop()
pb.stop()


# ---------------------------------------------------------------------------
# Passive partner accept/listen tests
Expand Down
Loading