python-snap7 3.4.0__py3-none-any.whl → 3.6.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {python_snap7-3.4.0.dist-info → python_snap7-3.6.0.dist-info}/METADATA +2 -2
- {python_snap7-3.4.0.dist-info → python_snap7-3.6.0.dist-info}/RECORD +13 -13
- snap7/async_client.py +16 -9
- snap7/client.py +40 -19
- snap7/optimizer.py +16 -3
- snap7/partner.py +260 -55
- snap7/s7protocol.py +17 -11
- snap7/server/__init__.py +56 -13
- snap7/szl.py +36 -0
- {python_snap7-3.4.0.dist-info → python_snap7-3.6.0.dist-info}/WHEEL +0 -0
- {python_snap7-3.4.0.dist-info → python_snap7-3.6.0.dist-info}/entry_points.txt +0 -0
- {python_snap7-3.4.0.dist-info → python_snap7-3.6.0.dist-info}/licenses/LICENSE +0 -0
- {python_snap7-3.4.0.dist-info → python_snap7-3.6.0.dist-info}/top_level.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: python-snap7
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.6.0
|
|
4
4
|
Summary: Pure Python S7 communication library for Siemens PLCs
|
|
5
5
|
Author-email: Gijs Molenaar <gijsmolenaar@gmail.com>
|
|
6
6
|
License-Expression: MIT
|
|
@@ -12,7 +12,7 @@ Classifier: Environment :: Console
|
|
|
12
12
|
Classifier: Topic :: System :: Hardware
|
|
13
13
|
Classifier: Intended Audience :: Developers
|
|
14
14
|
Classifier: Intended Audience :: Manufacturing
|
|
15
|
-
Classifier: Operating System ::
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
16
|
Classifier: Programming Language :: Python :: 3.10
|
|
17
17
|
Classifier: Programming Language :: Python :: 3.11
|
|
18
18
|
Classifier: Programming Language :: Python :: 3.12
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
python_snap7-3.
|
|
1
|
+
python_snap7-3.6.0.dist-info/licenses/LICENSE,sha256=PIihE_yP-8gc-ff9ikvQQPOa0biOCZ6Bc-6h3G3xRUQ,1097
|
|
2
2
|
s7/__init__.py,sha256=q6E4rA1BDx36PPkJS55xv7XCxwlaQeEK6HNotFjLeYo,1096
|
|
3
3
|
snap7/__init__.py,sha256=2NAAE1oaSSd7DqPl0dx7jNXtsM2PRBWRm9X-bkmgC6U,1275
|
|
4
|
-
snap7/async_client.py,sha256=
|
|
4
|
+
snap7/async_client.py,sha256=_cb17lJaXMApfAEOPzH9AZZa7QFE1TkvMLvY6ywNitE,66408
|
|
5
5
|
snap7/cli.py,sha256=L1B7NMAemDcl93JUSqJV3Ls_CN2ghlG75nTMD08JkMs,13787
|
|
6
|
-
snap7/client.py,sha256=
|
|
6
|
+
snap7/client.py,sha256=iNzg2RPTwUA2px3Oq_lYB18-0KhutLIR6f0nCD_klHk,103674
|
|
7
7
|
snap7/client_base.py,sha256=tNZs_MA8FGit8pg9axNoljH1kFToDI1HIzXC8WQLYHs,11324
|
|
8
8
|
snap7/connection.py,sha256=W-jOV7hXVI-cuCFcqRzXY3vFp8weeJh0zEJzXNLLBss,19053
|
|
9
9
|
snap7/datatypes.py,sha256=Gqu1XDuKkQI76n4TYrFrhm0RlPz4XNA5GKA-GJJXJDU,12042
|
|
@@ -12,23 +12,23 @@ snap7/discovery.py,sha256=LONPYg83b2quKXht6y_GTTArdxitjD8DoGyaHfe9B1w,3964
|
|
|
12
12
|
snap7/error.py,sha256=S5BquFFSL1NpgdytIpOD_FzhN6gOCngSkxJVZT4rxdw,21323
|
|
13
13
|
snap7/log.py,sha256=XX4UyPgByz3EhTc39BTGY454fHvYmiJAX4v-a-gkIEY,4968
|
|
14
14
|
snap7/logo.py,sha256=0h-EZ5K86Qddna_lryBn6xLXLVwnznYJuMGuevzH6bI,9192
|
|
15
|
-
snap7/optimizer.py,sha256=
|
|
16
|
-
snap7/partner.py,sha256=
|
|
15
|
+
snap7/optimizer.py,sha256=YK6B2RedZ59kIIYH8fV70eVCz-T694Kl6c4ltcu61FQ,9944
|
|
16
|
+
snap7/partner.py,sha256=NhiYAZ8zN5DpnnsuVigaYCyGBQVRdNJgJcHQi_7HN-4,45698
|
|
17
17
|
snap7/ppi.py,sha256=p0fVelfUQOT3QH5uuWOjpDxA5IyT3gx5FzCMaYYEuWQ,16070
|
|
18
18
|
snap7/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
19
19
|
snap7/rate_limiter.py,sha256=dnXCOJLWmszo8oskbFM0om0gPC4LHHCOr-Nt22tImeU,4151
|
|
20
|
-
snap7/s7protocol.py,sha256=
|
|
21
|
-
snap7/szl.py,sha256=
|
|
20
|
+
snap7/s7protocol.py,sha256=kSKtJYBcSYLVSSMiVlDwjxZR7x6NyhGsft4oAMso-mg,71107
|
|
21
|
+
snap7/szl.py,sha256=eQsSTw_GT9l_OXZ8eYC_notJct5qowNXSa3T3LNq7EY,9472
|
|
22
22
|
snap7/tags.py,sha256=5YmYKtRXc3GMpqqkv6J0q1IHZ_k5y17yNLqFx6KjoqI,34332
|
|
23
23
|
snap7/type.py,sha256=EiXqU0ayYYxlM-5fUcPL7psgL1EGNNqAa7JXH4QlAnU,9752
|
|
24
|
-
snap7/server/__init__.py,sha256=
|
|
24
|
+
snap7/server/__init__.py,sha256=D47Huk07oeDB7YKfUxuf4i3-skXNJYisHTggqvEfv3c,120493
|
|
25
25
|
snap7/server/__main__.py,sha256=OdOgyMmFThjSe2jSgvlbkquGYnZcBW6wubs2ldhNSOE,1206
|
|
26
26
|
snap7/util/__init__.py,sha256=d6n2oy7tNYke1ia0TUyWz_ni3l0XN1qvilM5sW0T-Es,1874
|
|
27
27
|
snap7/util/db.py,sha256=geesYS2oyOuTADOJa2me1p1rqJVzPuLTCfye6JIeav0,27120
|
|
28
28
|
snap7/util/getters.py,sha256=UjojRLazJECrngor_8BI38R8VMEMdXusC95zqNEErJg,25767
|
|
29
29
|
snap7/util/setters.py,sha256=InGXodcfGxNvdGQ5Y589aBOFqa-e2hIUqNCk-HqziiE,29335
|
|
30
|
-
python_snap7-3.
|
|
31
|
-
python_snap7-3.
|
|
32
|
-
python_snap7-3.
|
|
33
|
-
python_snap7-3.
|
|
34
|
-
python_snap7-3.
|
|
30
|
+
python_snap7-3.6.0.dist-info/METADATA,sha256=ooXfoftMoE-6h6_WlvjXk0FMYvlxcdoCTYaH-tIajxQ,4678
|
|
31
|
+
python_snap7-3.6.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
32
|
+
python_snap7-3.6.0.dist-info/entry_points.txt,sha256=IPZyYr1lKyavXXpAc4xO505afTGwTY8GmNFuy5lsSiM,75
|
|
33
|
+
python_snap7-3.6.0.dist-info/top_level.txt,sha256=PTgDoDG45QNL2XIE9RM7S_ZCdWQjtMMuXNyrI2UdnbU,9
|
|
34
|
+
python_snap7-3.6.0.dist-info/RECORD,,
|
snap7/async_client.py
CHANGED
|
@@ -23,7 +23,7 @@ from .error import S7Error, S7ConnectionError, S7ProtocolError, S7TimeoutError
|
|
|
23
23
|
from .client_base import ClientMixin, _instrumented
|
|
24
24
|
from .tags import Tag, decode_tag, encode_tag
|
|
25
25
|
from .client import Client
|
|
26
|
-
from .szl import parse_cp_info_szl, parse_cpu_info_szl, parse_order_code_szl, parse_protection_szl
|
|
26
|
+
from .szl import parse_cp_info_szl, parse_cpu_info_szl, parse_cpu_state_szl, parse_order_code_szl, parse_protection_szl
|
|
27
27
|
from .client import _parse_force_szl
|
|
28
28
|
from .rate_limiter import RateLimitAlgorithm, RateLimitBehavior, RequestRateLimiter
|
|
29
29
|
from .type import (
|
|
@@ -811,8 +811,10 @@ class AsyncClient(ClientMixin):
|
|
|
811
811
|
return await self.write_area(Area(resolved.area), resolved.db_number, resolved.byte_offset, buf)
|
|
812
812
|
|
|
813
813
|
async def read_tags(self, tags: "Sequence[Union[Tag, str]]", encoding: str = "latin-1") -> list[Any]:
|
|
814
|
-
"""Read
|
|
814
|
+
"""Read any number of tags, returning the values in input order."""
|
|
815
815
|
resolved = [Tag.from_string(t) if isinstance(t, str) else t for t in tags]
|
|
816
|
+
if any(t.is_symbolic for t in resolved):
|
|
817
|
+
raise NotImplementedError("Symbolic (LID-based) tag access is not supported by the classic S7 client.")
|
|
816
818
|
items = [{"area": Area(t.area), "db_number": t.db_number, "start": t.byte_offset, "size": t.size} for t in resolved]
|
|
817
819
|
_code, data_list = await self.read_multi_vars(items)
|
|
818
820
|
return [decode_tag(t, bytearray(d), encoding=encoding) for t, d in zip(resolved, data_list)]
|
|
@@ -951,15 +953,14 @@ class AsyncClient(ClientMixin):
|
|
|
951
953
|
"""Read multiple variables (sequentially, one read_area per item).
|
|
952
954
|
|
|
953
955
|
Args:
|
|
954
|
-
items: List of item dicts with keys: area, db_number, start, size
|
|
956
|
+
items: List of item dicts with keys: area, db_number, start, size.
|
|
957
|
+
Any number of items is accepted.
|
|
955
958
|
|
|
956
959
|
Returns:
|
|
957
960
|
Tuple of (result_code, list_of_bytearrays)
|
|
958
961
|
"""
|
|
959
962
|
if not items:
|
|
960
963
|
return (0, [])
|
|
961
|
-
if len(items) > self.MAX_VARS:
|
|
962
|
-
raise ValueError(f"Too many items: {len(items)} exceeds MAX_VARS ({self.MAX_VARS})")
|
|
963
964
|
|
|
964
965
|
results: list[bytearray] = []
|
|
965
966
|
for item in items:
|
|
@@ -1115,10 +1116,16 @@ class AsyncClient(ClientMixin):
|
|
|
1115
1116
|
return parse_cpu_info_szl(await self.read_szl(0x001C, 0))
|
|
1116
1117
|
|
|
1117
1118
|
async def get_cpu_state(self) -> str:
|
|
1118
|
-
"""Get CPU state
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1119
|
+
"""Get the CPU operating state by reading SZL 0x0424.
|
|
1120
|
+
|
|
1121
|
+
Returns ``"S7CpuStatusRun"``, ``"S7CpuStatusStop"`` or ``"S7CpuStatusUnknown"``.
|
|
1122
|
+
Startup, HOLD and DEFECT are reported as ``"S7CpuStatusStop"``, as native Snap7 does.
|
|
1123
|
+
|
|
1124
|
+
Raises:
|
|
1125
|
+
S7ConnectionError: If the client is not connected.
|
|
1126
|
+
S7ProtocolError: If the PLC refuses SZL 0x0424 or its reply is too short.
|
|
1127
|
+
"""
|
|
1128
|
+
return parse_cpu_state_szl(await self.read_szl(0x0424, 0))
|
|
1122
1129
|
|
|
1123
1130
|
# ---------------------------------------------------------------
|
|
1124
1131
|
# Upload / Download / Delete
|
snap7/client.py
CHANGED
|
@@ -24,14 +24,14 @@ from ctypes import (
|
|
|
24
24
|
from .connection import ISOTCPConnection
|
|
25
25
|
from .s7protocol import S7Protocol, S7UserDataGroup, S7UserDataSubfunction, get_return_code_description
|
|
26
26
|
from .datatypes import S7DataTypes, S7WordLen
|
|
27
|
-
from .error import S7Error, S7ConnectionError, S7ProtocolError, S7StalePacketError, S7TimeoutError
|
|
27
|
+
from .error import S7Error, S7ConnectionError, S7PacketLostError, S7ProtocolError, S7StalePacketError, S7TimeoutError
|
|
28
28
|
from .client_base import ClientMixin, _instrumented
|
|
29
29
|
from .log import PLCLoggerAdapter, OperationLogger
|
|
30
30
|
from .optimizer import ReadItem, ReadPacket, sort_items, merge_items, packetize, extract_results
|
|
31
31
|
from .rate_limiter import RateLimitAlgorithm, RateLimitBehavior, RequestRateLimiter
|
|
32
32
|
from .tags import Tag, decode_tag, encode_tag
|
|
33
33
|
|
|
34
|
-
from .szl import parse_cp_info_szl, parse_cpu_info_szl, parse_order_code_szl, parse_protection_szl
|
|
34
|
+
from .szl import parse_cp_info_szl, parse_cpu_info_szl, parse_cpu_state_szl, parse_order_code_szl, parse_protection_szl
|
|
35
35
|
from .type import (
|
|
36
36
|
Area,
|
|
37
37
|
Block,
|
|
@@ -107,7 +107,7 @@ class Client(ClientMixin):
|
|
|
107
107
|
>>> client.disconnect()
|
|
108
108
|
"""
|
|
109
109
|
|
|
110
|
-
MAX_VARS = 20 # Max variables per multi-read/multi-write
|
|
110
|
+
MAX_VARS = 20 # Max variables per multi-read/multi-write PDU
|
|
111
111
|
|
|
112
112
|
def __init__(
|
|
113
113
|
self,
|
|
@@ -421,7 +421,7 @@ class Client(ClientMixin):
|
|
|
421
421
|
try:
|
|
422
422
|
with self._reconnect_lock:
|
|
423
423
|
if self.connected and self.connection is not None:
|
|
424
|
-
self.
|
|
424
|
+
self._heartbeat_probe()
|
|
425
425
|
self._is_alive = True
|
|
426
426
|
except Exception as e:
|
|
427
427
|
logger.warning(f"Heartbeat probe failed: {e}")
|
|
@@ -434,6 +434,20 @@ class Client(ClientMixin):
|
|
|
434
434
|
except S7ConnectionError:
|
|
435
435
|
logger.warning("Heartbeat reconnection failed")
|
|
436
436
|
|
|
437
|
+
def _heartbeat_probe(self) -> None:
|
|
438
|
+
"""Ask the PLC for its CPU state to prove the connection is alive.
|
|
439
|
+
|
|
440
|
+
A PLC that answers with a refusal (for example a CPU without
|
|
441
|
+
SZL 0x0424) has still answered, so only a transport failure or a lost
|
|
442
|
+
or stale reply is raised.
|
|
443
|
+
"""
|
|
444
|
+
try:
|
|
445
|
+
self.get_cpu_state()
|
|
446
|
+
except (S7PacketLostError, S7StalePacketError):
|
|
447
|
+
raise
|
|
448
|
+
except (S7ProtocolError, RuntimeError) as e:
|
|
449
|
+
logger.debug(f"Heartbeat probe was refused, connection is alive: {e}")
|
|
450
|
+
|
|
437
451
|
def connect(self, address: str, rack: int, slot: int, tcp_port: int = 102) -> "Client":
|
|
438
452
|
"""
|
|
439
453
|
Connect to S7 PLC.
|
|
@@ -714,10 +728,11 @@ class Client(ClientMixin):
|
|
|
714
728
|
return self.write_area(Area(resolved.area), resolved.db_number, resolved.byte_offset, buf)
|
|
715
729
|
|
|
716
730
|
def read_tags(self, tags: "Sequence[Union[Tag, str]]", encoding: str = "latin-1") -> list[Any]:
|
|
717
|
-
"""Read multiple tags in
|
|
731
|
+
"""Read multiple tags in as few requests as possible.
|
|
718
732
|
|
|
719
733
|
Uses the multi-variable read optimizer when available to batch
|
|
720
|
-
reads into minimal PDU exchanges.
|
|
734
|
+
reads into minimal PDU exchanges. Any number of tags is accepted;
|
|
735
|
+
tags that do not fit in one request go into further requests.
|
|
721
736
|
|
|
722
737
|
Args:
|
|
723
738
|
tags: Sequence of :class:`~snap7.tags.Tag` instances or address strings.
|
|
@@ -727,6 +742,8 @@ class Client(ClientMixin):
|
|
|
727
742
|
List of decoded values in the same order as input.
|
|
728
743
|
"""
|
|
729
744
|
resolved = [Tag.from_string(t) if isinstance(t, str) else t for t in tags]
|
|
745
|
+
if any(t.is_symbolic for t in resolved):
|
|
746
|
+
raise NotImplementedError("Symbolic (LID-based) tag access is not supported by the classic S7 client.")
|
|
730
747
|
items = [{"area": Area(t.area), "db_number": t.db_number, "start": t.byte_offset, "size": t.size} for t in resolved]
|
|
731
748
|
_code, data_list = self.read_multi_vars(items)
|
|
732
749
|
return [decode_tag(t, bytearray(d), encoding=encoding) for t, d in zip(resolved, data_list)]
|
|
@@ -962,12 +979,14 @@ class Client(ClientMixin):
|
|
|
962
979
|
|
|
963
980
|
@_instrumented("read_multi_vars")
|
|
964
981
|
def read_multi_vars(self, items: Union[List[dict[str, Any]], "Array[S7DataItem]"]) -> Tuple[int, Any]:
|
|
965
|
-
"""Read multiple variables in
|
|
982
|
+
"""Read multiple variables in as few requests as possible.
|
|
966
983
|
|
|
967
984
|
When given a list of dicts with two or more items, uses the multi-variable
|
|
968
985
|
read optimizer to merge adjacent reads and pack them into minimal PDU
|
|
969
986
|
exchanges. This significantly reduces the number of round-trips compared
|
|
970
|
-
to reading each variable individually.
|
|
987
|
+
to reading each variable individually. A list of dicts may hold any
|
|
988
|
+
number of items: each request carries at most ``MAX_VARS`` address
|
|
989
|
+
specifications and the rest go into further requests.
|
|
971
990
|
|
|
972
991
|
.. warning::
|
|
973
992
|
|
|
@@ -985,16 +1004,15 @@ class Client(ClientMixin):
|
|
|
985
1004
|
ctypes array or a list of bytearrays in the original item order.
|
|
986
1005
|
|
|
987
1006
|
Raises:
|
|
988
|
-
ValueError: If more than MAX_VARS items
|
|
1007
|
+
ValueError: If a ctypes array holds more than MAX_VARS items.
|
|
989
1008
|
"""
|
|
990
1009
|
if not items:
|
|
991
1010
|
return (0, items)
|
|
992
1011
|
|
|
993
|
-
if len(items) > self.MAX_VARS:
|
|
994
|
-
raise ValueError(f"Too many items: {len(items)} exceeds MAX_VARS ({self.MAX_VARS})")
|
|
995
|
-
|
|
996
1012
|
# Handle S7DataItem array (ctypes) -- unchanged legacy path
|
|
997
1013
|
if hasattr(items, "_type_") and hasattr(items[0], "Area"):
|
|
1014
|
+
if len(items) > self.MAX_VARS:
|
|
1015
|
+
raise ValueError(f"Too many items: {len(items)} exceeds MAX_VARS ({self.MAX_VARS})")
|
|
998
1016
|
s7_items = cast("Array[S7DataItem]", items)
|
|
999
1017
|
for s7_item in s7_items:
|
|
1000
1018
|
area = Area(s7_item.Area)
|
|
@@ -1138,7 +1156,7 @@ class Client(ClientMixin):
|
|
|
1138
1156
|
sorted_ri = sort_items(read_items)
|
|
1139
1157
|
max_block = self._max_read_size()
|
|
1140
1158
|
blocks = merge_items(sorted_ri, max_gap=self.multi_read_max_gap, max_block_size=max_block)
|
|
1141
|
-
packets = packetize(blocks, self.pdu_length)
|
|
1159
|
+
packets = packetize(blocks, self.pdu_length, max_items=self.MAX_VARS)
|
|
1142
1160
|
self._opt_plan = _OptimizationPlan(cache_key, packets, read_items)
|
|
1143
1161
|
|
|
1144
1162
|
# Deep-copy blocks from cached packets so we don't mutate cached state
|
|
@@ -1387,15 +1405,18 @@ class Client(ClientMixin):
|
|
|
1387
1405
|
|
|
1388
1406
|
def get_cpu_state(self) -> str:
|
|
1389
1407
|
"""
|
|
1390
|
-
Get CPU state
|
|
1408
|
+
Get the CPU operating state by reading SZL 0x0424.
|
|
1391
1409
|
|
|
1392
1410
|
Returns:
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
response = self._send_receive(request)
|
|
1411
|
+
``"S7CpuStatusRun"``, ``"S7CpuStatusStop"`` or ``"S7CpuStatusUnknown"``.
|
|
1412
|
+
Startup, HOLD and DEFECT are reported as ``"S7CpuStatusStop"``, as
|
|
1413
|
+
native Snap7 does.
|
|
1397
1414
|
|
|
1398
|
-
|
|
1415
|
+
Raises:
|
|
1416
|
+
S7ConnectionError: If the client is not connected.
|
|
1417
|
+
S7ProtocolError: If the PLC refuses SZL 0x0424 or its reply is too short.
|
|
1418
|
+
"""
|
|
1419
|
+
return parse_cpu_state_szl(self.read_szl(0x0424, 0))
|
|
1399
1420
|
|
|
1400
1421
|
def get_block_info(self, block_type: Block, db_number: int) -> TS7BlockInfo:
|
|
1401
1422
|
"""
|
snap7/optimizer.py
CHANGED
|
@@ -14,6 +14,10 @@ from dataclasses import dataclass, field
|
|
|
14
14
|
|
|
15
15
|
logger = logging.getLogger(__name__)
|
|
16
16
|
|
|
17
|
+
# Most address specifications a CPU accepts in one read request. This is the
|
|
18
|
+
# limit native Snap7 enforces as ``MaxVars``.
|
|
19
|
+
MAX_ITEMS_PER_PDU = 20
|
|
20
|
+
|
|
17
21
|
# Areas that support contiguous-block merging. Counter (0x1C) and Timer
|
|
18
22
|
# (0x1D) use element-based addressing, not byte-based, so merging them
|
|
19
23
|
# as contiguous byte ranges would produce incorrect reads.
|
|
@@ -206,12 +210,13 @@ def _split_block(block: ReadBlock, max_block_size: int) -> list[ReadBlock]:
|
|
|
206
210
|
return sub_blocks
|
|
207
211
|
|
|
208
212
|
|
|
209
|
-
def packetize(blocks: list[ReadBlock], pdu_size: int) -> list[ReadPacket]:
|
|
213
|
+
def packetize(blocks: list[ReadBlock], pdu_size: int, max_items: int = MAX_ITEMS_PER_PDU) -> list[ReadPacket]:
|
|
210
214
|
"""Pack blocks into PDU-sized packets.
|
|
211
215
|
|
|
212
|
-
|
|
216
|
+
Three limits are enforced per packet:
|
|
213
217
|
- **Request budget**: ``12 (header) + 2 (func+count) + 12*N (address specs) <= pdu_size``
|
|
214
218
|
- **Reply budget**: ``12 (header) + 2 (func+count) + sum(4 + ceil_even(length)) <= pdu_size``
|
|
219
|
+
- **Item count**: at most *max_items* blocks (address specs)
|
|
215
220
|
|
|
216
221
|
Oversized blocks are first split at item boundaries, then blocks are
|
|
217
222
|
greedily packed into packets.
|
|
@@ -219,10 +224,17 @@ def packetize(blocks: list[ReadBlock], pdu_size: int) -> list[ReadPacket]:
|
|
|
219
224
|
Args:
|
|
220
225
|
blocks: Merged read blocks.
|
|
221
226
|
pdu_size: Negotiated PDU size in bytes.
|
|
227
|
+
max_items: Maximum number of blocks per packet (default 20).
|
|
222
228
|
|
|
223
229
|
Returns:
|
|
224
230
|
List of ReadPackets.
|
|
231
|
+
|
|
232
|
+
Raises:
|
|
233
|
+
ValueError: If *max_items* is less than 1.
|
|
225
234
|
"""
|
|
235
|
+
if max_items < 1:
|
|
236
|
+
raise ValueError(f"max_items must be at least 1, got {max_items}")
|
|
237
|
+
|
|
226
238
|
# First split any oversized blocks
|
|
227
239
|
# Max data payload per block in a single-block packet
|
|
228
240
|
max_single_block = pdu_size - 12 - 2 - 4 # header + param + data item header
|
|
@@ -248,8 +260,9 @@ def packetize(blocks: list[ReadBlock], pdu_size: int) -> list[ReadPacket]:
|
|
|
248
260
|
|
|
249
261
|
fits_request = current_req_used + req_cost <= pdu_size
|
|
250
262
|
fits_reply = current_reply_used + reply_cost <= pdu_size
|
|
263
|
+
fits_count = len(current_packet.blocks) < max_items
|
|
251
264
|
|
|
252
|
-
if current_packet.blocks and (not fits_request or not fits_reply):
|
|
265
|
+
if current_packet.blocks and (not fits_request or not fits_reply or not fits_count):
|
|
253
266
|
# Start a new packet
|
|
254
267
|
packets.append(current_packet)
|
|
255
268
|
current_packet = ReadPacket()
|
snap7/partner.py
CHANGED
|
@@ -88,6 +88,10 @@ class Partner:
|
|
|
88
88
|
self._protocol = S7Protocol()
|
|
89
89
|
self.pdu_length = 480
|
|
90
90
|
|
|
91
|
+
# Sequence counter
|
|
92
|
+
self.bsend_param_sequence = 1
|
|
93
|
+
self.du_ref_nr = 1
|
|
94
|
+
|
|
91
95
|
# R-ID for bsend/brecv matching (default 0, can be set by caller)
|
|
92
96
|
self.r_id: int = 0
|
|
93
97
|
|
|
@@ -261,19 +265,69 @@ class Partner:
|
|
|
261
265
|
self.send_errors += 1
|
|
262
266
|
raise S7ConnectionError("Not connected")
|
|
263
267
|
|
|
268
|
+
if len(self._send_data) > 65534:
|
|
269
|
+
self.send_errors += 1
|
|
270
|
+
raise ValueError("B_send data too long (>65534 bytes)")
|
|
271
|
+
|
|
264
272
|
start_time = datetime.now()
|
|
265
273
|
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
pdu = self._build_partner_data_pdu(self._send_data)
|
|
274
|
+
du_ref_nr = self._next_du_ref_nr()
|
|
275
|
+
bsend_length = len(self._send_data)
|
|
269
276
|
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
277
|
+
fragmented = False
|
|
278
|
+
first_fragment = True
|
|
279
|
+
last_data_unit = False
|
|
280
|
+
curr_pos = 0
|
|
281
|
+
sequence_num = 0
|
|
282
|
+
|
|
283
|
+
# Max payload legnth
|
|
284
|
+
bsend_payload_length = self.pdu_length - 36
|
|
285
|
+
bsend_fragm_payload_length = self.pdu_length - 34
|
|
273
286
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
287
|
+
if bsend_length > bsend_payload_length:
|
|
288
|
+
fragmented = True
|
|
289
|
+
|
|
290
|
+
try:
|
|
291
|
+
with self._io_lock:
|
|
292
|
+
while not last_data_unit:
|
|
293
|
+
# parameters for the PDU
|
|
294
|
+
if first_fragment:
|
|
295
|
+
# the 1. fragment has the length field and 2 bytes less payload bytes
|
|
296
|
+
max_length = bsend_payload_length
|
|
297
|
+
else:
|
|
298
|
+
max_length = bsend_fragm_payload_length
|
|
299
|
+
|
|
300
|
+
if not fragmented:
|
|
301
|
+
last_data_unit = True
|
|
302
|
+
data = self._send_data
|
|
303
|
+
else:
|
|
304
|
+
if curr_pos + max_length >= bsend_length:
|
|
305
|
+
last_data_unit = True
|
|
306
|
+
data = self._send_data[curr_pos:]
|
|
307
|
+
else:
|
|
308
|
+
data = self._send_data[curr_pos : curr_pos + max_length]
|
|
309
|
+
curr_pos += max_length
|
|
310
|
+
|
|
311
|
+
# Build partner data PDU
|
|
312
|
+
pdu, send_pduref = self._build_partner_data_pdu(
|
|
313
|
+
data, sequence_num, du_ref_nr, bsend_length, last_data_unit, first_fragment
|
|
314
|
+
)
|
|
315
|
+
# Send via ISO connection
|
|
316
|
+
self._connection.send_data(pdu)
|
|
317
|
+
|
|
318
|
+
# Wait for acknowledgment
|
|
319
|
+
ack_data = self._connection.receive_data()
|
|
320
|
+
ack_pduref, sequence_num = self._parse_partner_ack(ack_data)
|
|
321
|
+
|
|
322
|
+
if ack_pduref == -1: # try agan
|
|
323
|
+
ack_data = self._connection.receive_data()
|
|
324
|
+
ack_pduref, sequence_num = self._parse_partner_ack(ack_data)
|
|
325
|
+
|
|
326
|
+
if send_pduref != ack_pduref:
|
|
327
|
+
raise S7Error("Send failed: received wrong pdu-referenze-number")
|
|
328
|
+
|
|
329
|
+
if first_fragment:
|
|
330
|
+
first_fragment = False
|
|
277
331
|
|
|
278
332
|
self.bytes_sent += len(self._send_data)
|
|
279
333
|
self.last_send_time = int((datetime.now() - start_time).total_seconds() * 1000)
|
|
@@ -303,24 +357,20 @@ class Partner:
|
|
|
303
357
|
|
|
304
358
|
try:
|
|
305
359
|
with self._io_lock:
|
|
306
|
-
|
|
307
|
-
data = self._connection.receive_data()
|
|
308
|
-
received, r_id, pdu_ref = self._parse_partner_data_pdu(data)
|
|
360
|
+
received, r_id = self._b_recv_loop(self._connection)
|
|
309
361
|
|
|
310
|
-
|
|
311
|
-
ack = self._build_partner_ack(pdu_ref)
|
|
312
|
-
self._connection.send_data(ack)
|
|
362
|
+
bytes_rcv = len(received)
|
|
313
363
|
|
|
314
|
-
self.bytes_recv += len(received)
|
|
315
364
|
self.last_recv_time = int((datetime.now() - start_time).total_seconds() * 1000)
|
|
316
365
|
self._recv_data = received
|
|
317
366
|
self._recv_r_id = r_id
|
|
367
|
+
self.bytes_recv += bytes_rcv
|
|
318
368
|
|
|
319
369
|
# Call receive callback if set
|
|
320
370
|
if self._recv_callback:
|
|
321
371
|
self._recv_callback(received)
|
|
322
372
|
|
|
323
|
-
logger.debug(f"Received {
|
|
373
|
+
logger.debug(f"Received {bytes_rcv} bytes synchronously")
|
|
324
374
|
return 0
|
|
325
375
|
|
|
326
376
|
except socket.timeout:
|
|
@@ -333,6 +383,60 @@ class Partner:
|
|
|
333
383
|
logger.error(f"Synchronous receive failed: {e}")
|
|
334
384
|
return -1
|
|
335
385
|
|
|
386
|
+
def _b_recv_loop(self, conn: ISOTCPConnection, sock_timeout: Optional[float] = None) -> Tuple[bytes, int]:
|
|
387
|
+
"""
|
|
388
|
+
Receives the frames and reassembles fragmented data
|
|
389
|
+
|
|
390
|
+
Args:
|
|
391
|
+
conn: The ISOTCPConnection
|
|
392
|
+
sock_timeout: Socket timeout from the 2nd and subsequent frames
|
|
393
|
+
|
|
394
|
+
Returns:
|
|
395
|
+
data
|
|
396
|
+
r_id
|
|
397
|
+
"""
|
|
398
|
+
if not self.connected or conn is None or conn.socket is None:
|
|
399
|
+
raise S7ConnectionError("Not connected")
|
|
400
|
+
|
|
401
|
+
last_segment = False
|
|
402
|
+
fragmented = False
|
|
403
|
+
reassembled = bytearray()
|
|
404
|
+
bsend_lengh = 0
|
|
405
|
+
|
|
406
|
+
while not last_segment:
|
|
407
|
+
data = conn.receive_data()
|
|
408
|
+
received, r_id, pdu_ref, par_seq_num, _, par_last_unit, data_bsend_lengh = self._parse_partner_data_pdu(data)
|
|
409
|
+
|
|
410
|
+
if par_seq_num == 0:
|
|
411
|
+
sequence = self._next_bsend_param_sequence() # set sequence for new fragemneted transmission
|
|
412
|
+
bsend_lengh = data_bsend_lengh
|
|
413
|
+
else:
|
|
414
|
+
sequence = par_seq_num
|
|
415
|
+
|
|
416
|
+
ack = self._build_partner_ack(pdu_ref, sequence)
|
|
417
|
+
conn.send_data(ack)
|
|
418
|
+
|
|
419
|
+
if par_last_unit == 0:
|
|
420
|
+
last_segment = True
|
|
421
|
+
if fragmented:
|
|
422
|
+
reassembled += bytearray(received)
|
|
423
|
+
received = bytes(reassembled)
|
|
424
|
+
if bsend_lengh != len(received):
|
|
425
|
+
raise S7Error("Incorrect bsend-lenght")
|
|
426
|
+
else:
|
|
427
|
+
fragmented = True
|
|
428
|
+
reassembled += bytearray(received)
|
|
429
|
+
if sock_timeout is not None:
|
|
430
|
+
conn.socket.settimeout(sock_timeout) # Set timeout for next segment
|
|
431
|
+
|
|
432
|
+
if len(reassembled) > 65534 or len(received) > 65534:
|
|
433
|
+
raise S7Error("Received s_send data too long (>65534 bytes)")
|
|
434
|
+
|
|
435
|
+
if len(reassembled) > bsend_lengh:
|
|
436
|
+
raise S7Error("Received s_send data too long (>announced length)")
|
|
437
|
+
|
|
438
|
+
return received, r_id
|
|
439
|
+
|
|
336
440
|
def as_b_send(self) -> int:
|
|
337
441
|
"""
|
|
338
442
|
Send data asynchronously (non-blocking).
|
|
@@ -633,6 +737,20 @@ class Partner:
|
|
|
633
737
|
"""
|
|
634
738
|
return self._recv_r_id
|
|
635
739
|
|
|
740
|
+
def _next_bsend_param_sequence(self) -> int:
|
|
741
|
+
"""Get next sequence number for BSend parameter."""
|
|
742
|
+
self.bsend_param_sequence = (self.bsend_param_sequence + 1) & 0xFF
|
|
743
|
+
if self.bsend_param_sequence == 0: # must not be 0
|
|
744
|
+
self.bsend_param_sequence += 1
|
|
745
|
+
return self.bsend_param_sequence
|
|
746
|
+
|
|
747
|
+
def _next_du_ref_nr(self) -> int:
|
|
748
|
+
"""Get next data unit reference number for BSend parameter."""
|
|
749
|
+
self.du_ref_nr = (self.du_ref_nr + 1) & 0xFF
|
|
750
|
+
if self.du_ref_nr == 0: # must not be 0
|
|
751
|
+
self.du_ref_nr += 1
|
|
752
|
+
return self.du_ref_nr
|
|
753
|
+
|
|
636
754
|
def _connect_to_remote(self) -> None:
|
|
637
755
|
"""Connect to remote partner (active mode).
|
|
638
756
|
|
|
@@ -758,10 +876,8 @@ class Partner:
|
|
|
758
876
|
old_timeout = conn.socket.gettimeout()
|
|
759
877
|
conn.socket.settimeout(self.recv_timeout)
|
|
760
878
|
try:
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
ack = self._build_partner_ack(pdu_ref)
|
|
764
|
-
conn.send_data(ack)
|
|
879
|
+
received, r_id = self._b_recv_loop(conn, old_timeout)
|
|
880
|
+
|
|
765
881
|
finally:
|
|
766
882
|
try:
|
|
767
883
|
if conn.socket is not None:
|
|
@@ -922,7 +1038,16 @@ class Partner:
|
|
|
922
1038
|
data.extend(chunk)
|
|
923
1039
|
return bytes(data)
|
|
924
1040
|
|
|
925
|
-
def _build_partner_data_pdu(
|
|
1041
|
+
def _build_partner_data_pdu(
|
|
1042
|
+
self,
|
|
1043
|
+
data: bytes,
|
|
1044
|
+
sequence_nr: int,
|
|
1045
|
+
du_ref_nr: int,
|
|
1046
|
+
bsend_length: int,
|
|
1047
|
+
last_data_unit: bool,
|
|
1048
|
+
first_fragment: bool,
|
|
1049
|
+
r_id: Optional[int] = None,
|
|
1050
|
+
) -> Tuple[bytes, int]:
|
|
926
1051
|
"""Build an S7 USERDATA PDU for partner data push (bsend).
|
|
927
1052
|
|
|
928
1053
|
The PDU uses the standard S7 USERDATA header (10 bytes) followed by
|
|
@@ -932,15 +1057,26 @@ class Partner:
|
|
|
932
1057
|
|
|
933
1058
|
Args:
|
|
934
1059
|
data: Payload to send.
|
|
1060
|
+
serquence_nr: Sequence number. 0 if not fragemented or 1st fragmented PDU
|
|
1061
|
+
du_ref_nr: Data unit reference number
|
|
1062
|
+
bsend_length: >0 if not fragemented or 1st fragmented PDU
|
|
1063
|
+
last_data_unit: True ist not fragemented or last fragmented PDU
|
|
935
1064
|
r_id: Request ID for bsend/brecv matching. Falls back to ``self.r_id``.
|
|
936
1065
|
|
|
937
1066
|
Returns:
|
|
938
|
-
Complete S7 PDU bytes (without COTP/TPKT framing)
|
|
1067
|
+
Complete S7 PDU bytes (without COTP/TPKT framing) + pdu-ref-nr
|
|
939
1068
|
"""
|
|
940
1069
|
if r_id is None:
|
|
941
1070
|
r_id = self.r_id
|
|
942
1071
|
|
|
943
1072
|
sequence = self._protocol._next_sequence()
|
|
1073
|
+
if sequence == 0: # must not be 0
|
|
1074
|
+
sequence = self._protocol._next_sequence()
|
|
1075
|
+
|
|
1076
|
+
if last_data_unit:
|
|
1077
|
+
last_du = 0x00
|
|
1078
|
+
else:
|
|
1079
|
+
last_du = 0x01
|
|
944
1080
|
|
|
945
1081
|
# Parameter section: USERDATA header (12 bytes)
|
|
946
1082
|
param = struct.pack(
|
|
@@ -952,17 +1088,23 @@ class Partner:
|
|
|
952
1088
|
0x12, # method: extended parameter
|
|
953
1089
|
0x46, # type 4 (request) | group 6 (PBC BSEND)
|
|
954
1090
|
_PUSH_SUBFUNCTION_BSEND,
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1091
|
+
sequence_nr, # sequence number (always 0 for PBC)
|
|
1092
|
+
du_ref_nr, # data unit reference number
|
|
1093
|
+
last_du, # last data unit
|
|
958
1094
|
0x0000, # error code
|
|
959
1095
|
)
|
|
960
1096
|
|
|
961
1097
|
# Data section: header + variable spec + R-ID + payload length + payload
|
|
962
1098
|
# Variable specification: type=0x12, len=0x06, syntax_id=0x13, reserved=0x00
|
|
963
1099
|
var_spec = struct.pack(">BBBB", 0x12, 0x06, 0x13, 0x00)
|
|
964
|
-
|
|
965
|
-
|
|
1100
|
+
|
|
1101
|
+
if first_fragment:
|
|
1102
|
+
# R-ID (4 bytes) + payload length (2 bytes)
|
|
1103
|
+
var_spec += struct.pack(">IH", r_id, bsend_length)
|
|
1104
|
+
else:
|
|
1105
|
+
# R-ID (4 bytes)
|
|
1106
|
+
var_spec += struct.pack(">I", r_id)
|
|
1107
|
+
|
|
966
1108
|
# Data header: return_code=0xFF, transport_size=0x09, length=varspec+data
|
|
967
1109
|
data_section = struct.pack(">BBH", 0xFF, 0x09, len(var_spec) + len(data)) + var_spec + data
|
|
968
1110
|
|
|
@@ -977,16 +1119,17 @@ class Partner:
|
|
|
977
1119
|
len(data_section),
|
|
978
1120
|
)
|
|
979
1121
|
|
|
980
|
-
return header + param + data_section
|
|
1122
|
+
return header + param + data_section, sequence
|
|
981
1123
|
|
|
982
|
-
def _parse_partner_data_pdu(self, pdu: bytes) -> Tuple[bytes, int, int]:
|
|
1124
|
+
def _parse_partner_data_pdu(self, pdu: bytes) -> Tuple[bytes, int, int, int, int, int, int]:
|
|
983
1125
|
"""Parse an incoming partner data push PDU and extract the payload.
|
|
984
1126
|
|
|
985
1127
|
Returns:
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
1128
|
+
Payload, r_id, pdu_ref, par_seq_num, par_duref_num, par_last_unit, data_bsend_lengh
|
|
1129
|
+
|
|
1130
|
+
*r_id* and *pdu_ref* are extracted from the variable
|
|
1131
|
+
specification block and the S7 header respectively.
|
|
1132
|
+
If the variable specification is absent both default to ``0``.
|
|
990
1133
|
"""
|
|
991
1134
|
if len(pdu) < 6:
|
|
992
1135
|
raise S7Error("Invalid partner PDU: too short")
|
|
@@ -1000,27 +1143,76 @@ class Partner:
|
|
|
1000
1143
|
if len(pdu) < 10:
|
|
1001
1144
|
raise S7Error("USERDATA partner PDU too short")
|
|
1002
1145
|
_, _, _, pdu_ref, param_len, data_len = struct.unpack(">BBHHHH", pdu[:10])
|
|
1003
|
-
|
|
1004
|
-
if
|
|
1005
|
-
raise S7Error("
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1146
|
+
|
|
1147
|
+
if len(pdu) < 10 + param_len + data_len:
|
|
1148
|
+
raise S7Error("USERDATA partner PDU too short")
|
|
1149
|
+
|
|
1150
|
+
param = pdu[10 : 10 + param_len]
|
|
1151
|
+
data = pdu[10 + param_len : 10 + param_len + data_len]
|
|
1152
|
+
|
|
1153
|
+
if len(param) < 5:
|
|
1154
|
+
raise S7Error("USERDATA bsend parameter block too short")
|
|
1155
|
+
|
|
1156
|
+
par_func, par_items, par_var_spec, par_addr_lengh, par_syntax_id = struct.unpack(">BBBBB", param[:5])
|
|
1157
|
+
|
|
1158
|
+
if (
|
|
1159
|
+
par_func == 0x00
|
|
1160
|
+
and par_items == 1
|
|
1161
|
+
and par_var_spec == 0x12
|
|
1162
|
+
and par_addr_lengh == 8
|
|
1163
|
+
and par_syntax_id == 0x12
|
|
1164
|
+
and data_len >= 13
|
|
1165
|
+
): # BSend
|
|
1166
|
+
# BSend-data
|
|
1167
|
+
if len(param) < 12:
|
|
1168
|
+
raise S7Error("USERDATA bsend parameter block too short")
|
|
1169
|
+
|
|
1170
|
+
if len(data) < 12:
|
|
1171
|
+
raise S7Error("USERDATA bsend data block too short")
|
|
1172
|
+
|
|
1173
|
+
par_func_group, par_subfunc, par_seq_num, par_duref_num, par_last_unit, par_error_code = struct.unpack(
|
|
1174
|
+
">BBBBBH", param[5:12]
|
|
1175
|
+
)
|
|
1176
|
+
|
|
1177
|
+
_, _, _, data_var_spec, data_var_len, data_syntax_id, _, data_r_id = struct.unpack(">BBHBBBBI", data[:12])
|
|
1178
|
+
|
|
1179
|
+
payload = bytes()
|
|
1180
|
+
r_id = 0
|
|
1181
|
+
data_bsend_lengh = 0
|
|
1182
|
+
|
|
1183
|
+
if (
|
|
1184
|
+
par_func_group == 0x46
|
|
1185
|
+
and par_subfunc == 0x01
|
|
1186
|
+
and par_error_code == 0
|
|
1187
|
+
and data_var_spec == 0x12
|
|
1188
|
+
and data_var_len == 0x06
|
|
1189
|
+
and data_syntax_id == 0x13
|
|
1190
|
+
):
|
|
1191
|
+
if par_seq_num == 0x00: # not fragmented transmission or first segment of fragmented transmission
|
|
1192
|
+
if len(data) >= 14:
|
|
1193
|
+
data_bsend_lengh = struct.unpack(">H", data[12:14])[0]
|
|
1194
|
+
else:
|
|
1195
|
+
raise S7Error("USERDATA bsend data block too short")
|
|
1196
|
+
r_id = data_r_id
|
|
1197
|
+
# skip data header (6) + body (var_len) + length field (2)
|
|
1198
|
+
payload = data[6 + data_var_len + 2 :]
|
|
1199
|
+
|
|
1200
|
+
else: # next segment of fragmented transmission
|
|
1201
|
+
r_id = data_r_id
|
|
1202
|
+
# skip data header (6) + body (var_len)
|
|
1203
|
+
payload = data[6 + data_var_len :]
|
|
1204
|
+
|
|
1205
|
+
return payload, r_id, pdu_ref, par_seq_num, par_duref_num, par_last_unit, data_bsend_lengh
|
|
1206
|
+
|
|
1207
|
+
else:
|
|
1208
|
+
raise S7Error("Unsupported PDU function group, subfunction or b_send parameter")
|
|
1209
|
+
|
|
1210
|
+
else:
|
|
1211
|
+
raise S7Error("Unknown USERDATA-Type")
|
|
1020
1212
|
else:
|
|
1021
1213
|
raise S7Error(f"Unexpected PDU type in partner data: {pdu_type:#04x}")
|
|
1022
1214
|
|
|
1023
|
-
def _build_partner_ack(self, pdu_ref: int = 0) -> bytes:
|
|
1215
|
+
def _build_partner_ack(self, pdu_ref: int = 0, sequence: int = 0) -> bytes:
|
|
1024
1216
|
"""Build an S7 USERDATA acknowledgment PDU for a received bsend.
|
|
1025
1217
|
|
|
1026
1218
|
The PLC expects the same PDU reference in the ACK as in the
|
|
@@ -1028,11 +1220,11 @@ class Partner:
|
|
|
1028
1220
|
|
|
1029
1221
|
Args:
|
|
1030
1222
|
pdu_ref: Protocol Data Unit reference echoed from the data PDU.
|
|
1223
|
+
sequence: Sequence number
|
|
1031
1224
|
|
|
1032
1225
|
Returns:
|
|
1033
1226
|
Complete S7 PDU bytes.
|
|
1034
1227
|
"""
|
|
1035
|
-
sequence = self._protocol._next_sequence()
|
|
1036
1228
|
|
|
1037
1229
|
param = struct.pack(
|
|
1038
1230
|
">BBBBBBBB",
|
|
@@ -1062,11 +1254,15 @@ class Partner:
|
|
|
1062
1254
|
|
|
1063
1255
|
return header + param + data
|
|
1064
1256
|
|
|
1065
|
-
def _parse_partner_ack(self, pdu: bytes) ->
|
|
1257
|
+
def _parse_partner_ack(self, pdu: bytes) -> Tuple[int, int]:
|
|
1066
1258
|
"""Parse a partner acknowledgment PDU.
|
|
1067
1259
|
|
|
1068
1260
|
Validates that the PDU is a proper S7 USERDATA response for a push
|
|
1069
1261
|
acknowledgment and checks for error codes.
|
|
1262
|
+
|
|
1263
|
+
Returns:
|
|
1264
|
+
DPU-Ref + sequence number (for fragmented Bsend transfers).
|
|
1265
|
+
|
|
1070
1266
|
"""
|
|
1071
1267
|
if len(pdu) < 6:
|
|
1072
1268
|
raise S7Error("Invalid partner ACK: too short")
|
|
@@ -1078,19 +1274,28 @@ class Partner:
|
|
|
1078
1274
|
if pdu_type != S7PDUType.USERDATA:
|
|
1079
1275
|
raise S7Error(f"Expected partner ACK (USERDATA), got {pdu_type:#04x}")
|
|
1080
1276
|
|
|
1277
|
+
pdu_ref = 0
|
|
1081
1278
|
# Check for error code in parameter section
|
|
1279
|
+
|
|
1280
|
+
sequence_num = 0
|
|
1082
1281
|
if len(pdu) >= 10:
|
|
1083
|
-
_, _, _,
|
|
1282
|
+
_, _, _, pdu_ref, param_len, _ = struct.unpack(">BBHHHH", pdu[:10])
|
|
1084
1283
|
param = pdu[10 : 10 + param_len]
|
|
1085
1284
|
# Parameter layout: 00 01 12 LL [method tg sf seq ...] [error_code]
|
|
1086
1285
|
if len(param) >= 4:
|
|
1087
1286
|
sub_len = param[3]
|
|
1088
1287
|
if sub_len >= 8 and len(param) >= 12:
|
|
1288
|
+
if param[5] != 0x86: # not a bsend-ack
|
|
1289
|
+
return -1, -1
|
|
1290
|
+
# Sequence number is at offset 7 within param
|
|
1291
|
+
sequence_num = struct.unpack(">B", param[7:8])[0]
|
|
1089
1292
|
# Error code is at offset 10-11 within param (bytes 6-7 after 12 LL)
|
|
1090
1293
|
error_code = struct.unpack(">H", param[10:12])[0]
|
|
1091
1294
|
if error_code != 0:
|
|
1092
1295
|
raise S7Error(f"Partner ACK error: {error_code:#06x}")
|
|
1093
1296
|
|
|
1297
|
+
return pdu_ref, sequence_num
|
|
1298
|
+
|
|
1094
1299
|
def __enter__(self) -> "Partner":
|
|
1095
1300
|
"""Context manager entry."""
|
|
1096
1301
|
return self
|
snap7/s7protocol.py
CHANGED
|
@@ -1487,12 +1487,16 @@ class S7Protocol:
|
|
|
1487
1487
|
|
|
1488
1488
|
def build_cpu_state_request(self) -> bytes:
|
|
1489
1489
|
"""
|
|
1490
|
-
Build
|
|
1490
|
+
Build the request ``get_cpu_state()`` used to send.
|
|
1491
|
+
|
|
1492
|
+
.. deprecated:: 3.5
|
|
1493
|
+
This is a read request without an address specification, which is
|
|
1494
|
+
not a valid S7 PDU. The clients read SZL 0x0424 instead; see
|
|
1495
|
+
:func:`snap7.szl.parse_cpu_state_szl`. Kept for backwards compatibility.
|
|
1491
1496
|
|
|
1492
1497
|
Returns:
|
|
1493
|
-
|
|
1498
|
+
S7 PDU for the old CPU state query
|
|
1494
1499
|
"""
|
|
1495
|
-
# Simple CPU state request - in real S7 this would be a userdata function
|
|
1496
1500
|
header = struct.pack(
|
|
1497
1501
|
">BBHHHH",
|
|
1498
1502
|
0x32, # Protocol ID
|
|
@@ -1503,24 +1507,26 @@ class S7Protocol:
|
|
|
1503
1507
|
0x0000, # Data length
|
|
1504
1508
|
)
|
|
1505
1509
|
|
|
1506
|
-
|
|
1507
|
-
parameters = struct.pack(">B", 0x04) # Use READ_AREA function for simplicity
|
|
1510
|
+
parameters = struct.pack(">B", 0x04) # READ_AREA function code, nothing else
|
|
1508
1511
|
|
|
1509
1512
|
return header + parameters
|
|
1510
1513
|
|
|
1511
1514
|
def extract_cpu_state(self, response: Dict[str, Any]) -> str:
|
|
1512
1515
|
"""
|
|
1513
|
-
|
|
1516
|
+
Return ``"S7CpuStatusRun"`` whatever the response holds.
|
|
1517
|
+
|
|
1518
|
+
.. deprecated:: 3.5
|
|
1519
|
+
This never looked at the response. The clients read SZL 0x0424
|
|
1520
|
+
instead; see :func:`snap7.szl.parse_cpu_state_szl`. Kept for
|
|
1521
|
+
backwards compatibility.
|
|
1514
1522
|
|
|
1515
1523
|
Args:
|
|
1516
|
-
response: Parsed S7 response
|
|
1524
|
+
response: Parsed S7 response (ignored)
|
|
1517
1525
|
|
|
1518
1526
|
Returns:
|
|
1519
|
-
|
|
1527
|
+
Always ``"S7CpuStatusRun"``
|
|
1520
1528
|
"""
|
|
1521
|
-
|
|
1522
|
-
# The cpu_statuses dict in type.py uses: {0: "S7CpuStatusUnknown", 4: "S7CpuStatusStop", 8: "S7CpuStatusRun"}
|
|
1523
|
-
return "S7CpuStatusRun" # Default state for pure Python server
|
|
1529
|
+
return "S7CpuStatusRun"
|
|
1524
1530
|
|
|
1525
1531
|
def parse_response(self, pdu: bytes) -> Dict[str, Any]:
|
|
1526
1532
|
"""
|
snap7/server/__init__.py
CHANGED
|
@@ -14,7 +14,7 @@ import time
|
|
|
14
14
|
from ctypes import Array, c_char
|
|
15
15
|
from enum import IntEnum
|
|
16
16
|
from types import TracebackType
|
|
17
|
-
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
|
|
17
|
+
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type, Union
|
|
18
18
|
|
|
19
19
|
from ..datatypes import S7Area, S7WordLen
|
|
20
20
|
from ..error import S7ConnectionError, S7ProtocolError
|
|
@@ -37,6 +37,11 @@ EVC_DATA_WRITE = 0x00040000
|
|
|
37
37
|
|
|
38
38
|
_EVENT_QUEUE_CAPACITY = 1024
|
|
39
39
|
|
|
40
|
+
# Item return code "accessing the object not allowed". An S7-1214C V4.2 answers a
|
|
41
|
+
# Write Var to a write-protected DB with it, at item level and without a header
|
|
42
|
+
# error (capture in python-snap7 issue #976).
|
|
43
|
+
_ITEM_ACCESS_NOT_ALLOWED = 0x03
|
|
44
|
+
|
|
40
45
|
|
|
41
46
|
class ServerState(IntEnum):
|
|
42
47
|
"""S7 server states."""
|
|
@@ -94,6 +99,7 @@ class Server:
|
|
|
94
99
|
# Memory areas
|
|
95
100
|
self.memory_areas: Dict[Tuple[S7Area, int], bytearray] = {}
|
|
96
101
|
self.area_locks: Dict[Tuple[S7Area, int], threading.Lock] = {}
|
|
102
|
+
self._read_only_areas: Set[Tuple[S7Area, int]] = set()
|
|
97
103
|
self._upload_contexts: Dict[Tuple[str, int], Dict[str, Any]] = {}
|
|
98
104
|
self._download_contexts: Dict[Tuple[str, int], Dict[str, Any]] = {}
|
|
99
105
|
|
|
@@ -211,7 +217,9 @@ class Server:
|
|
|
211
217
|
logger.info("S7 Server stopped")
|
|
212
218
|
return 0
|
|
213
219
|
|
|
214
|
-
def register_area(
|
|
220
|
+
def register_area(
|
|
221
|
+
self, area: SrvArea, index: int, userdata: Union[bytearray, "Array[c_char]"], *, read_only: bool = False
|
|
222
|
+
) -> int:
|
|
215
223
|
"""
|
|
216
224
|
Register a memory area with the server.
|
|
217
225
|
|
|
@@ -219,6 +227,11 @@ class Server:
|
|
|
219
227
|
area: Memory area type
|
|
220
228
|
index: Area index/number
|
|
221
229
|
userdata: Initial data for the area (bytearray or ctypes array)
|
|
230
|
+
read_only: Refuse client writes (Write Var) to this area with item
|
|
231
|
+
return code ``0x03``, "accessing the object not allowed", as an
|
|
232
|
+
S7-1200 does for a write-protected DB. Reads still work, and so
|
|
233
|
+
do a block download and changes the server side makes to
|
|
234
|
+
``userdata``. Registering the area again replaces the flag.
|
|
222
235
|
|
|
223
236
|
Returns:
|
|
224
237
|
0 on success
|
|
@@ -246,8 +259,12 @@ class Server:
|
|
|
246
259
|
area_key = (s7_area, index)
|
|
247
260
|
self.memory_areas[area_key] = data
|
|
248
261
|
self.area_locks[area_key] = threading.Lock()
|
|
262
|
+
if read_only:
|
|
263
|
+
self._read_only_areas.add(area_key)
|
|
264
|
+
else:
|
|
265
|
+
self._read_only_areas.discard(area_key)
|
|
249
266
|
|
|
250
|
-
logger.info(f"Registered area {area.name} index {index}, size {len(data)}")
|
|
267
|
+
logger.info(f"Registered area {area.name} index {index}, size {len(data)}{', read-only' if read_only else ''}")
|
|
251
268
|
return 0
|
|
252
269
|
|
|
253
270
|
def unregister_area(self, area: SrvArea, index: int) -> int:
|
|
@@ -278,6 +295,7 @@ class Server:
|
|
|
278
295
|
if area_key in self.memory_areas:
|
|
279
296
|
del self.memory_areas[area_key]
|
|
280
297
|
del self.area_locks[area_key]
|
|
298
|
+
self._read_only_areas.discard(area_key)
|
|
281
299
|
logger.info(f"Unregistered area {area.name} index {index}")
|
|
282
300
|
|
|
283
301
|
return 0
|
|
@@ -1021,9 +1039,9 @@ class Server:
|
|
|
1021
1039
|
)
|
|
1022
1040
|
return (area, db_number, start, byte_count)
|
|
1023
1041
|
|
|
1024
|
-
#
|
|
1025
|
-
logger.warning("
|
|
1026
|
-
return
|
|
1042
|
+
# A read request without an address specification is malformed
|
|
1043
|
+
logger.warning("Read request carries no address specification")
|
|
1044
|
+
return None
|
|
1027
1045
|
|
|
1028
1046
|
except Exception as e:
|
|
1029
1047
|
logger.error(f"Error parsing read address: {e}")
|
|
@@ -1083,10 +1101,16 @@ class Server:
|
|
|
1083
1101
|
|
|
1084
1102
|
area, db_number, start, count, write_data = addr_info
|
|
1085
1103
|
|
|
1086
|
-
#
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1104
|
+
# A read-only area refuses the write at item level, with no header
|
|
1105
|
+
# error, as a real S7-1200 does for a write-protected DB.
|
|
1106
|
+
read_only = (area, db_number) in self._read_only_areas
|
|
1107
|
+
if read_only:
|
|
1108
|
+
logger.warning(f"Write to read-only area {area}#{db_number} refused")
|
|
1109
|
+
else:
|
|
1110
|
+
# Write data to registered memory area
|
|
1111
|
+
success = self._write_to_memory_area(area, db_number, start, write_data)
|
|
1112
|
+
if not success:
|
|
1113
|
+
return self._build_error_response(request, 0x8404) # Area not found or write error
|
|
1090
1114
|
|
|
1091
1115
|
# Build successful response with error bytes
|
|
1092
1116
|
header = struct.pack(
|
|
@@ -1109,6 +1133,9 @@ class Server:
|
|
|
1109
1133
|
)
|
|
1110
1134
|
|
|
1111
1135
|
# Data section (write response)
|
|
1136
|
+
if read_only:
|
|
1137
|
+
return header + parameters + bytes((_ITEM_ACCESS_NOT_ALLOWED,))
|
|
1138
|
+
|
|
1112
1139
|
data_section = b"\xff" # Success return code
|
|
1113
1140
|
|
|
1114
1141
|
self._emit_event(
|
|
@@ -1310,8 +1337,10 @@ class Server:
|
|
|
1310
1337
|
|
|
1311
1338
|
Returns:
|
|
1312
1339
|
Item return code: ``0xFF`` on success, ``0x0A`` when the area is not
|
|
1313
|
-
registered, and ``0x05`` when the range
|
|
1314
|
-
Nothing is written unless the whole
|
|
1340
|
+
registered, ``0x03`` when it is read-only, and ``0x05`` when the range
|
|
1341
|
+
is outside the registered area. Nothing is written unless the whole
|
|
1342
|
+
item fits. That read-only is checked before the range is a choice:
|
|
1343
|
+
there is no capture of an out-of-range write to a protected DB.
|
|
1315
1344
|
"""
|
|
1316
1345
|
try:
|
|
1317
1346
|
area_key = (area, db_number)
|
|
@@ -1320,6 +1349,10 @@ class Server:
|
|
|
1320
1349
|
logger.warning(f"Memory area {area}#{db_number} not registered for write")
|
|
1321
1350
|
return 0x0A
|
|
1322
1351
|
|
|
1352
|
+
if area_key in self._read_only_areas:
|
|
1353
|
+
logger.warning(f"Write to read-only area {area}#{db_number} refused")
|
|
1354
|
+
return _ITEM_ACCESS_NOT_ALLOWED
|
|
1355
|
+
|
|
1323
1356
|
with self.area_locks[area_key]:
|
|
1324
1357
|
area_data = self.memory_areas[area_key]
|
|
1325
1358
|
|
|
@@ -1837,6 +1870,7 @@ class Server:
|
|
|
1837
1870
|
- 0x001C: Component identification (for get_cpu_info)
|
|
1838
1871
|
- 0x0011: Module identification (for get_order_code)
|
|
1839
1872
|
- 0x0131: Communication parameters (for get_cp_info)
|
|
1873
|
+
- 0x0424: Current operating mode transition (for get_cpu_state)
|
|
1840
1874
|
- 0x0232: Protection level (for get_protection)
|
|
1841
1875
|
|
|
1842
1876
|
Args:
|
|
@@ -1933,10 +1967,19 @@ class Server:
|
|
|
1933
1967
|
# anl_sch: factory setting protection
|
|
1934
1968
|
return struct.pack(">HHHHH", 1, 0, 0, 0, 0) # No protection
|
|
1935
1969
|
|
|
1970
|
+
# SZL 0x0424: current operating mode transition (get_cpu_state)
|
|
1971
|
+
# Record layout: ereig(2) + ae(1) + bzu-id(1) + res(4) + anlinfo1..4(4) + time(8) = 20 bytes.
|
|
1972
|
+
# bzu-id carries the requested mode in bits 0-3: 4 is STOP, 8 is RUN.
|
|
1973
|
+
elif szl_id == 0x0424:
|
|
1974
|
+
# Event IDs: 0x4302 "STARTUP to RUN", 0x4304 "STOP caused by PG STOP operation"
|
|
1975
|
+
event_ids = {CPUState.RUN: 0x4302, CPUState.STOP: 0x4304}
|
|
1976
|
+
record = struct.pack(">HBB", event_ids.get(self.cpu_state, 0x0000), 0xFF, int(self.cpu_state)) + bytes(16)
|
|
1977
|
+
return struct.pack(">HH", len(record), 1) + record
|
|
1978
|
+
|
|
1936
1979
|
# SZL 0x0000: SZL list
|
|
1937
1980
|
elif szl_id == 0x0000:
|
|
1938
1981
|
# Return list of available SZL IDs
|
|
1939
|
-
available_ids = [0x0000, 0x0011, 0x001C, 0x0131, 0x0232]
|
|
1982
|
+
available_ids = [0x0000, 0x0011, 0x001C, 0x0131, 0x0232, 0x0424]
|
|
1940
1983
|
szl_bytes = b""
|
|
1941
1984
|
for id_val in available_ids:
|
|
1942
1985
|
szl_bytes += struct.pack(">H", id_val)
|
snap7/szl.py
CHANGED
|
@@ -14,6 +14,7 @@ from __future__ import annotations
|
|
|
14
14
|
|
|
15
15
|
import struct
|
|
16
16
|
|
|
17
|
+
from .error import S7ProtocolError
|
|
17
18
|
from .type import S7CpInfo, S7CpuInfo, S7OrderCode, S7Protection, S7SZL
|
|
18
19
|
|
|
19
20
|
|
|
@@ -56,6 +57,41 @@ def parse_cpu_info_szl(szl: S7SZL) -> S7CpuInfo:
|
|
|
56
57
|
return info
|
|
57
58
|
|
|
58
59
|
|
|
60
|
+
def parse_cpu_state_szl(szl: S7SZL) -> str:
|
|
61
|
+
"""Decode SZL 0x0424 (current operating mode transition) into an ``S7CpuStatus*`` string.
|
|
62
|
+
|
|
63
|
+
The payload is the 4-byte partial-list header (``LENTHDR``, ``N_DR``)
|
|
64
|
+
followed by one 20-byte record::
|
|
65
|
+
|
|
66
|
+
ereig(2) ae(1) bzu-id(1) res(4) anlinfo1..4(4) time(8)
|
|
67
|
+
|
|
68
|
+
``bzu-id`` holds the requested operating mode in bits 0-3 and the previous
|
|
69
|
+
one in bits 4-7 (1-4 are STOP variants, 5 and 7 are startup, 8 is RUN,
|
|
70
|
+
0xA is HOLD, 0xD is DEFECT). The layout follows Wireshark's S7comm
|
|
71
|
+
dissector (``packet-s7comm_szl_ids.c``) and matches the byte native Snap7
|
|
72
|
+
reads in ``opGetPlcStatus``.
|
|
73
|
+
|
|
74
|
+
Like native Snap7, only RUN is reported as ``S7CpuStatusRun``, a zero byte
|
|
75
|
+
as ``S7CpuStatusUnknown``, and every other mode (startup, HOLD and DEFECT
|
|
76
|
+
included) as ``S7CpuStatusStop``. Snap7 compares the whole byte against
|
|
77
|
+
0x08; this looks at the requested-mode nibble only, so a RUN reply that
|
|
78
|
+
also carries a previous mode is still reported as RUN.
|
|
79
|
+
|
|
80
|
+
Raises:
|
|
81
|
+
S7ProtocolError: If the reply is too short to hold the mode byte.
|
|
82
|
+
"""
|
|
83
|
+
data = _szl_data(szl)
|
|
84
|
+
if len(data) < 8:
|
|
85
|
+
raise S7ProtocolError(f"SZL 0x0424 reply too short for an operating mode: {len(data)} bytes")
|
|
86
|
+
|
|
87
|
+
mode = data[7]
|
|
88
|
+
if mode == 0x00:
|
|
89
|
+
return "S7CpuStatusUnknown"
|
|
90
|
+
if mode & 0x0F == 0x08:
|
|
91
|
+
return "S7CpuStatusRun"
|
|
92
|
+
return "S7CpuStatusStop"
|
|
93
|
+
|
|
94
|
+
|
|
59
95
|
def parse_cp_info_szl(szl: S7SZL) -> S7CpInfo:
|
|
60
96
|
"""Decode SZL 0x0131 (communication processor info) into an :class:`S7CpInfo`.
|
|
61
97
|
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|