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
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
|
@@ -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
|
|
@@ -1486,12 +1487,16 @@ class S7Protocol:
|
|
|
1486
1487
|
|
|
1487
1488
|
def build_cpu_state_request(self) -> bytes:
|
|
1488
1489
|
"""
|
|
1489
|
-
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.
|
|
1490
1496
|
|
|
1491
1497
|
Returns:
|
|
1492
|
-
|
|
1498
|
+
S7 PDU for the old CPU state query
|
|
1493
1499
|
"""
|
|
1494
|
-
# Simple CPU state request - in real S7 this would be a userdata function
|
|
1495
1500
|
header = struct.pack(
|
|
1496
1501
|
">BBHHHH",
|
|
1497
1502
|
0x32, # Protocol ID
|
|
@@ -1502,24 +1507,26 @@ class S7Protocol:
|
|
|
1502
1507
|
0x0000, # Data length
|
|
1503
1508
|
)
|
|
1504
1509
|
|
|
1505
|
-
|
|
1506
|
-
parameters = struct.pack(">B", 0x04) # Use READ_AREA function for simplicity
|
|
1510
|
+
parameters = struct.pack(">B", 0x04) # READ_AREA function code, nothing else
|
|
1507
1511
|
|
|
1508
1512
|
return header + parameters
|
|
1509
1513
|
|
|
1510
1514
|
def extract_cpu_state(self, response: Dict[str, Any]) -> str:
|
|
1511
1515
|
"""
|
|
1512
|
-
|
|
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.
|
|
1513
1522
|
|
|
1514
1523
|
Args:
|
|
1515
|
-
response: Parsed S7 response
|
|
1524
|
+
response: Parsed S7 response (ignored)
|
|
1516
1525
|
|
|
1517
1526
|
Returns:
|
|
1518
|
-
|
|
1527
|
+
Always ``"S7CpuStatusRun"``
|
|
1519
1528
|
"""
|
|
1520
|
-
|
|
1521
|
-
# The cpu_statuses dict in type.py uses: {0: "S7CpuStatusUnknown", 4: "S7CpuStatusStop", 8: "S7CpuStatusRun"}
|
|
1522
|
-
return "S7CpuStatusRun" # Default state for pure Python server
|
|
1529
|
+
return "S7CpuStatusRun"
|
|
1523
1530
|
|
|
1524
1531
|
def parse_response(self, pdu: bytes) -> Dict[str, Any]:
|
|
1525
1532
|
"""
|
snap7/server/__init__.py
CHANGED
|
@@ -1021,9 +1021,9 @@ class Server:
|
|
|
1021
1021
|
)
|
|
1022
1022
|
return (area, db_number, start, byte_count)
|
|
1023
1023
|
|
|
1024
|
-
#
|
|
1025
|
-
logger.warning("
|
|
1026
|
-
return
|
|
1024
|
+
# A read request without an address specification is malformed
|
|
1025
|
+
logger.warning("Read request carries no address specification")
|
|
1026
|
+
return None
|
|
1027
1027
|
|
|
1028
1028
|
except Exception as e:
|
|
1029
1029
|
logger.error(f"Error parsing read address: {e}")
|
|
@@ -1837,6 +1837,7 @@ class Server:
|
|
|
1837
1837
|
- 0x001C: Component identification (for get_cpu_info)
|
|
1838
1838
|
- 0x0011: Module identification (for get_order_code)
|
|
1839
1839
|
- 0x0131: Communication parameters (for get_cp_info)
|
|
1840
|
+
- 0x0424: Current operating mode transition (for get_cpu_state)
|
|
1840
1841
|
- 0x0232: Protection level (for get_protection)
|
|
1841
1842
|
|
|
1842
1843
|
Args:
|
|
@@ -1933,10 +1934,19 @@ class Server:
|
|
|
1933
1934
|
# anl_sch: factory setting protection
|
|
1934
1935
|
return struct.pack(">HHHHH", 1, 0, 0, 0, 0) # No protection
|
|
1935
1936
|
|
|
1937
|
+
# SZL 0x0424: current operating mode transition (get_cpu_state)
|
|
1938
|
+
# Record layout: ereig(2) + ae(1) + bzu-id(1) + res(4) + anlinfo1..4(4) + time(8) = 20 bytes.
|
|
1939
|
+
# bzu-id carries the requested mode in bits 0-3: 4 is STOP, 8 is RUN.
|
|
1940
|
+
elif szl_id == 0x0424:
|
|
1941
|
+
# Event IDs: 0x4302 "STARTUP to RUN", 0x4304 "STOP caused by PG STOP operation"
|
|
1942
|
+
event_ids = {CPUState.RUN: 0x4302, CPUState.STOP: 0x4304}
|
|
1943
|
+
record = struct.pack(">HBB", event_ids.get(self.cpu_state, 0x0000), 0xFF, int(self.cpu_state)) + bytes(16)
|
|
1944
|
+
return struct.pack(">HH", len(record), 1) + record
|
|
1945
|
+
|
|
1936
1946
|
# SZL 0x0000: SZL list
|
|
1937
1947
|
elif szl_id == 0x0000:
|
|
1938
1948
|
# Return list of available SZL IDs
|
|
1939
|
-
available_ids = [0x0000, 0x0011, 0x001C, 0x0131, 0x0232]
|
|
1949
|
+
available_ids = [0x0000, 0x0011, 0x001C, 0x0131, 0x0232, 0x0424]
|
|
1940
1950
|
szl_bytes = b""
|
|
1941
1951
|
for id_val in available_ids:
|
|
1942
1952
|
szl_bytes += struct.pack(">H", id_val)
|
|
@@ -2036,9 +2046,10 @@ class Server:
|
|
|
2036
2046
|
try:
|
|
2037
2047
|
from datetime import datetime
|
|
2038
2048
|
|
|
2039
|
-
|
|
2040
|
-
if
|
|
2049
|
+
millisecond_ones = raw_data[9] >> 4
|
|
2050
|
+
if millisecond_ones > 9 or not 1 <= (raw_data[9] & 0x0F) <= 7:
|
|
2041
2051
|
raise ValueError("Invalid clock millisecond or weekday")
|
|
2052
|
+
millisecond = from_bcd(raw_data[8]) * 10 + millisecond_ones
|
|
2042
2053
|
year = from_bcd(raw_data[2])
|
|
2043
2054
|
timestamp = datetime(
|
|
2044
2055
|
2000 + year if year < 90 else 1900 + year,
|
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
|
|
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
|
# ---------------------------------------------------------------------------
|