python-snap7 3.3.1__py3-none-any.whl → 3.4.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.4.0.dist-info}/METADATA +1 -1
- {python_snap7-3.3.1.dist-info → python_snap7-3.4.0.dist-info}/RECORD +14 -14
- snap7/async_client.py +11 -22
- snap7/client.py +9 -195
- snap7/connection.py +5 -2
- snap7/partner.py +6 -2
- snap7/s7protocol.py +3 -2
- snap7/server/__init__.py +3 -2
- snap7/tags.py +230 -9
- snap7/util/setters.py +48 -2
- {python_snap7-3.3.1.dist-info → python_snap7-3.4.0.dist-info}/WHEEL +0 -0
- {python_snap7-3.3.1.dist-info → python_snap7-3.4.0.dist-info}/entry_points.txt +0 -0
- {python_snap7-3.3.1.dist-info → python_snap7-3.4.0.dist-info}/licenses/LICENSE +0 -0
- {python_snap7-3.3.1.dist-info → python_snap7-3.4.0.dist-info}/top_level.txt +0 -0
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
python_snap7-3.
|
|
1
|
+
python_snap7-3.4.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=45CB0uKDBlkoMv2ZMMvSzY7dqHIIG9ux6B84VhYTHf4,66036
|
|
5
5
|
snap7/cli.py,sha256=L1B7NMAemDcl93JUSqJV3Ls_CN2ghlG75nTMD08JkMs,13787
|
|
6
|
-
snap7/client.py,sha256=
|
|
6
|
+
snap7/client.py,sha256=eUmmIP9oHW8W2ni5r8DYNglWhNmWjNtMTbCh1YZODT0,102336
|
|
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
|
|
@@ -13,22 +13,22 @@ 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
15
|
snap7/optimizer.py,sha256=Bu4zWCfdeA5GG3sWwjYOLkp0tWEfNbAXvbe_RldlYVM,9383
|
|
16
|
-
snap7/partner.py,sha256=
|
|
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=
|
|
20
|
+
snap7/s7protocol.py,sha256=Dk_FNt0bZCOuVsdF0Aj1JbvO4ke2GYnEUxjNuoMRB_Q,70992
|
|
21
21
|
snap7/szl.py,sha256=952lFvuTTE4nBlG2Lvn_3SaS_hazkM0ZfboIPgTwFM8,7999
|
|
22
|
-
snap7/tags.py,sha256=
|
|
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=8gfQjx0xjLGB5rISQNOgbM-QuplFk7_Y3XZElDULAH0,118004
|
|
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.4.0.dist-info/METADATA,sha256=2VtLbPWAGLnlpfJUN4jmHKqP_5yi7tHCXPRzGkbjCps,4669
|
|
31
|
+
python_snap7-3.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
32
|
+
python_snap7-3.4.0.dist-info/entry_points.txt,sha256=IPZyYr1lKyavXXpAc4xO505afTGwTY8GmNFuy5lsSiM,75
|
|
33
|
+
python_snap7-3.4.0.dist-info/top_level.txt,sha256=PTgDoDG45QNL2XIE9RM7S_ZCdWQjtMMuXNyrI2UdnbU,9
|
|
34
|
+
python_snap7-3.4.0.dist-info/RECORD,,
|
snap7/async_client.py
CHANGED
|
@@ -21,8 +21,8 @@ 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
|
|
24
|
+
from .tags import Tag, decode_tag, encode_tag
|
|
25
|
+
from .client import Client
|
|
26
26
|
from .szl import parse_cp_info_szl, parse_cpu_info_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
|
|
@@ -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,7 +807,7 @@ 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]:
|
|
@@ -814,7 +815,7 @@ class AsyncClient(ClientMixin):
|
|
|
814
815
|
resolved = [Tag.from_string(t) if isinstance(t, str) else t for t in tags]
|
|
815
816
|
items = [{"area": Area(t.area), "db_number": t.db_number, "start": t.byte_offset, "size": t.size} for t in resolved]
|
|
816
817
|
_code, data_list = await self.read_multi_vars(items)
|
|
817
|
-
return [
|
|
818
|
+
return [decode_tag(t, bytearray(d), encoding=encoding) for t, d in zip(resolved, data_list)]
|
|
818
819
|
|
|
819
820
|
async def db_get(self, db_number: int, size: int = 0) -> bytearray:
|
|
820
821
|
"""Get entire DB.
|
|
@@ -1022,8 +1023,6 @@ class AsyncClient(ClientMixin):
|
|
|
1022
1023
|
if not self.get_connected():
|
|
1023
1024
|
raise S7ConnectionError("Not connected to PLC")
|
|
1024
1025
|
|
|
1025
|
-
conn = self._get_connection()
|
|
1026
|
-
|
|
1027
1026
|
block_type_codes = {
|
|
1028
1027
|
Block.OB: 0x38,
|
|
1029
1028
|
Block.DB: 0x41,
|
|
@@ -1057,12 +1056,8 @@ class AsyncClient(ClientMixin):
|
|
|
1057
1056
|
if last_data_unit == 0x00:
|
|
1058
1057
|
break
|
|
1059
1058
|
|
|
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)
|
|
1059
|
+
followup = self.protocol.build_userdata_followup_request(group, subfunction, sequence_number)
|
|
1060
|
+
response = await self._send_receive(followup)
|
|
1066
1061
|
self.protocol.check_userdata_response(response, S7UserDataGroup.BLOCK_INFO, S7UserDataSubfunction.LIST_BLOCKS_OF_TYPE)
|
|
1067
1062
|
|
|
1068
1063
|
data_info = response.get("data", {})
|
|
@@ -1346,8 +1341,6 @@ class AsyncClient(ClientMixin):
|
|
|
1346
1341
|
if not self.get_connected():
|
|
1347
1342
|
raise S7ConnectionError("Not connected to PLC")
|
|
1348
1343
|
|
|
1349
|
-
conn = self._get_connection()
|
|
1350
|
-
|
|
1351
1344
|
request = self.protocol.build_read_szl_request(ssl_id, index)
|
|
1352
1345
|
response = await self._send_receive(request)
|
|
1353
1346
|
self.protocol.check_userdata_response(response, S7UserDataGroup.SZL, S7UserDataSubfunction.READ_SZL)
|
|
@@ -1371,12 +1364,8 @@ class AsyncClient(ClientMixin):
|
|
|
1371
1364
|
if last_data_unit == 0x00:
|
|
1372
1365
|
break
|
|
1373
1366
|
|
|
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)
|
|
1367
|
+
followup = self.protocol.build_userdata_followup_request(group, subfunction, sequence_number)
|
|
1368
|
+
response = await self._send_receive(followup)
|
|
1380
1369
|
self.protocol.check_userdata_response(response, S7UserDataGroup.SZL, S7UserDataSubfunction.READ_SZL)
|
|
1381
1370
|
|
|
1382
1371
|
data_info = response.get("data", {})
|
snap7/client.py
CHANGED
|
@@ -29,8 +29,7 @@ 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
34
|
from .szl import parse_cp_info_szl, parse_cpu_info_szl, parse_order_code_szl, parse_protection_szl
|
|
36
35
|
from .type import (
|
|
@@ -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]:
|
|
@@ -864,7 +688,7 @@ class Client(ClientMixin):
|
|
|
864
688
|
if resolved.is_symbolic:
|
|
865
689
|
raise NotImplementedError("Symbolic (LID-based) tag access is not supported by the classic S7 client.")
|
|
866
690
|
data = self.read_area(Area(resolved.area), resolved.db_number, resolved.byte_offset, resolved.size)
|
|
867
|
-
return
|
|
691
|
+
return decode_tag(resolved, bytearray(data), encoding=encoding)
|
|
868
692
|
|
|
869
693
|
def write_tag(self, tag: "Union[Tag, str]", value: Any, encoding: str = "latin-1") -> int:
|
|
870
694
|
"""Write a typed value by :class:`~snap7.tags.Tag` or address string.
|
|
@@ -886,7 +710,7 @@ class Client(ClientMixin):
|
|
|
886
710
|
if resolved.datatype.upper() == "BOOL":
|
|
887
711
|
current = self.read_area(Area(resolved.area), resolved.db_number, resolved.byte_offset, 1)
|
|
888
712
|
buf[0] = current[0]
|
|
889
|
-
|
|
713
|
+
encode_tag(resolved, buf, value, encoding=encoding)
|
|
890
714
|
return self.write_area(Area(resolved.area), resolved.db_number, resolved.byte_offset, buf)
|
|
891
715
|
|
|
892
716
|
def read_tags(self, tags: "Sequence[Union[Tag, str]]", encoding: str = "latin-1") -> list[Any]:
|
|
@@ -905,7 +729,7 @@ class Client(ClientMixin):
|
|
|
905
729
|
resolved = [Tag.from_string(t) if isinstance(t, str) else t for t in tags]
|
|
906
730
|
items = [{"area": Area(t.area), "db_number": t.db_number, "start": t.byte_offset, "size": t.size} for t in resolved]
|
|
907
731
|
_code, data_list = self.read_multi_vars(items)
|
|
908
|
-
return [
|
|
732
|
+
return [decode_tag(t, bytearray(d), encoding=encoding) for t, d in zip(resolved, data_list)]
|
|
909
733
|
|
|
910
734
|
def db_read(self, db_number: int, start: int, size: int) -> bytearray:
|
|
911
735
|
"""
|
|
@@ -1491,8 +1315,6 @@ class Client(ClientMixin):
|
|
|
1491
1315
|
if not self.get_connected():
|
|
1492
1316
|
raise S7ConnectionError("Not connected to PLC")
|
|
1493
1317
|
|
|
1494
|
-
conn = self._get_connection()
|
|
1495
|
-
|
|
1496
1318
|
# Map Block enum to S7 block type codes
|
|
1497
1319
|
block_type_codes = {
|
|
1498
1320
|
Block.OB: 0x38, # Organization Block
|
|
@@ -1534,10 +1356,7 @@ class Client(ClientMixin):
|
|
|
1534
1356
|
break
|
|
1535
1357
|
|
|
1536
1358
|
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)
|
|
1359
|
+
response = self._send_receive(followup)
|
|
1541
1360
|
self.protocol.check_userdata_response(response, S7UserDataGroup.BLOCK_INFO, S7UserDataSubfunction.LIST_BLOCKS_OF_TYPE)
|
|
1542
1361
|
|
|
1543
1362
|
# Check for errors
|
|
@@ -2143,8 +1962,6 @@ class Client(ClientMixin):
|
|
|
2143
1962
|
if not self.get_connected():
|
|
2144
1963
|
raise S7ConnectionError("Not connected to PLC")
|
|
2145
1964
|
|
|
2146
|
-
conn = self._get_connection()
|
|
2147
|
-
|
|
2148
1965
|
# Build and send read SZL request
|
|
2149
1966
|
request = self.protocol.build_read_szl_request(ssl_id, index)
|
|
2150
1967
|
response = self._send_receive(request)
|
|
@@ -2174,10 +1991,7 @@ class Client(ClientMixin):
|
|
|
2174
1991
|
break
|
|
2175
1992
|
|
|
2176
1993
|
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)
|
|
1994
|
+
response = self._send_receive(followup)
|
|
2181
1995
|
self.protocol.check_userdata_response(response, S7UserDataGroup.SZL, S7UserDataSubfunction.READ_SZL)
|
|
2182
1996
|
|
|
2183
1997
|
# 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:
|
snap7/partner.py
CHANGED
|
@@ -838,12 +838,16 @@ class Partner:
|
|
|
838
838
|
if self._connection is None:
|
|
839
839
|
raise S7ConnectionError("No connection object")
|
|
840
840
|
|
|
841
|
+
# The CR's source reference is the active partner's own; the CC echoes it
|
|
842
|
+
# as its destination reference, and our DR addresses it later (#972).
|
|
843
|
+
peer_ref = struct.unpack(">H", payload[4:6])[0]
|
|
844
|
+
self._connection.dst_ref = peer_ref
|
|
841
845
|
cc_pdu = struct.pack(
|
|
842
846
|
">BBHHB",
|
|
843
847
|
6, # PDU length
|
|
844
848
|
0xD0, # COTP_CC
|
|
845
|
-
|
|
846
|
-
|
|
849
|
+
peer_ref, # Destination reference (the active partner's)
|
|
850
|
+
self._connection.src_ref, # Source reference (ours)
|
|
847
851
|
0x00, # Class 0
|
|
848
852
|
)
|
|
849
853
|
# Add PDU size parameter
|
snap7/s7protocol.py
CHANGED
|
@@ -1312,9 +1312,10 @@ class S7Protocol:
|
|
|
1312
1312
|
microsecond = 0
|
|
1313
1313
|
if len(raw_data) == 10:
|
|
1314
1314
|
# Byte 8: milliseconds hundreds/tens (BCD); high nibble of byte 9: milliseconds ones
|
|
1315
|
-
|
|
1316
|
-
if
|
|
1315
|
+
millisecond_ones = time_bytes[7] >> 4
|
|
1316
|
+
if millisecond_ones > 9:
|
|
1317
1317
|
raise S7ProtocolError("Clock response contains an invalid BCD timestamp")
|
|
1318
|
+
microsecond = (from_bcd(time_bytes[6]) * 10 + millisecond_ones) * 1000
|
|
1318
1319
|
|
|
1319
1320
|
# The two-digit S7 year maps 90-99 to 1990-1999 and 00-89 to 2000-2089
|
|
1320
1321
|
full_year = 2000 + year if year < 90 else 1900 + year
|
snap7/server/__init__.py
CHANGED
|
@@ -2036,9 +2036,10 @@ class Server:
|
|
|
2036
2036
|
try:
|
|
2037
2037
|
from datetime import datetime
|
|
2038
2038
|
|
|
2039
|
-
|
|
2040
|
-
if
|
|
2039
|
+
millisecond_ones = raw_data[9] >> 4
|
|
2040
|
+
if millisecond_ones > 9 or not 1 <= (raw_data[9] & 0x0F) <= 7:
|
|
2041
2041
|
raise ValueError("Invalid clock millisecond or weekday")
|
|
2042
|
+
millisecond = from_bcd(raw_data[8]) * 10 + millisecond_ones
|
|
2042
2043
|
year = from_bcd(raw_data[2])
|
|
2043
2044
|
timestamp = datetime(
|
|
2044
2045
|
2000 + year if year < 90 else 1900 + year,
|
snap7/tags.py
CHANGED
|
@@ -47,6 +47,7 @@ from dataclasses import dataclass, field
|
|
|
47
47
|
from pathlib import Path
|
|
48
48
|
from typing import Any, Union
|
|
49
49
|
|
|
50
|
+
from . import util
|
|
50
51
|
from .type import Area
|
|
51
52
|
|
|
52
53
|
# Type name → byte size for fixed-size types
|
|
@@ -61,6 +62,7 @@ _TYPE_SIZE: dict[str, int] = {
|
|
|
61
62
|
"WORD": 2,
|
|
62
63
|
"WCHAR": 2,
|
|
63
64
|
"DATE": 2,
|
|
65
|
+
"S5TIME": 2,
|
|
64
66
|
"DINT": 4,
|
|
65
67
|
"UDINT": 4,
|
|
66
68
|
"DWORD": 4,
|
|
@@ -439,9 +441,11 @@ def parse_tag(address: str, *, strict: bool = True, name: str = "") -> Tag:
|
|
|
439
441
|
Args:
|
|
440
442
|
address: Tag address string.
|
|
441
443
|
strict: When ``True`` (default), require one of the dialect markers
|
|
442
|
-
above. Bare short forms like ``M7.1``
|
|
444
|
+
above and a type with a known size. Bare short forms like ``M7.1``
|
|
445
|
+
or ``IW22``, unknown types and ``STRING`` without a length raise
|
|
443
446
|
:class:`ValueError`. When ``False``, bare forms are dispatched
|
|
444
|
-
to the nodeS7 parser (which accepts them)
|
|
447
|
+
to the nodeS7 parser (which accepts them), and the type is not
|
|
448
|
+
checked until :attr:`Tag.size` is read.
|
|
445
449
|
name: Optional tag name to store on the resulting Tag.
|
|
446
450
|
|
|
447
451
|
Returns:
|
|
@@ -449,20 +453,237 @@ def parse_tag(address: str, *, strict: bool = True, name: str = "") -> Tag:
|
|
|
449
453
|
detected.
|
|
450
454
|
|
|
451
455
|
Raises:
|
|
452
|
-
ValueError: If the input is ambiguous
|
|
453
|
-
the selected parser fails to parse.
|
|
456
|
+
ValueError: If the input is ambiguous or its type has no known size
|
|
457
|
+
under strict mode, or if the selected parser fails to parse.
|
|
454
458
|
"""
|
|
455
459
|
s = address.strip()
|
|
460
|
+
tag: Tag
|
|
456
461
|
if "," in s:
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
462
|
+
tag = NodeS7Tag.parse(s, name)
|
|
463
|
+
elif ":" in s:
|
|
464
|
+
tag = PLC4XTag.parse(s, name)
|
|
465
|
+
elif strict:
|
|
461
466
|
raise ValueError(
|
|
462
467
|
f"Ambiguous tag syntax {address!r}: must contain ',' (nodeS7) "
|
|
463
468
|
f"or ':TYPE' (PLC4X). Pass strict=False to accept bare short forms."
|
|
464
469
|
)
|
|
465
|
-
|
|
470
|
+
else:
|
|
471
|
+
tag = NodeS7Tag.parse(s, name)
|
|
472
|
+
if strict:
|
|
473
|
+
try:
|
|
474
|
+
tag.size
|
|
475
|
+
except ValueError as e:
|
|
476
|
+
raise ValueError(f"Tag address {address!r} has a type with no known size: {tag.datatype}") from e
|
|
477
|
+
return tag
|
|
478
|
+
|
|
479
|
+
|
|
480
|
+
# ---------------------------------------------------------------------------
|
|
481
|
+
# Raw bytes <-> Python values
|
|
482
|
+
# ---------------------------------------------------------------------------
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def decode_tag(tag: Tag, data: bytearray, encoding: str = "latin-1") -> Any:
|
|
486
|
+
"""Decode a Tag's raw bytes into a typed Python value.
|
|
487
|
+
|
|
488
|
+
Args:
|
|
489
|
+
tag: The tag describing the value.
|
|
490
|
+
data: The tag's raw bytes, starting at offset 0, as read from the PLC.
|
|
491
|
+
encoding: Character encoding for ``STRING`` and ``FSTRING``.
|
|
492
|
+
|
|
493
|
+
Returns:
|
|
494
|
+
The decoded value, or a list of values when ``tag.count`` is above 1.
|
|
495
|
+
|
|
496
|
+
Raises:
|
|
497
|
+
ValueError: If the tag's type is unknown or has no decoder.
|
|
498
|
+
"""
|
|
499
|
+
upper = tag.datatype.upper()
|
|
500
|
+
# Variable-length string types
|
|
501
|
+
match = _STRING_RE.match(upper)
|
|
502
|
+
if match:
|
|
503
|
+
kind, length = match.group(1), int(match.group(2))
|
|
504
|
+
if kind == "FSTRING":
|
|
505
|
+
return util.get_fstring(data, 0, length, encoding=encoding)
|
|
506
|
+
if kind == "STRING":
|
|
507
|
+
return util.get_string(data, 0, encoding=encoding)
|
|
508
|
+
if kind == "WSTRING":
|
|
509
|
+
return util.get_wstring(data, 0)
|
|
510
|
+
|
|
511
|
+
# Arrays
|
|
512
|
+
if tag.count > 1:
|
|
513
|
+
per = tag.size // tag.count
|
|
514
|
+
return [_decode_scalar(upper, data[i * per : (i + 1) * per], tag.bit) for i in range(tag.count)]
|
|
515
|
+
|
|
516
|
+
return _decode_scalar(upper, data, tag.bit)
|
|
517
|
+
|
|
518
|
+
|
|
519
|
+
def _decode_scalar(datatype: str, data: bytearray, bit: int) -> Any:
|
|
520
|
+
"""Decode a single scalar value of the given type."""
|
|
521
|
+
if datatype == "BOOL":
|
|
522
|
+
return util.get_bool(data, 0, bit)
|
|
523
|
+
if datatype == "BYTE":
|
|
524
|
+
return util.get_byte(data, 0)
|
|
525
|
+
if datatype == "SINT":
|
|
526
|
+
return util.get_sint(data, 0)
|
|
527
|
+
if datatype == "USINT":
|
|
528
|
+
return util.get_usint(data, 0)
|
|
529
|
+
if datatype == "CHAR":
|
|
530
|
+
return util.get_char(data, 0)
|
|
531
|
+
if datatype == "INT":
|
|
532
|
+
return util.get_int(data, 0)
|
|
533
|
+
if datatype == "UINT":
|
|
534
|
+
return util.get_uint(data, 0)
|
|
535
|
+
if datatype == "WORD":
|
|
536
|
+
return util.get_word(data, 0)
|
|
537
|
+
if datatype == "WCHAR":
|
|
538
|
+
return util.get_wchar(data, 0)
|
|
539
|
+
if datatype == "DATE":
|
|
540
|
+
return util.get_date(data, 0)
|
|
541
|
+
if datatype == "S5TIME":
|
|
542
|
+
return util.get_s5time(data, 0)
|
|
543
|
+
if datatype == "DINT":
|
|
544
|
+
return util.get_dint(data, 0)
|
|
545
|
+
if datatype == "UDINT":
|
|
546
|
+
return util.get_udint(data, 0)
|
|
547
|
+
if datatype == "DWORD":
|
|
548
|
+
return util.get_dword(data, 0)
|
|
549
|
+
if datatype == "REAL":
|
|
550
|
+
return util.get_real(data, 0)
|
|
551
|
+
if datatype == "TIME":
|
|
552
|
+
return util.get_time(data, 0)
|
|
553
|
+
if datatype == "TOD":
|
|
554
|
+
return util.get_tod(data, 0)
|
|
555
|
+
if datatype == "LINT":
|
|
556
|
+
return util.get_lint(data, 0)
|
|
557
|
+
if datatype == "ULINT":
|
|
558
|
+
return util.get_ulint(data, 0)
|
|
559
|
+
if datatype == "LWORD":
|
|
560
|
+
return util.get_lword(data, 0)
|
|
561
|
+
if datatype == "LREAL":
|
|
562
|
+
return util.get_lreal(data, 0)
|
|
563
|
+
if datatype == "LTIME":
|
|
564
|
+
return util.get_ltime(data, 0)
|
|
565
|
+
if datatype == "LTOD":
|
|
566
|
+
return util.get_ltod(data, 0)
|
|
567
|
+
if datatype == "LDT":
|
|
568
|
+
return util.get_ldt(data, 0)
|
|
569
|
+
if datatype == "DT":
|
|
570
|
+
return util.get_dt(data, 0)
|
|
571
|
+
if datatype == "DTL":
|
|
572
|
+
return util.get_dtl(data, 0)
|
|
573
|
+
raise ValueError(f"Unsupported tag datatype: {datatype}")
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def encode_tag(tag: Tag, buf: bytearray, value: Any, encoding: str = "latin-1") -> None:
|
|
577
|
+
"""Encode a typed Python value into a Tag's byte buffer.
|
|
578
|
+
|
|
579
|
+
Args:
|
|
580
|
+
tag: The tag describing the value.
|
|
581
|
+
buf: Buffer of at least ``tag.size`` bytes. For ``BOOL`` it must hold the
|
|
582
|
+
byte's current value, since the other bits are kept.
|
|
583
|
+
value: The value, or a sequence of values when ``tag.count`` is above 1.
|
|
584
|
+
encoding: Character encoding for ``STRING`` and ``FSTRING``.
|
|
585
|
+
|
|
586
|
+
Raises:
|
|
587
|
+
ValueError: If the tag's type is unknown or has no encoder.
|
|
588
|
+
"""
|
|
589
|
+
upper = tag.datatype.upper()
|
|
590
|
+
match = _STRING_RE.match(upper)
|
|
591
|
+
if match:
|
|
592
|
+
kind, length = match.group(1), int(match.group(2))
|
|
593
|
+
if kind == "FSTRING":
|
|
594
|
+
util.set_fstring(buf, 0, value, length, encoding=encoding)
|
|
595
|
+
return
|
|
596
|
+
if kind == "STRING":
|
|
597
|
+
util.set_string(buf, 0, value, length, encoding=encoding)
|
|
598
|
+
return
|
|
599
|
+
if kind == "WSTRING":
|
|
600
|
+
util.set_wstring(buf, 0, value, length)
|
|
601
|
+
return
|
|
602
|
+
|
|
603
|
+
if tag.count > 1:
|
|
604
|
+
per = tag.size // tag.count
|
|
605
|
+
for i, v in enumerate(value):
|
|
606
|
+
_encode_scalar(upper, buf, i * per, v, tag.bit)
|
|
607
|
+
return
|
|
608
|
+
|
|
609
|
+
_encode_scalar(upper, buf, 0, value, tag.bit)
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def _encode_scalar(datatype: str, buf: bytearray, offset: int, value: Any, bit: int) -> None:
|
|
613
|
+
"""Encode a single scalar value at the given offset."""
|
|
614
|
+
if datatype == "BOOL":
|
|
615
|
+
util.set_bool(buf, offset, bit, value)
|
|
616
|
+
return
|
|
617
|
+
if datatype in ("BYTE", "USINT"):
|
|
618
|
+
util.set_byte(buf, offset, value) if datatype == "BYTE" else util.set_usint(buf, offset, value)
|
|
619
|
+
return
|
|
620
|
+
if datatype == "SINT":
|
|
621
|
+
util.set_sint(buf, offset, value)
|
|
622
|
+
return
|
|
623
|
+
if datatype == "CHAR":
|
|
624
|
+
util.set_char(buf, offset, value)
|
|
625
|
+
return
|
|
626
|
+
if datatype == "INT":
|
|
627
|
+
util.set_int(buf, offset, value)
|
|
628
|
+
return
|
|
629
|
+
if datatype == "UINT":
|
|
630
|
+
util.set_uint(buf, offset, value)
|
|
631
|
+
return
|
|
632
|
+
if datatype == "WORD":
|
|
633
|
+
util.set_word(buf, offset, value)
|
|
634
|
+
return
|
|
635
|
+
if datatype == "WCHAR":
|
|
636
|
+
util.set_wchar(buf, offset, value)
|
|
637
|
+
return
|
|
638
|
+
if datatype == "DATE":
|
|
639
|
+
util.set_date(buf, offset, value)
|
|
640
|
+
return
|
|
641
|
+
if datatype == "DINT":
|
|
642
|
+
util.set_dint(buf, offset, value)
|
|
643
|
+
return
|
|
644
|
+
if datatype == "UDINT":
|
|
645
|
+
util.set_udint(buf, offset, value)
|
|
646
|
+
return
|
|
647
|
+
if datatype == "DWORD":
|
|
648
|
+
util.set_dword(buf, offset, value)
|
|
649
|
+
return
|
|
650
|
+
if datatype == "REAL":
|
|
651
|
+
util.set_real(buf, offset, value)
|
|
652
|
+
return
|
|
653
|
+
if datatype == "TIME":
|
|
654
|
+
util.set_time(buf, offset, value)
|
|
655
|
+
return
|
|
656
|
+
if datatype == "TOD":
|
|
657
|
+
util.set_tod(buf, offset, value)
|
|
658
|
+
return
|
|
659
|
+
if datatype == "LINT":
|
|
660
|
+
util.set_lint(buf, offset, value)
|
|
661
|
+
return
|
|
662
|
+
if datatype == "ULINT":
|
|
663
|
+
util.set_ulint(buf, offset, value)
|
|
664
|
+
return
|
|
665
|
+
if datatype == "LWORD":
|
|
666
|
+
util.set_lword(buf, offset, value)
|
|
667
|
+
return
|
|
668
|
+
if datatype == "LREAL":
|
|
669
|
+
util.set_lreal(buf, offset, value)
|
|
670
|
+
return
|
|
671
|
+
if datatype == "LTIME":
|
|
672
|
+
util.set_ltime(buf, offset, value)
|
|
673
|
+
return
|
|
674
|
+
if datatype == "LTOD":
|
|
675
|
+
util.set_ltod(buf, offset, value)
|
|
676
|
+
return
|
|
677
|
+
if datatype == "LDT":
|
|
678
|
+
util.set_ldt(buf, offset, value)
|
|
679
|
+
return
|
|
680
|
+
if datatype == "DT":
|
|
681
|
+
util.set_dt(buf, offset, value)
|
|
682
|
+
return
|
|
683
|
+
if datatype == "DTL":
|
|
684
|
+
util.set_dtl(buf, offset, value)
|
|
685
|
+
return
|
|
686
|
+
raise ValueError(f"Unsupported tag datatype: {datatype}")
|
|
466
687
|
|
|
467
688
|
|
|
468
689
|
# ---------------------------------------------------------------------------
|
snap7/util/setters.py
CHANGED
|
@@ -10,6 +10,16 @@ from .getters import get_bool
|
|
|
10
10
|
Buffer = Union[bytearray, memoryview]
|
|
11
11
|
|
|
12
12
|
|
|
13
|
+
def _check_space(buffer: Buffer, byte_index: int, size: int) -> None:
|
|
14
|
+
"""Raise ValueError if ``size`` bytes don't fit at ``byte_index``.
|
|
15
|
+
|
|
16
|
+
A slice assignment past the end would otherwise grow a bytearray, which changes
|
|
17
|
+
the length of what gets written back to the PLC or shifts the fields after it.
|
|
18
|
+
"""
|
|
19
|
+
if byte_index + size > len(buffer):
|
|
20
|
+
raise ValueError(f"{size} bytes at index {byte_index} do not fit in a buffer of {len(buffer)} bytes")
|
|
21
|
+
|
|
22
|
+
|
|
13
23
|
def set_bool(bytearray_: Buffer, byte_index: int, bool_index: int, value: bool) -> Buffer:
|
|
14
24
|
"""Set boolean value on location in bytearray.
|
|
15
25
|
|
|
@@ -25,6 +35,7 @@ def set_bool(bytearray_: Buffer, byte_index: int, bool_index: int, value: bool)
|
|
|
25
35
|
>>> buffer
|
|
26
36
|
bytearray(b"\\x01")
|
|
27
37
|
"""
|
|
38
|
+
_check_space(bytearray_, byte_index, 1)
|
|
28
39
|
if value not in {0, 1, True, False}:
|
|
29
40
|
raise TypeError(f"Value value:{value} is not a boolean expression.")
|
|
30
41
|
|
|
@@ -60,6 +71,7 @@ def set_byte(bytearray_: Buffer, byte_index: int, _int: int) -> Buffer:
|
|
|
60
71
|
>>> set_byte(buffer, 0, 255)
|
|
61
72
|
bytearray(b"\\xFF")
|
|
62
73
|
"""
|
|
74
|
+
_check_space(bytearray_, byte_index, 1)
|
|
63
75
|
_int = int(_int)
|
|
64
76
|
bytearray_[byte_index : byte_index + 1] = struct.pack("B", _int)
|
|
65
77
|
return bytearray_
|
|
@@ -79,6 +91,7 @@ def set_word(bytearray_: Buffer, byte_index: int, _int: int) -> Buffer:
|
|
|
79
91
|
Return:
|
|
80
92
|
buffer with the written value
|
|
81
93
|
"""
|
|
94
|
+
_check_space(bytearray_, byte_index, 2)
|
|
82
95
|
_int = int(_int)
|
|
83
96
|
bytearray_[byte_index : byte_index + 2] = struct.pack(">H", _int)
|
|
84
97
|
return bytearray_
|
|
@@ -103,6 +116,7 @@ def set_int(bytearray_: Buffer, byte_index: int, _int: int) -> Buffer:
|
|
|
103
116
|
>>> set_int(data, 0, 255)
|
|
104
117
|
bytearray(b'\\x00\\xff')
|
|
105
118
|
"""
|
|
119
|
+
_check_space(bytearray_, byte_index, 2)
|
|
106
120
|
# make sure were dealing with an int
|
|
107
121
|
_int = int(_int)
|
|
108
122
|
bytearray_[byte_index : byte_index + 2] = struct.pack(">h", _int)
|
|
@@ -129,6 +143,7 @@ def set_uint(bytearray_: Buffer, byte_index: int, _int: int) -> Buffer:
|
|
|
129
143
|
>>> set_uint(data, 0, 65535)
|
|
130
144
|
bytearray(b'\\xff\\xff')
|
|
131
145
|
"""
|
|
146
|
+
_check_space(bytearray_, byte_index, 2)
|
|
132
147
|
# make sure were dealing with an int
|
|
133
148
|
_int = int(_int)
|
|
134
149
|
bytearray_[byte_index : byte_index + 2] = struct.pack(">H", _int)
|
|
@@ -155,6 +170,7 @@ def set_real(bytearray_: Buffer, byte_index: int, real: Union[bool, str, float,
|
|
|
155
170
|
>>> set_real(data, 0, 123.321)
|
|
156
171
|
bytearray(b'B\\xf6\\xa4Z')
|
|
157
172
|
"""
|
|
173
|
+
_check_space(bytearray_, byte_index, 4)
|
|
158
174
|
bytearray_[byte_index : byte_index + 4] = struct.pack(">f", float(real))
|
|
159
175
|
return bytearray_
|
|
160
176
|
|
|
@@ -180,6 +196,7 @@ def set_fstring(bytearray_: Buffer, byte_index: int, value: str, max_length: int
|
|
|
180
196
|
>>> data
|
|
181
197
|
bytearray(b'hello world \x00\x00\x00\x00\x00')
|
|
182
198
|
"""
|
|
199
|
+
_check_space(bytearray_, byte_index, max_length)
|
|
183
200
|
encoded = value.encode(encoding)
|
|
184
201
|
size = len(encoded)
|
|
185
202
|
if size > max_length:
|
|
@@ -216,6 +233,7 @@ def set_string(bytearray_: Buffer, byte_index: int, value: str, max_size: int =
|
|
|
216
233
|
>>> data
|
|
217
234
|
bytearray(b'\\xff\\x0bhello world\\x00\\x00\\x00\\x00\\x00\\x00\\x00')
|
|
218
235
|
"""
|
|
236
|
+
_check_space(bytearray_, byte_index, 2 + max_size)
|
|
219
237
|
if not isinstance(value, str):
|
|
220
238
|
raise TypeError(f"Value value:{value} is not from Type string")
|
|
221
239
|
|
|
@@ -260,6 +278,7 @@ def set_dword(bytearray_: Buffer, byte_index: int, dword: int) -> Buffer:
|
|
|
260
278
|
>>> data
|
|
261
279
|
bytearray(b'\\xff\\xff\\xff\\xff')
|
|
262
280
|
"""
|
|
281
|
+
_check_space(bytearray_, byte_index, 4)
|
|
263
282
|
dword = int(dword)
|
|
264
283
|
bytearray_[byte_index : byte_index + 4] = struct.pack(">I", dword)
|
|
265
284
|
return bytearray_
|
|
@@ -284,6 +303,7 @@ def set_dint(bytearray_: Buffer, byte_index: int, dint: int) -> Buffer:
|
|
|
284
303
|
>>> data
|
|
285
304
|
bytearray(b'\\x7f\\xff\\xff\\xff')
|
|
286
305
|
"""
|
|
306
|
+
_check_space(bytearray_, byte_index, 4)
|
|
287
307
|
dint = int(dint)
|
|
288
308
|
bytearray_[byte_index : byte_index + 4] = struct.pack(">i", dint)
|
|
289
309
|
return bytearray_
|
|
@@ -308,6 +328,7 @@ def set_udint(bytearray_: Buffer, byte_index: int, udint: int) -> Buffer:
|
|
|
308
328
|
>>> data
|
|
309
329
|
bytearray(b'\\xff\\xff\\xff\\xff')
|
|
310
330
|
"""
|
|
331
|
+
_check_space(bytearray_, byte_index, 4)
|
|
311
332
|
udint = int(udint)
|
|
312
333
|
bytearray_[byte_index : byte_index + 4] = struct.pack(">I", udint)
|
|
313
334
|
return bytearray_
|
|
@@ -334,6 +355,7 @@ def set_time(bytearray_: Buffer, byte_index: int, time_string: str) -> Buffer:
|
|
|
334
355
|
>>> data
|
|
335
356
|
bytearray(b'\x8d\xda\xaf\x00')
|
|
336
357
|
"""
|
|
358
|
+
_check_space(bytearray_, byte_index, 4)
|
|
337
359
|
sign = 1
|
|
338
360
|
if re.fullmatch(
|
|
339
361
|
r"(-?(2[0-3]|1?\d):(2[0-3]|1?\d|\d):([1-5]?\d):[1-5]?\d.\d{1,3})|"
|
|
@@ -381,6 +403,7 @@ def set_usint(bytearray_: Buffer, byte_index: int, _int: int) -> Buffer:
|
|
|
381
403
|
>>> set_usint(data, 0, 255)
|
|
382
404
|
bytearray(b'\\xff')
|
|
383
405
|
"""
|
|
406
|
+
_check_space(bytearray_, byte_index, 1)
|
|
384
407
|
_int = int(_int)
|
|
385
408
|
bytearray_[byte_index] = struct.pack(">B", _int)[0]
|
|
386
409
|
return bytearray_
|
|
@@ -407,6 +430,7 @@ def set_sint(bytearray_: Buffer, byte_index: int, _int: int) -> Buffer:
|
|
|
407
430
|
>>> set_sint(data, 0, 127)
|
|
408
431
|
bytearray(b'\\x7f')
|
|
409
432
|
"""
|
|
433
|
+
_check_space(bytearray_, byte_index, 1)
|
|
410
434
|
_int = int(_int)
|
|
411
435
|
bytearray_[byte_index] = struct.pack(">b", _int)[0]
|
|
412
436
|
return bytearray_
|
|
@@ -436,6 +460,7 @@ def set_lreal(bytearray_: Buffer, byte_index: int, lreal: float) -> Buffer:
|
|
|
436
460
|
>>> Client().db_write(db_number=1, start=10, data=data)
|
|
437
461
|
|
|
438
462
|
"""
|
|
463
|
+
_check_space(bytearray_, byte_index, 8)
|
|
439
464
|
lreal = float(lreal)
|
|
440
465
|
struct.pack_into(">d", bytearray_, byte_index, lreal)
|
|
441
466
|
return bytearray_
|
|
@@ -463,6 +488,7 @@ def set_lword(bytearray_: Buffer, byte_index: int, lword: int) -> Buffer:
|
|
|
463
488
|
>>> data
|
|
464
489
|
bytearray(b'\\x00\\x00\\x00\\x00\\x00\\x00\\xab\\xcd')
|
|
465
490
|
"""
|
|
491
|
+
_check_space(bytearray_, byte_index, 8)
|
|
466
492
|
lword = int(lword)
|
|
467
493
|
bytearray_[byte_index : byte_index + 8] = struct.pack(">Q", lword)
|
|
468
494
|
return bytearray_
|
|
@@ -489,6 +515,7 @@ def set_char(bytearray_: Buffer, byte_index: int, chr_: str) -> Buffer:
|
|
|
489
515
|
>>> data
|
|
490
516
|
bytearray('0x43')
|
|
491
517
|
"""
|
|
518
|
+
_check_space(bytearray_, byte_index, 1)
|
|
492
519
|
if not isinstance(chr_, str):
|
|
493
520
|
raise TypeError(f"Value value:{chr_} is not from Type string")
|
|
494
521
|
|
|
@@ -519,6 +546,7 @@ def set_date(bytearray_: Buffer, byte_index: int, date_: date) -> Buffer:
|
|
|
519
546
|
>>> data
|
|
520
547
|
bytearray(b'\x30\xd8')
|
|
521
548
|
"""
|
|
549
|
+
_check_space(bytearray_, byte_index, 2)
|
|
522
550
|
if date_ < date(1990, 1, 1):
|
|
523
551
|
raise ValueError("date is lower than specification allows.")
|
|
524
552
|
elif date_ > date(2168, 12, 31):
|
|
@@ -542,16 +570,24 @@ def set_wchar(bytearray_: Buffer, byte_index: int, chr_: str) -> Buffer:
|
|
|
542
570
|
Returns:
|
|
543
571
|
Buffer with the written value.
|
|
544
572
|
|
|
573
|
+
Raises:
|
|
574
|
+
TypeError: if the value is not a string.
|
|
575
|
+
ValueError: if the value is not a single character, or is outside the Basic Multilingual Plane
|
|
576
|
+
(codepoint > U+FFFF) and so does not fit in a `wchar`.
|
|
577
|
+
|
|
545
578
|
Examples:
|
|
546
579
|
>>> data = bytearray(2)
|
|
547
580
|
>>> set_wchar(data, 0, 'C')
|
|
548
581
|
>>> data
|
|
549
582
|
bytearray(b'\\x00C')
|
|
550
583
|
"""
|
|
584
|
+
_check_space(bytearray_, byte_index, 2)
|
|
551
585
|
if not isinstance(chr_, str):
|
|
552
586
|
raise TypeError(f"Value value:{chr_} is not from Type string")
|
|
553
587
|
if len(chr_) != 1:
|
|
554
588
|
raise ValueError(f"Expected single character, got length {len(chr_)}")
|
|
589
|
+
if ord(chr_) > 0xFFFF:
|
|
590
|
+
raise ValueError(f"Character U+{ord(chr_):X} is outside the Basic Multilingual Plane and does not fit in a wchar")
|
|
555
591
|
encoded = chr_.encode("utf-16-be")
|
|
556
592
|
bytearray_[byte_index : byte_index + 2] = encoded
|
|
557
593
|
return bytearray_
|
|
@@ -595,14 +631,16 @@ def set_wstring(bytearray_: Buffer, byte_index: int, value: str, max_size: int =
|
|
|
595
631
|
if size > max_size:
|
|
596
632
|
raise ValueError(f"size {size} > max_size {max_size}")
|
|
597
633
|
|
|
634
|
+
encoded = value.encode("utf-16-be")
|
|
635
|
+
_check_space(bytearray_, byte_index, 4 + len(encoded))
|
|
636
|
+
|
|
598
637
|
# set max string size (2 bytes, big-endian)
|
|
599
638
|
bytearray_[byte_index : byte_index + 2] = struct.pack(">H", max_size)
|
|
600
639
|
|
|
601
640
|
# set current length (2 bytes, big-endian)
|
|
602
641
|
bytearray_[byte_index + 2 : byte_index + 4] = struct.pack(">H", size)
|
|
603
642
|
|
|
604
|
-
#
|
|
605
|
-
encoded = value.encode("utf-16-be")
|
|
643
|
+
# write UTF-16-BE characters
|
|
606
644
|
bytearray_[byte_index + 4 : byte_index + 4 + len(encoded)] = encoded
|
|
607
645
|
|
|
608
646
|
|
|
@@ -626,6 +664,7 @@ def set_tod(bytearray_: Buffer, byte_index: int, tod: timedelta) -> Buffer:
|
|
|
626
664
|
>>> data = bytearray(4)
|
|
627
665
|
>>> set_tod(data, 0, timedelta(hours=12, minutes=30, seconds=15, milliseconds=500))
|
|
628
666
|
"""
|
|
667
|
+
_check_space(bytearray_, byte_index, 4)
|
|
629
668
|
if tod.days >= 1 or tod < timedelta(0):
|
|
630
669
|
raise ValueError("TIME_OF_DAY must be between 00:00:00.000 and 23:59:59.999")
|
|
631
670
|
ms = (tod.days * 86400 + tod.seconds) * 1000 + tod.microseconds // 1000
|
|
@@ -660,6 +699,7 @@ def set_dtl(bytearray_: Buffer, byte_index: int, dt_: datetime) -> Buffer:
|
|
|
660
699
|
>>> data = bytearray(12)
|
|
661
700
|
>>> set_dtl(data, 0, datetime(2024, 3, 27, 14, 30, 0))
|
|
662
701
|
"""
|
|
702
|
+
_check_space(bytearray_, byte_index, 12)
|
|
663
703
|
if dt_ > datetime(2554, 12, 31, 23, 59, 59):
|
|
664
704
|
raise ValueError("date_val is higher than specification allows.")
|
|
665
705
|
|
|
@@ -704,6 +744,7 @@ def set_dt(bytearray_: Buffer, byte_index: int, dt_: datetime) -> Buffer:
|
|
|
704
744
|
>>> data = bytearray(8)
|
|
705
745
|
>>> set_dt(data, 0, datetime(2020, 7, 12, 17, 32, 2, 854000))
|
|
706
746
|
"""
|
|
747
|
+
_check_space(bytearray_, byte_index, 8)
|
|
707
748
|
|
|
708
749
|
def byte_to_bcd(val: int) -> int:
|
|
709
750
|
return ((val // 10) << 4) | (val % 10)
|
|
@@ -752,6 +793,7 @@ def set_lint(bytearray_: Buffer, byte_index: int, value: int) -> Buffer:
|
|
|
752
793
|
>>> data = bytearray(8)
|
|
753
794
|
>>> set_lint(data, 0, 12345)
|
|
754
795
|
"""
|
|
796
|
+
_check_space(bytearray_, byte_index, 8)
|
|
755
797
|
bytearray_[byte_index : byte_index + 8] = struct.pack(">q", value)
|
|
756
798
|
return bytearray_
|
|
757
799
|
|
|
@@ -775,6 +817,7 @@ def set_ulint(bytearray_: Buffer, byte_index: int, value: int) -> Buffer:
|
|
|
775
817
|
>>> data = bytearray(8)
|
|
776
818
|
>>> set_ulint(data, 0, 12345)
|
|
777
819
|
"""
|
|
820
|
+
_check_space(bytearray_, byte_index, 8)
|
|
778
821
|
bytearray_[byte_index : byte_index + 8] = struct.pack(">Q", value)
|
|
779
822
|
return bytearray_
|
|
780
823
|
|
|
@@ -799,6 +842,7 @@ def set_ltime(bytearray_: Buffer, byte_index: int, value: timedelta) -> Buffer:
|
|
|
799
842
|
>>> data = bytearray(8)
|
|
800
843
|
>>> set_ltime(data, 0, timedelta(seconds=1))
|
|
801
844
|
"""
|
|
845
|
+
_check_space(bytearray_, byte_index, 8)
|
|
802
846
|
# Use integer arithmetic to avoid float precision loss
|
|
803
847
|
nanoseconds = (value.days * 86400 + value.seconds) * 1_000_000_000 + value.microseconds * 1000
|
|
804
848
|
bytearray_[byte_index : byte_index + 8] = struct.pack(">q", nanoseconds)
|
|
@@ -825,6 +869,7 @@ def set_ltod(bytearray_: Buffer, byte_index: int, value: timedelta) -> Buffer:
|
|
|
825
869
|
>>> data = bytearray(8)
|
|
826
870
|
>>> set_ltod(data, 0, timedelta(hours=12, minutes=30))
|
|
827
871
|
"""
|
|
872
|
+
_check_space(bytearray_, byte_index, 8)
|
|
828
873
|
if value.days >= 1:
|
|
829
874
|
raise ValueError("LTOD value must be less than 24 hours")
|
|
830
875
|
nanoseconds = (value.days * 86400 + value.seconds) * 1_000_000_000 + value.microseconds * 1000
|
|
@@ -853,6 +898,7 @@ def set_ldt(bytearray_: Buffer, byte_index: int, value: datetime) -> Buffer:
|
|
|
853
898
|
>>> data = bytearray(8)
|
|
854
899
|
>>> set_ldt(data, 0, datetime(2024, 1, 15, 10, 30, 0))
|
|
855
900
|
"""
|
|
901
|
+
_check_space(bytearray_, byte_index, 8)
|
|
856
902
|
epoch = datetime(1970, 1, 1)
|
|
857
903
|
delta = value - epoch
|
|
858
904
|
nanoseconds = (delta.days * 86400 + delta.seconds) * 1_000_000_000 + delta.microseconds * 1000
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|