python-snap7 3.3.1__py3-none-any.whl → 3.5.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.3.1.dist-info → python_snap7-3.5.0.dist-info}/METADATA +2 -2
- {python_snap7-3.3.1.dist-info → python_snap7-3.5.0.dist-info}/RECORD +16 -16
- snap7/async_client.py +27 -31
- snap7/client.py +49 -214
- snap7/connection.py +5 -2
- snap7/optimizer.py +16 -3
- snap7/partner.py +6 -2
- snap7/s7protocol.py +20 -13
- snap7/server/__init__.py +17 -6
- snap7/szl.py +36 -0
- snap7/tags.py +230 -9
- snap7/util/setters.py +48 -2
- {python_snap7-3.3.1.dist-info → python_snap7-3.5.0.dist-info}/WHEEL +0 -0
- {python_snap7-3.3.1.dist-info → python_snap7-3.5.0.dist-info}/entry_points.txt +0 -0
- {python_snap7-3.3.1.dist-info → python_snap7-3.5.0.dist-info}/licenses/LICENSE +0 -0
- {python_snap7-3.3.1.dist-info → python_snap7-3.5.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.5.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,34 +1,34 @@
|
|
|
1
|
-
python_snap7-3.
|
|
1
|
+
python_snap7-3.5.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
|
-
snap7/connection.py,sha256=
|
|
8
|
+
snap7/connection.py,sha256=W-jOV7hXVI-cuCFcqRzXY3vFp8weeJh0zEJzXNLLBss,19053
|
|
9
9
|
snap7/datatypes.py,sha256=Gqu1XDuKkQI76n4TYrFrhm0RlPz4XNA5GKA-GJJXJDU,12042
|
|
10
10
|
snap7/demo.py,sha256=JWSKLj2QPIXeSFTZSXuADAJzWVKls712MUZnuqwNkNs,17376
|
|
11
11
|
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=NdRwithWSj7F8YxfgeDPtpZ4CG81CV-8E7QaDpAZch8,38194
|
|
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=
|
|
22
|
-
snap7/tags.py,sha256=
|
|
20
|
+
snap7/s7protocol.py,sha256=kSKtJYBcSYLVSSMiVlDwjxZR7x6NyhGsft4oAMso-mg,71107
|
|
21
|
+
snap7/szl.py,sha256=eQsSTw_GT9l_OXZ8eYC_notJct5qowNXSa3T3LNq7EY,9472
|
|
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=hiZ1-5d6PW3-6DX-3bFe62T66ergJjpgkkdxB70bx8I,118701
|
|
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
|
-
snap7/util/setters.py,sha256=
|
|
30
|
-
python_snap7-3.
|
|
31
|
-
python_snap7-3.
|
|
32
|
-
python_snap7-3.
|
|
33
|
-
python_snap7-3.
|
|
34
|
-
python_snap7-3.
|
|
29
|
+
snap7/util/setters.py,sha256=InGXodcfGxNvdGQ5Y589aBOFqa-e2hIUqNCk-HqziiE,29335
|
|
30
|
+
python_snap7-3.5.0.dist-info/METADATA,sha256=rUUM0IpdvtNhWia1kTHeM43rHSCS3oMVmtNkO3zS5h0,4678
|
|
31
|
+
python_snap7-3.5.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
32
|
+
python_snap7-3.5.0.dist-info/entry_points.txt,sha256=IPZyYr1lKyavXXpAc4xO505afTGwTY8GmNFuy5lsSiM,75
|
|
33
|
+
python_snap7-3.5.0.dist-info/top_level.txt,sha256=PTgDoDG45QNL2XIE9RM7S_ZCdWQjtMMuXNyrI2UdnbU,9
|
|
34
|
+
python_snap7-3.5.0.dist-info/RECORD,,
|
snap7/async_client.py
CHANGED
|
@@ -21,9 +21,9 @@ from .s7protocol import S7Protocol, S7UserDataGroup, S7UserDataSubfunction, get_
|
|
|
21
21
|
from .datatypes import S7DataTypes, S7WordLen
|
|
22
22
|
from .error import S7Error, S7ConnectionError, S7ProtocolError, S7TimeoutError
|
|
23
23
|
from .client_base import ClientMixin, _instrumented
|
|
24
|
-
from .tags import Tag
|
|
25
|
-
from .client import Client
|
|
26
|
-
from .szl import parse_cp_info_szl, parse_cpu_info_szl, parse_order_code_szl, parse_protection_szl
|
|
24
|
+
from .tags import Tag, decode_tag, encode_tag
|
|
25
|
+
from .client import Client
|
|
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 (
|
|
@@ -255,7 +255,8 @@ class AsyncISOTCPConnection:
|
|
|
255
255
|
if pdu_type != self.COTP_CC:
|
|
256
256
|
raise S7ConnectionError(f"Expected COTP CC, got {pdu_type:#02x}")
|
|
257
257
|
|
|
258
|
-
|
|
258
|
+
# The CC's source reference is the peer's; see ISOTCPConnection._parse_cotp_cc (#972).
|
|
259
|
+
self.dst_ref = src_ref
|
|
259
260
|
|
|
260
261
|
# Parse parameters
|
|
261
262
|
offset = 7
|
|
@@ -794,7 +795,7 @@ class AsyncClient(ClientMixin):
|
|
|
794
795
|
if resolved.is_symbolic:
|
|
795
796
|
raise NotImplementedError("Symbolic (LID-based) tag access is not supported by the classic S7 client.")
|
|
796
797
|
data = await self.read_area(Area(resolved.area), resolved.db_number, resolved.byte_offset, resolved.size)
|
|
797
|
-
return
|
|
798
|
+
return decode_tag(resolved, bytearray(data), encoding=encoding)
|
|
798
799
|
|
|
799
800
|
async def write_tag(self, tag: "Union[Tag, str]", value: Any, encoding: str = "latin-1") -> int:
|
|
800
801
|
"""Write a typed value by :class:`~snap7.tags.Tag` or address string. Returns 0 on success."""
|
|
@@ -806,15 +807,17 @@ class AsyncClient(ClientMixin):
|
|
|
806
807
|
# Preserve the other bits of the byte
|
|
807
808
|
current = await self.read_area(Area(resolved.area), resolved.db_number, resolved.byte_offset, 1)
|
|
808
809
|
buf[0] = current[0]
|
|
809
|
-
|
|
810
|
+
encode_tag(resolved, buf, value, encoding=encoding)
|
|
810
811
|
return await self.write_area(Area(resolved.area), resolved.db_number, resolved.byte_offset, buf)
|
|
811
812
|
|
|
812
813
|
async def read_tags(self, tags: "Sequence[Union[Tag, str]]", encoding: str = "latin-1") -> list[Any]:
|
|
813
|
-
"""Read
|
|
814
|
+
"""Read any number of tags, returning the values in input order."""
|
|
814
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.")
|
|
815
818
|
items = [{"area": Area(t.area), "db_number": t.db_number, "start": t.byte_offset, "size": t.size} for t in resolved]
|
|
816
819
|
_code, data_list = await self.read_multi_vars(items)
|
|
817
|
-
return [
|
|
820
|
+
return [decode_tag(t, bytearray(d), encoding=encoding) for t, d in zip(resolved, data_list)]
|
|
818
821
|
|
|
819
822
|
async def db_get(self, db_number: int, size: int = 0) -> bytearray:
|
|
820
823
|
"""Get entire DB.
|
|
@@ -950,15 +953,14 @@ class AsyncClient(ClientMixin):
|
|
|
950
953
|
"""Read multiple variables (sequentially, one read_area per item).
|
|
951
954
|
|
|
952
955
|
Args:
|
|
953
|
-
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.
|
|
954
958
|
|
|
955
959
|
Returns:
|
|
956
960
|
Tuple of (result_code, list_of_bytearrays)
|
|
957
961
|
"""
|
|
958
962
|
if not items:
|
|
959
963
|
return (0, [])
|
|
960
|
-
if len(items) > self.MAX_VARS:
|
|
961
|
-
raise ValueError(f"Too many items: {len(items)} exceeds MAX_VARS ({self.MAX_VARS})")
|
|
962
964
|
|
|
963
965
|
results: list[bytearray] = []
|
|
964
966
|
for item in items:
|
|
@@ -1022,8 +1024,6 @@ class AsyncClient(ClientMixin):
|
|
|
1022
1024
|
if not self.get_connected():
|
|
1023
1025
|
raise S7ConnectionError("Not connected to PLC")
|
|
1024
1026
|
|
|
1025
|
-
conn = self._get_connection()
|
|
1026
|
-
|
|
1027
1027
|
block_type_codes = {
|
|
1028
1028
|
Block.OB: 0x38,
|
|
1029
1029
|
Block.DB: 0x41,
|
|
@@ -1057,12 +1057,8 @@ class AsyncClient(ClientMixin):
|
|
|
1057
1057
|
if last_data_unit == 0x00:
|
|
1058
1058
|
break
|
|
1059
1059
|
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
await self._send_data(conn, followup)
|
|
1063
|
-
response_data = await conn.receive_data()
|
|
1064
|
-
|
|
1065
|
-
response = self.protocol.parse_response(response_data)
|
|
1060
|
+
followup = self.protocol.build_userdata_followup_request(group, subfunction, sequence_number)
|
|
1061
|
+
response = await self._send_receive(followup)
|
|
1066
1062
|
self.protocol.check_userdata_response(response, S7UserDataGroup.BLOCK_INFO, S7UserDataSubfunction.LIST_BLOCKS_OF_TYPE)
|
|
1067
1063
|
|
|
1068
1064
|
data_info = response.get("data", {})
|
|
@@ -1120,10 +1116,16 @@ class AsyncClient(ClientMixin):
|
|
|
1120
1116
|
return parse_cpu_info_szl(await self.read_szl(0x001C, 0))
|
|
1121
1117
|
|
|
1122
1118
|
async def get_cpu_state(self) -> str:
|
|
1123
|
-
"""Get CPU state
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
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))
|
|
1127
1129
|
|
|
1128
1130
|
# ---------------------------------------------------------------
|
|
1129
1131
|
# Upload / Download / Delete
|
|
@@ -1346,8 +1348,6 @@ class AsyncClient(ClientMixin):
|
|
|
1346
1348
|
if not self.get_connected():
|
|
1347
1349
|
raise S7ConnectionError("Not connected to PLC")
|
|
1348
1350
|
|
|
1349
|
-
conn = self._get_connection()
|
|
1350
|
-
|
|
1351
1351
|
request = self.protocol.build_read_szl_request(ssl_id, index)
|
|
1352
1352
|
response = await self._send_receive(request)
|
|
1353
1353
|
self.protocol.check_userdata_response(response, S7UserDataGroup.SZL, S7UserDataSubfunction.READ_SZL)
|
|
@@ -1371,12 +1371,8 @@ class AsyncClient(ClientMixin):
|
|
|
1371
1371
|
if last_data_unit == 0x00:
|
|
1372
1372
|
break
|
|
1373
1373
|
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
await self._send_data(conn, followup)
|
|
1377
|
-
response_data = await conn.receive_data()
|
|
1378
|
-
|
|
1379
|
-
response = self.protocol.parse_response(response_data)
|
|
1374
|
+
followup = self.protocol.build_userdata_followup_request(group, subfunction, sequence_number)
|
|
1375
|
+
response = await self._send_receive(followup)
|
|
1380
1376
|
self.protocol.check_userdata_response(response, S7UserDataGroup.SZL, S7UserDataSubfunction.READ_SZL)
|
|
1381
1377
|
|
|
1382
1378
|
data_info = response.get("data", {})
|
snap7/client.py
CHANGED
|
@@ -24,15 +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
|
-
from .tags import Tag,
|
|
33
|
-
from . import util
|
|
32
|
+
from .tags import Tag, decode_tag, encode_tag
|
|
34
33
|
|
|
35
|
-
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
|
|
36
35
|
from .type import (
|
|
37
36
|
Area,
|
|
38
37
|
Block,
|
|
@@ -55,184 +54,9 @@ _VALID_AREA_VALUES: frozenset[int] = frozenset(a.value for a in Area)
|
|
|
55
54
|
|
|
56
55
|
logger = logging.getLogger(__name__)
|
|
57
56
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
upper = tag.datatype.upper()
|
|
62
|
-
# Variable-length string types
|
|
63
|
-
match = _STRING_RE.match(upper)
|
|
64
|
-
if match:
|
|
65
|
-
kind, length = match.group(1), int(match.group(2))
|
|
66
|
-
if kind == "FSTRING":
|
|
67
|
-
return util.get_fstring(data, 0, length, encoding=encoding)
|
|
68
|
-
if kind == "STRING":
|
|
69
|
-
return util.get_string(data, 0, encoding=encoding)
|
|
70
|
-
if kind == "WSTRING":
|
|
71
|
-
return util.get_wstring(data, 0)
|
|
72
|
-
|
|
73
|
-
# Arrays
|
|
74
|
-
if tag.count > 1:
|
|
75
|
-
per = tag.size // tag.count
|
|
76
|
-
return [_decode_scalar(upper, data[i * per : (i + 1) * per], tag.bit) for i in range(tag.count)]
|
|
77
|
-
|
|
78
|
-
return _decode_scalar(upper, data, tag.bit)
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
def _decode_scalar(datatype: str, data: bytearray, bit: int) -> Any:
|
|
82
|
-
"""Decode a single scalar value of the given type."""
|
|
83
|
-
if datatype == "BOOL":
|
|
84
|
-
return util.get_bool(data, 0, bit)
|
|
85
|
-
if datatype == "BYTE":
|
|
86
|
-
return util.get_byte(data, 0)
|
|
87
|
-
if datatype == "SINT":
|
|
88
|
-
return util.get_sint(data, 0)
|
|
89
|
-
if datatype == "USINT":
|
|
90
|
-
return util.get_usint(data, 0)
|
|
91
|
-
if datatype == "CHAR":
|
|
92
|
-
return util.get_char(data, 0)
|
|
93
|
-
if datatype == "INT":
|
|
94
|
-
return util.get_int(data, 0)
|
|
95
|
-
if datatype == "UINT":
|
|
96
|
-
return util.get_uint(data, 0)
|
|
97
|
-
if datatype == "WORD":
|
|
98
|
-
return util.get_word(data, 0)
|
|
99
|
-
if datatype == "WCHAR":
|
|
100
|
-
return util.get_wchar(data, 0)
|
|
101
|
-
if datatype == "DATE":
|
|
102
|
-
return util.get_date(data, 0)
|
|
103
|
-
if datatype == "DINT":
|
|
104
|
-
return util.get_dint(data, 0)
|
|
105
|
-
if datatype == "UDINT":
|
|
106
|
-
return util.get_udint(data, 0)
|
|
107
|
-
if datatype == "DWORD":
|
|
108
|
-
return util.get_dword(data, 0)
|
|
109
|
-
if datatype == "REAL":
|
|
110
|
-
return util.get_real(data, 0)
|
|
111
|
-
if datatype == "TIME":
|
|
112
|
-
return util.get_time(data, 0)
|
|
113
|
-
if datatype == "TOD":
|
|
114
|
-
return util.get_tod(data, 0)
|
|
115
|
-
if datatype == "LINT":
|
|
116
|
-
return util.get_lint(data, 0)
|
|
117
|
-
if datatype == "ULINT":
|
|
118
|
-
return util.get_ulint(data, 0)
|
|
119
|
-
if datatype == "LWORD":
|
|
120
|
-
return util.get_lword(data, 0)
|
|
121
|
-
if datatype == "LREAL":
|
|
122
|
-
return util.get_lreal(data, 0)
|
|
123
|
-
if datatype == "LTIME":
|
|
124
|
-
return util.get_ltime(data, 0)
|
|
125
|
-
if datatype == "LTOD":
|
|
126
|
-
return util.get_ltod(data, 0)
|
|
127
|
-
if datatype == "LDT":
|
|
128
|
-
return util.get_ldt(data, 0)
|
|
129
|
-
if datatype == "DT":
|
|
130
|
-
return util.get_dt(data, 0)
|
|
131
|
-
if datatype == "DTL":
|
|
132
|
-
return util.get_dtl(data, 0)
|
|
133
|
-
raise ValueError(f"Unsupported tag datatype: {datatype}")
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
def _encode_tag(tag: Tag, buf: bytearray, value: Any, encoding: str = "latin-1") -> None:
|
|
137
|
-
"""Encode a typed Python value into a Tag's byte buffer."""
|
|
138
|
-
upper = tag.datatype.upper()
|
|
139
|
-
match = _STRING_RE.match(upper)
|
|
140
|
-
if match:
|
|
141
|
-
kind, length = match.group(1), int(match.group(2))
|
|
142
|
-
if kind == "FSTRING":
|
|
143
|
-
util.set_fstring(buf, 0, value, length, encoding=encoding)
|
|
144
|
-
return
|
|
145
|
-
if kind == "STRING":
|
|
146
|
-
util.set_string(buf, 0, value, length, encoding=encoding)
|
|
147
|
-
return
|
|
148
|
-
if kind == "WSTRING":
|
|
149
|
-
util.set_wstring(buf, 0, value, length)
|
|
150
|
-
return
|
|
151
|
-
|
|
152
|
-
if tag.count > 1:
|
|
153
|
-
per = tag.size // tag.count
|
|
154
|
-
for i, v in enumerate(value):
|
|
155
|
-
_encode_scalar(upper, buf, i * per, v, tag.bit)
|
|
156
|
-
return
|
|
157
|
-
|
|
158
|
-
_encode_scalar(upper, buf, 0, value, tag.bit)
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
def _encode_scalar(datatype: str, buf: bytearray, offset: int, value: Any, bit: int) -> None:
|
|
162
|
-
"""Encode a single scalar value at the given offset."""
|
|
163
|
-
if datatype == "BOOL":
|
|
164
|
-
util.set_bool(buf, offset, bit, value)
|
|
165
|
-
return
|
|
166
|
-
if datatype in ("BYTE", "USINT"):
|
|
167
|
-
util.set_byte(buf, offset, value) if datatype == "BYTE" else util.set_usint(buf, offset, value)
|
|
168
|
-
return
|
|
169
|
-
if datatype == "SINT":
|
|
170
|
-
util.set_sint(buf, offset, value)
|
|
171
|
-
return
|
|
172
|
-
if datatype == "CHAR":
|
|
173
|
-
util.set_char(buf, offset, value)
|
|
174
|
-
return
|
|
175
|
-
if datatype == "INT":
|
|
176
|
-
util.set_int(buf, offset, value)
|
|
177
|
-
return
|
|
178
|
-
if datatype == "UINT":
|
|
179
|
-
util.set_uint(buf, offset, value)
|
|
180
|
-
return
|
|
181
|
-
if datatype == "WORD":
|
|
182
|
-
util.set_word(buf, offset, value)
|
|
183
|
-
return
|
|
184
|
-
if datatype == "WCHAR":
|
|
185
|
-
util.set_wchar(buf, offset, value)
|
|
186
|
-
return
|
|
187
|
-
if datatype == "DATE":
|
|
188
|
-
util.set_date(buf, offset, value)
|
|
189
|
-
return
|
|
190
|
-
if datatype == "DINT":
|
|
191
|
-
util.set_dint(buf, offset, value)
|
|
192
|
-
return
|
|
193
|
-
if datatype == "UDINT":
|
|
194
|
-
util.set_udint(buf, offset, value)
|
|
195
|
-
return
|
|
196
|
-
if datatype == "DWORD":
|
|
197
|
-
util.set_dword(buf, offset, value)
|
|
198
|
-
return
|
|
199
|
-
if datatype == "REAL":
|
|
200
|
-
util.set_real(buf, offset, value)
|
|
201
|
-
return
|
|
202
|
-
if datatype == "TIME":
|
|
203
|
-
util.set_time(buf, offset, value)
|
|
204
|
-
return
|
|
205
|
-
if datatype == "TOD":
|
|
206
|
-
util.set_tod(buf, offset, value)
|
|
207
|
-
return
|
|
208
|
-
if datatype == "LINT":
|
|
209
|
-
util.set_lint(buf, offset, value)
|
|
210
|
-
return
|
|
211
|
-
if datatype == "ULINT":
|
|
212
|
-
util.set_ulint(buf, offset, value)
|
|
213
|
-
return
|
|
214
|
-
if datatype == "LWORD":
|
|
215
|
-
util.set_lword(buf, offset, value)
|
|
216
|
-
return
|
|
217
|
-
if datatype == "LREAL":
|
|
218
|
-
util.set_lreal(buf, offset, value)
|
|
219
|
-
return
|
|
220
|
-
if datatype == "LTIME":
|
|
221
|
-
util.set_ltime(buf, offset, value)
|
|
222
|
-
return
|
|
223
|
-
if datatype == "LTOD":
|
|
224
|
-
util.set_ltod(buf, offset, value)
|
|
225
|
-
return
|
|
226
|
-
if datatype == "LDT":
|
|
227
|
-
util.set_ldt(buf, offset, value)
|
|
228
|
-
return
|
|
229
|
-
if datatype == "DT":
|
|
230
|
-
util.set_dt(buf, offset, value)
|
|
231
|
-
return
|
|
232
|
-
if datatype == "DTL":
|
|
233
|
-
util.set_dtl(buf, offset, value)
|
|
234
|
-
return
|
|
235
|
-
raise ValueError(f"Unsupported tag datatype: {datatype}")
|
|
57
|
+
# Old private names; ha-s7 releases up to 0.1.4 import these from here.
|
|
58
|
+
_decode_tag = decode_tag
|
|
59
|
+
_encode_tag = encode_tag
|
|
236
60
|
|
|
237
61
|
|
|
238
62
|
def _parse_force_szl(raw: bytes) -> list[ForceEntry]:
|
|
@@ -283,7 +107,7 @@ class Client(ClientMixin):
|
|
|
283
107
|
>>> client.disconnect()
|
|
284
108
|
"""
|
|
285
109
|
|
|
286
|
-
MAX_VARS = 20 # Max variables per multi-read/multi-write
|
|
110
|
+
MAX_VARS = 20 # Max variables per multi-read/multi-write PDU
|
|
287
111
|
|
|
288
112
|
def __init__(
|
|
289
113
|
self,
|
|
@@ -597,7 +421,7 @@ class Client(ClientMixin):
|
|
|
597
421
|
try:
|
|
598
422
|
with self._reconnect_lock:
|
|
599
423
|
if self.connected and self.connection is not None:
|
|
600
|
-
self.
|
|
424
|
+
self._heartbeat_probe()
|
|
601
425
|
self._is_alive = True
|
|
602
426
|
except Exception as e:
|
|
603
427
|
logger.warning(f"Heartbeat probe failed: {e}")
|
|
@@ -610,6 +434,20 @@ class Client(ClientMixin):
|
|
|
610
434
|
except S7ConnectionError:
|
|
611
435
|
logger.warning("Heartbeat reconnection failed")
|
|
612
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
|
+
|
|
613
451
|
def connect(self, address: str, rack: int, slot: int, tcp_port: int = 102) -> "Client":
|
|
614
452
|
"""
|
|
615
453
|
Connect to S7 PLC.
|
|
@@ -864,7 +702,7 @@ class Client(ClientMixin):
|
|
|
864
702
|
if resolved.is_symbolic:
|
|
865
703
|
raise NotImplementedError("Symbolic (LID-based) tag access is not supported by the classic S7 client.")
|
|
866
704
|
data = self.read_area(Area(resolved.area), resolved.db_number, resolved.byte_offset, resolved.size)
|
|
867
|
-
return
|
|
705
|
+
return decode_tag(resolved, bytearray(data), encoding=encoding)
|
|
868
706
|
|
|
869
707
|
def write_tag(self, tag: "Union[Tag, str]", value: Any, encoding: str = "latin-1") -> int:
|
|
870
708
|
"""Write a typed value by :class:`~snap7.tags.Tag` or address string.
|
|
@@ -886,14 +724,15 @@ class Client(ClientMixin):
|
|
|
886
724
|
if resolved.datatype.upper() == "BOOL":
|
|
887
725
|
current = self.read_area(Area(resolved.area), resolved.db_number, resolved.byte_offset, 1)
|
|
888
726
|
buf[0] = current[0]
|
|
889
|
-
|
|
727
|
+
encode_tag(resolved, buf, value, encoding=encoding)
|
|
890
728
|
return self.write_area(Area(resolved.area), resolved.db_number, resolved.byte_offset, buf)
|
|
891
729
|
|
|
892
730
|
def read_tags(self, tags: "Sequence[Union[Tag, str]]", encoding: str = "latin-1") -> list[Any]:
|
|
893
|
-
"""Read multiple tags in
|
|
731
|
+
"""Read multiple tags in as few requests as possible.
|
|
894
732
|
|
|
895
733
|
Uses the multi-variable read optimizer when available to batch
|
|
896
|
-
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.
|
|
897
736
|
|
|
898
737
|
Args:
|
|
899
738
|
tags: Sequence of :class:`~snap7.tags.Tag` instances or address strings.
|
|
@@ -903,9 +742,11 @@ class Client(ClientMixin):
|
|
|
903
742
|
List of decoded values in the same order as input.
|
|
904
743
|
"""
|
|
905
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.")
|
|
906
747
|
items = [{"area": Area(t.area), "db_number": t.db_number, "start": t.byte_offset, "size": t.size} for t in resolved]
|
|
907
748
|
_code, data_list = self.read_multi_vars(items)
|
|
908
|
-
return [
|
|
749
|
+
return [decode_tag(t, bytearray(d), encoding=encoding) for t, d in zip(resolved, data_list)]
|
|
909
750
|
|
|
910
751
|
def db_read(self, db_number: int, start: int, size: int) -> bytearray:
|
|
911
752
|
"""
|
|
@@ -1138,12 +979,14 @@ class Client(ClientMixin):
|
|
|
1138
979
|
|
|
1139
980
|
@_instrumented("read_multi_vars")
|
|
1140
981
|
def read_multi_vars(self, items: Union[List[dict[str, Any]], "Array[S7DataItem]"]) -> Tuple[int, Any]:
|
|
1141
|
-
"""Read multiple variables in
|
|
982
|
+
"""Read multiple variables in as few requests as possible.
|
|
1142
983
|
|
|
1143
984
|
When given a list of dicts with two or more items, uses the multi-variable
|
|
1144
985
|
read optimizer to merge adjacent reads and pack them into minimal PDU
|
|
1145
986
|
exchanges. This significantly reduces the number of round-trips compared
|
|
1146
|
-
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.
|
|
1147
990
|
|
|
1148
991
|
.. warning::
|
|
1149
992
|
|
|
@@ -1161,16 +1004,15 @@ class Client(ClientMixin):
|
|
|
1161
1004
|
ctypes array or a list of bytearrays in the original item order.
|
|
1162
1005
|
|
|
1163
1006
|
Raises:
|
|
1164
|
-
ValueError: If more than MAX_VARS items
|
|
1007
|
+
ValueError: If a ctypes array holds more than MAX_VARS items.
|
|
1165
1008
|
"""
|
|
1166
1009
|
if not items:
|
|
1167
1010
|
return (0, items)
|
|
1168
1011
|
|
|
1169
|
-
if len(items) > self.MAX_VARS:
|
|
1170
|
-
raise ValueError(f"Too many items: {len(items)} exceeds MAX_VARS ({self.MAX_VARS})")
|
|
1171
|
-
|
|
1172
1012
|
# Handle S7DataItem array (ctypes) -- unchanged legacy path
|
|
1173
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})")
|
|
1174
1016
|
s7_items = cast("Array[S7DataItem]", items)
|
|
1175
1017
|
for s7_item in s7_items:
|
|
1176
1018
|
area = Area(s7_item.Area)
|
|
@@ -1314,7 +1156,7 @@ class Client(ClientMixin):
|
|
|
1314
1156
|
sorted_ri = sort_items(read_items)
|
|
1315
1157
|
max_block = self._max_read_size()
|
|
1316
1158
|
blocks = merge_items(sorted_ri, max_gap=self.multi_read_max_gap, max_block_size=max_block)
|
|
1317
|
-
packets = packetize(blocks, self.pdu_length)
|
|
1159
|
+
packets = packetize(blocks, self.pdu_length, max_items=self.MAX_VARS)
|
|
1318
1160
|
self._opt_plan = _OptimizationPlan(cache_key, packets, read_items)
|
|
1319
1161
|
|
|
1320
1162
|
# Deep-copy blocks from cached packets so we don't mutate cached state
|
|
@@ -1491,8 +1333,6 @@ class Client(ClientMixin):
|
|
|
1491
1333
|
if not self.get_connected():
|
|
1492
1334
|
raise S7ConnectionError("Not connected to PLC")
|
|
1493
1335
|
|
|
1494
|
-
conn = self._get_connection()
|
|
1495
|
-
|
|
1496
1336
|
# Map Block enum to S7 block type codes
|
|
1497
1337
|
block_type_codes = {
|
|
1498
1338
|
Block.OB: 0x38, # Organization Block
|
|
@@ -1534,10 +1374,7 @@ class Client(ClientMixin):
|
|
|
1534
1374
|
break
|
|
1535
1375
|
|
|
1536
1376
|
followup = self.protocol.build_userdata_followup_request(group, subfunction, sequence_number)
|
|
1537
|
-
self.
|
|
1538
|
-
|
|
1539
|
-
response_data = conn.receive_data()
|
|
1540
|
-
response = self.protocol.parse_response(response_data)
|
|
1377
|
+
response = self._send_receive(followup)
|
|
1541
1378
|
self.protocol.check_userdata_response(response, S7UserDataGroup.BLOCK_INFO, S7UserDataSubfunction.LIST_BLOCKS_OF_TYPE)
|
|
1542
1379
|
|
|
1543
1380
|
# Check for errors
|
|
@@ -1568,15 +1405,18 @@ class Client(ClientMixin):
|
|
|
1568
1405
|
|
|
1569
1406
|
def get_cpu_state(self) -> str:
|
|
1570
1407
|
"""
|
|
1571
|
-
Get CPU state
|
|
1408
|
+
Get the CPU operating state by reading SZL 0x0424.
|
|
1572
1409
|
|
|
1573
1410
|
Returns:
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
response = self._send_receive(request)
|
|
1411
|
+
``"S7CpuStatusRun"``, ``"S7CpuStatusStop"`` or ``"S7CpuStatusUnknown"``.
|
|
1412
|
+
Startup, HOLD and DEFECT are reported as ``"S7CpuStatusStop"``, as
|
|
1413
|
+
native Snap7 does.
|
|
1578
1414
|
|
|
1579
|
-
|
|
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))
|
|
1580
1420
|
|
|
1581
1421
|
def get_block_info(self, block_type: Block, db_number: int) -> TS7BlockInfo:
|
|
1582
1422
|
"""
|
|
@@ -2143,8 +1983,6 @@ class Client(ClientMixin):
|
|
|
2143
1983
|
if not self.get_connected():
|
|
2144
1984
|
raise S7ConnectionError("Not connected to PLC")
|
|
2145
1985
|
|
|
2146
|
-
conn = self._get_connection()
|
|
2147
|
-
|
|
2148
1986
|
# Build and send read SZL request
|
|
2149
1987
|
request = self.protocol.build_read_szl_request(ssl_id, index)
|
|
2150
1988
|
response = self._send_receive(request)
|
|
@@ -2174,10 +2012,7 @@ class Client(ClientMixin):
|
|
|
2174
2012
|
break
|
|
2175
2013
|
|
|
2176
2014
|
followup = self.protocol.build_userdata_followup_request(group, subfunction, sequence_number)
|
|
2177
|
-
self.
|
|
2178
|
-
|
|
2179
|
-
response_data = conn.receive_data()
|
|
2180
|
-
response = self.protocol.parse_response(response_data)
|
|
2015
|
+
response = self._send_receive(followup)
|
|
2181
2016
|
self.protocol.check_userdata_response(response, S7UserDataGroup.SZL, S7UserDataSubfunction.READ_SZL)
|
|
2182
2017
|
|
|
2183
2018
|
# Check for errors
|
snap7/connection.py
CHANGED
|
@@ -342,7 +342,10 @@ class ISOTCPConnection:
|
|
|
342
342
|
"""
|
|
343
343
|
Parse COTP Connection Confirm PDU.
|
|
344
344
|
|
|
345
|
-
Extracts
|
|
345
|
+
Extracts the peer's reference and the negotiated PDU size. The CC's
|
|
346
|
+
source reference is the peer's own reference, which every later TPDU
|
|
347
|
+
addressed to it (the DR) carries as its destination reference. Its
|
|
348
|
+
destination reference only echoes ours (#972).
|
|
346
349
|
"""
|
|
347
350
|
if len(data) < 7:
|
|
348
351
|
raise S7ConnectionError("Invalid COTP CC: too short")
|
|
@@ -352,7 +355,7 @@ class ISOTCPConnection:
|
|
|
352
355
|
if pdu_type != self.COTP_CC:
|
|
353
356
|
raise S7ConnectionError(f"Expected COTP CC, got {pdu_type:#02x}")
|
|
354
357
|
|
|
355
|
-
self.dst_ref =
|
|
358
|
+
self.dst_ref = src_ref
|
|
356
359
|
|
|
357
360
|
# Parse parameters if present
|
|
358
361
|
if len(data) > 7:
|