python-snap7 3.4.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-snap7
3
- Version: 3.4.0
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 :: POSIX
15
+ Classifier: Operating System :: OS Independent
16
16
  Classifier: Programming Language :: Python :: 3.10
17
17
  Classifier: Programming Language :: Python :: 3.11
18
18
  Classifier: Programming Language :: Python :: 3.12
@@ -1,9 +1,9 @@
1
- python_snap7-3.4.0.dist-info/licenses/LICENSE,sha256=PIihE_yP-8gc-ff9ikvQQPOa0biOCZ6Bc-6h3G3xRUQ,1097
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=45CB0uKDBlkoMv2ZMMvSzY7dqHIIG9ux6B84VhYTHf4,66036
4
+ snap7/async_client.py,sha256=_cb17lJaXMApfAEOPzH9AZZa7QFE1TkvMLvY6ywNitE,66408
5
5
  snap7/cli.py,sha256=L1B7NMAemDcl93JUSqJV3Ls_CN2ghlG75nTMD08JkMs,13787
6
- snap7/client.py,sha256=eUmmIP9oHW8W2ni5r8DYNglWhNmWjNtMTbCh1YZODT0,102336
6
+ snap7/client.py,sha256=iNzg2RPTwUA2px3Oq_lYB18-0KhutLIR6f0nCD_klHk,103674
7
7
  snap7/client_base.py,sha256=tNZs_MA8FGit8pg9axNoljH1kFToDI1HIzXC8WQLYHs,11324
8
8
  snap7/connection.py,sha256=W-jOV7hXVI-cuCFcqRzXY3vFp8weeJh0zEJzXNLLBss,19053
9
9
  snap7/datatypes.py,sha256=Gqu1XDuKkQI76n4TYrFrhm0RlPz4XNA5GKA-GJJXJDU,12042
@@ -12,23 +12,23 @@ snap7/discovery.py,sha256=LONPYg83b2quKXht6y_GTTArdxitjD8DoGyaHfe9B1w,3964
12
12
  snap7/error.py,sha256=S5BquFFSL1NpgdytIpOD_FzhN6gOCngSkxJVZT4rxdw,21323
13
13
  snap7/log.py,sha256=XX4UyPgByz3EhTc39BTGY454fHvYmiJAX4v-a-gkIEY,4968
14
14
  snap7/logo.py,sha256=0h-EZ5K86Qddna_lryBn6xLXLVwnznYJuMGuevzH6bI,9192
15
- snap7/optimizer.py,sha256=Bu4zWCfdeA5GG3sWwjYOLkp0tWEfNbAXvbe_RldlYVM,9383
15
+ snap7/optimizer.py,sha256=YK6B2RedZ59kIIYH8fV70eVCz-T694Kl6c4ltcu61FQ,9944
16
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=Dk_FNt0bZCOuVsdF0Aj1JbvO4ke2GYnEUxjNuoMRB_Q,70992
21
- snap7/szl.py,sha256=952lFvuTTE4nBlG2Lvn_3SaS_hazkM0ZfboIPgTwFM8,7999
20
+ snap7/s7protocol.py,sha256=kSKtJYBcSYLVSSMiVlDwjxZR7x6NyhGsft4oAMso-mg,71107
21
+ snap7/szl.py,sha256=eQsSTw_GT9l_OXZ8eYC_notJct5qowNXSa3T3LNq7EY,9472
22
22
  snap7/tags.py,sha256=5YmYKtRXc3GMpqqkv6J0q1IHZ_k5y17yNLqFx6KjoqI,34332
23
23
  snap7/type.py,sha256=EiXqU0ayYYxlM-5fUcPL7psgL1EGNNqAa7JXH4QlAnU,9752
24
- snap7/server/__init__.py,sha256=8gfQjx0xjLGB5rISQNOgbM-QuplFk7_Y3XZElDULAH0,118004
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
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,,
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
@@ -23,7 +23,7 @@ from .error import S7Error, S7ConnectionError, S7ProtocolError, S7TimeoutError
23
23
  from .client_base import ClientMixin, _instrumented
24
24
  from .tags import Tag, decode_tag, encode_tag
25
25
  from .client import Client
26
- from .szl import parse_cp_info_szl, parse_cpu_info_szl, parse_order_code_szl, parse_protection_szl
26
+ from .szl import parse_cp_info_szl, parse_cpu_info_szl, parse_cpu_state_szl, parse_order_code_szl, parse_protection_szl
27
27
  from .client import _parse_force_szl
28
28
  from .rate_limiter import RateLimitAlgorithm, RateLimitBehavior, RequestRateLimiter
29
29
  from .type import (
@@ -811,8 +811,10 @@ class AsyncClient(ClientMixin):
811
811
  return await self.write_area(Area(resolved.area), resolved.db_number, resolved.byte_offset, buf)
812
812
 
813
813
  async def read_tags(self, tags: "Sequence[Union[Tag, str]]", encoding: str = "latin-1") -> list[Any]:
814
- """Read multiple tags in a single optimized request, in input order."""
814
+ """Read any number of tags, returning the values in input order."""
815
815
  resolved = [Tag.from_string(t) if isinstance(t, str) else t for t in tags]
816
+ if any(t.is_symbolic for t in resolved):
817
+ raise NotImplementedError("Symbolic (LID-based) tag access is not supported by the classic S7 client.")
816
818
  items = [{"area": Area(t.area), "db_number": t.db_number, "start": t.byte_offset, "size": t.size} for t in resolved]
817
819
  _code, data_list = await self.read_multi_vars(items)
818
820
  return [decode_tag(t, bytearray(d), encoding=encoding) for t, d in zip(resolved, data_list)]
@@ -951,15 +953,14 @@ class AsyncClient(ClientMixin):
951
953
  """Read multiple variables (sequentially, one read_area per item).
952
954
 
953
955
  Args:
954
- items: List of item dicts with keys: area, db_number, start, size
956
+ items: List of item dicts with keys: area, db_number, start, size.
957
+ Any number of items is accepted.
955
958
 
956
959
  Returns:
957
960
  Tuple of (result_code, list_of_bytearrays)
958
961
  """
959
962
  if not items:
960
963
  return (0, [])
961
- if len(items) > self.MAX_VARS:
962
- raise ValueError(f"Too many items: {len(items)} exceeds MAX_VARS ({self.MAX_VARS})")
963
964
 
964
965
  results: list[bytearray] = []
965
966
  for item in items:
@@ -1115,10 +1116,16 @@ class AsyncClient(ClientMixin):
1115
1116
  return parse_cpu_info_szl(await self.read_szl(0x001C, 0))
1116
1117
 
1117
1118
  async def get_cpu_state(self) -> str:
1118
- """Get CPU state (running/stopped)."""
1119
- request = self.protocol.build_cpu_state_request()
1120
- response = await self._send_receive(request)
1121
- return self.protocol.extract_cpu_state(response)
1119
+ """Get the CPU operating state by reading SZL 0x0424.
1120
+
1121
+ Returns ``"S7CpuStatusRun"``, ``"S7CpuStatusStop"`` or ``"S7CpuStatusUnknown"``.
1122
+ Startup, HOLD and DEFECT are reported as ``"S7CpuStatusStop"``, as native Snap7 does.
1123
+
1124
+ Raises:
1125
+ S7ConnectionError: If the client is not connected.
1126
+ S7ProtocolError: If the PLC refuses SZL 0x0424 or its reply is too short.
1127
+ """
1128
+ return parse_cpu_state_szl(await self.read_szl(0x0424, 0))
1122
1129
 
1123
1130
  # ---------------------------------------------------------------
1124
1131
  # Upload / Download / Delete
snap7/client.py CHANGED
@@ -24,14 +24,14 @@ from ctypes import (
24
24
  from .connection import ISOTCPConnection
25
25
  from .s7protocol import S7Protocol, S7UserDataGroup, S7UserDataSubfunction, get_return_code_description
26
26
  from .datatypes import S7DataTypes, S7WordLen
27
- from .error import S7Error, S7ConnectionError, S7ProtocolError, S7StalePacketError, S7TimeoutError
27
+ from .error import S7Error, S7ConnectionError, S7PacketLostError, S7ProtocolError, S7StalePacketError, S7TimeoutError
28
28
  from .client_base import ClientMixin, _instrumented
29
29
  from .log import PLCLoggerAdapter, OperationLogger
30
30
  from .optimizer import ReadItem, ReadPacket, sort_items, merge_items, packetize, extract_results
31
31
  from .rate_limiter import RateLimitAlgorithm, RateLimitBehavior, RequestRateLimiter
32
32
  from .tags import Tag, decode_tag, encode_tag
33
33
 
34
- from .szl import parse_cp_info_szl, parse_cpu_info_szl, parse_order_code_szl, parse_protection_szl
34
+ from .szl import parse_cp_info_szl, parse_cpu_info_szl, parse_cpu_state_szl, parse_order_code_szl, parse_protection_szl
35
35
  from .type import (
36
36
  Area,
37
37
  Block,
@@ -107,7 +107,7 @@ class Client(ClientMixin):
107
107
  >>> client.disconnect()
108
108
  """
109
109
 
110
- MAX_VARS = 20 # Max variables per multi-read/multi-write request
110
+ MAX_VARS = 20 # Max variables per multi-read/multi-write PDU
111
111
 
112
112
  def __init__(
113
113
  self,
@@ -421,7 +421,7 @@ class Client(ClientMixin):
421
421
  try:
422
422
  with self._reconnect_lock:
423
423
  if self.connected and self.connection is not None:
424
- self.get_cpu_state()
424
+ self._heartbeat_probe()
425
425
  self._is_alive = True
426
426
  except Exception as e:
427
427
  logger.warning(f"Heartbeat probe failed: {e}")
@@ -434,6 +434,20 @@ class Client(ClientMixin):
434
434
  except S7ConnectionError:
435
435
  logger.warning("Heartbeat reconnection failed")
436
436
 
437
+ def _heartbeat_probe(self) -> None:
438
+ """Ask the PLC for its CPU state to prove the connection is alive.
439
+
440
+ A PLC that answers with a refusal (for example a CPU without
441
+ SZL 0x0424) has still answered, so only a transport failure or a lost
442
+ or stale reply is raised.
443
+ """
444
+ try:
445
+ self.get_cpu_state()
446
+ except (S7PacketLostError, S7StalePacketError):
447
+ raise
448
+ except (S7ProtocolError, RuntimeError) as e:
449
+ logger.debug(f"Heartbeat probe was refused, connection is alive: {e}")
450
+
437
451
  def connect(self, address: str, rack: int, slot: int, tcp_port: int = 102) -> "Client":
438
452
  """
439
453
  Connect to S7 PLC.
@@ -714,10 +728,11 @@ class Client(ClientMixin):
714
728
  return self.write_area(Area(resolved.area), resolved.db_number, resolved.byte_offset, buf)
715
729
 
716
730
  def read_tags(self, tags: "Sequence[Union[Tag, str]]", encoding: str = "latin-1") -> list[Any]:
717
- """Read multiple tags in a single optimized request.
731
+ """Read multiple tags in as few requests as possible.
718
732
 
719
733
  Uses the multi-variable read optimizer when available to batch
720
- reads into minimal PDU exchanges.
734
+ reads into minimal PDU exchanges. Any number of tags is accepted;
735
+ tags that do not fit in one request go into further requests.
721
736
 
722
737
  Args:
723
738
  tags: Sequence of :class:`~snap7.tags.Tag` instances or address strings.
@@ -727,6 +742,8 @@ class Client(ClientMixin):
727
742
  List of decoded values in the same order as input.
728
743
  """
729
744
  resolved = [Tag.from_string(t) if isinstance(t, str) else t for t in tags]
745
+ if any(t.is_symbolic for t in resolved):
746
+ raise NotImplementedError("Symbolic (LID-based) tag access is not supported by the classic S7 client.")
730
747
  items = [{"area": Area(t.area), "db_number": t.db_number, "start": t.byte_offset, "size": t.size} for t in resolved]
731
748
  _code, data_list = self.read_multi_vars(items)
732
749
  return [decode_tag(t, bytearray(d), encoding=encoding) for t, d in zip(resolved, data_list)]
@@ -962,12 +979,14 @@ class Client(ClientMixin):
962
979
 
963
980
  @_instrumented("read_multi_vars")
964
981
  def read_multi_vars(self, items: Union[List[dict[str, Any]], "Array[S7DataItem]"]) -> Tuple[int, Any]:
965
- """Read multiple variables in a single request.
982
+ """Read multiple variables in as few requests as possible.
966
983
 
967
984
  When given a list of dicts with two or more items, uses the multi-variable
968
985
  read optimizer to merge adjacent reads and pack them into minimal PDU
969
986
  exchanges. This significantly reduces the number of round-trips compared
970
- to reading each variable individually.
987
+ to reading each variable individually. A list of dicts may hold any
988
+ number of items: each request carries at most ``MAX_VARS`` address
989
+ specifications and the rest go into further requests.
971
990
 
972
991
  .. warning::
973
992
 
@@ -985,16 +1004,15 @@ class Client(ClientMixin):
985
1004
  ctypes array or a list of bytearrays in the original item order.
986
1005
 
987
1006
  Raises:
988
- ValueError: If more than MAX_VARS items are requested.
1007
+ ValueError: If a ctypes array holds more than MAX_VARS items.
989
1008
  """
990
1009
  if not items:
991
1010
  return (0, items)
992
1011
 
993
- if len(items) > self.MAX_VARS:
994
- raise ValueError(f"Too many items: {len(items)} exceeds MAX_VARS ({self.MAX_VARS})")
995
-
996
1012
  # Handle S7DataItem array (ctypes) -- unchanged legacy path
997
1013
  if hasattr(items, "_type_") and hasattr(items[0], "Area"):
1014
+ if len(items) > self.MAX_VARS:
1015
+ raise ValueError(f"Too many items: {len(items)} exceeds MAX_VARS ({self.MAX_VARS})")
998
1016
  s7_items = cast("Array[S7DataItem]", items)
999
1017
  for s7_item in s7_items:
1000
1018
  area = Area(s7_item.Area)
@@ -1138,7 +1156,7 @@ class Client(ClientMixin):
1138
1156
  sorted_ri = sort_items(read_items)
1139
1157
  max_block = self._max_read_size()
1140
1158
  blocks = merge_items(sorted_ri, max_gap=self.multi_read_max_gap, max_block_size=max_block)
1141
- packets = packetize(blocks, self.pdu_length)
1159
+ packets = packetize(blocks, self.pdu_length, max_items=self.MAX_VARS)
1142
1160
  self._opt_plan = _OptimizationPlan(cache_key, packets, read_items)
1143
1161
 
1144
1162
  # Deep-copy blocks from cached packets so we don't mutate cached state
@@ -1387,15 +1405,18 @@ class Client(ClientMixin):
1387
1405
 
1388
1406
  def get_cpu_state(self) -> str:
1389
1407
  """
1390
- Get CPU state (running/stopped).
1408
+ Get the CPU operating state by reading SZL 0x0424.
1391
1409
 
1392
1410
  Returns:
1393
- CPU state string
1394
- """
1395
- request = self.protocol.build_cpu_state_request()
1396
- response = self._send_receive(request)
1411
+ ``"S7CpuStatusRun"``, ``"S7CpuStatusStop"`` or ``"S7CpuStatusUnknown"``.
1412
+ Startup, HOLD and DEFECT are reported as ``"S7CpuStatusStop"``, as
1413
+ native Snap7 does.
1397
1414
 
1398
- return self.protocol.extract_cpu_state(response)
1415
+ Raises:
1416
+ S7ConnectionError: If the client is not connected.
1417
+ S7ProtocolError: If the PLC refuses SZL 0x0424 or its reply is too short.
1418
+ """
1419
+ return parse_cpu_state_szl(self.read_szl(0x0424, 0))
1399
1420
 
1400
1421
  def get_block_info(self, block_type: Block, db_number: int) -> TS7BlockInfo:
1401
1422
  """
snap7/optimizer.py CHANGED
@@ -14,6 +14,10 @@ from dataclasses import dataclass, field
14
14
 
15
15
  logger = logging.getLogger(__name__)
16
16
 
17
+ # Most address specifications a CPU accepts in one read request. This is the
18
+ # limit native Snap7 enforces as ``MaxVars``.
19
+ MAX_ITEMS_PER_PDU = 20
20
+
17
21
  # Areas that support contiguous-block merging. Counter (0x1C) and Timer
18
22
  # (0x1D) use element-based addressing, not byte-based, so merging them
19
23
  # as contiguous byte ranges would produce incorrect reads.
@@ -206,12 +210,13 @@ def _split_block(block: ReadBlock, max_block_size: int) -> list[ReadBlock]:
206
210
  return sub_blocks
207
211
 
208
212
 
209
- def packetize(blocks: list[ReadBlock], pdu_size: int) -> list[ReadPacket]:
213
+ def packetize(blocks: list[ReadBlock], pdu_size: int, max_items: int = MAX_ITEMS_PER_PDU) -> list[ReadPacket]:
210
214
  """Pack blocks into PDU-sized packets.
211
215
 
212
- Two budgets are enforced per packet:
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/s7protocol.py CHANGED
@@ -1487,12 +1487,16 @@ class S7Protocol:
1487
1487
 
1488
1488
  def build_cpu_state_request(self) -> bytes:
1489
1489
  """
1490
- Build CPU state request.
1490
+ Build the request ``get_cpu_state()`` used to send.
1491
+
1492
+ .. deprecated:: 3.5
1493
+ This is a read request without an address specification, which is
1494
+ not a valid S7 PDU. The clients read SZL 0x0424 instead; see
1495
+ :func:`snap7.szl.parse_cpu_state_szl`. Kept for backwards compatibility.
1491
1496
 
1492
1497
  Returns:
1493
- Complete S7 PDU for CPU state query
1498
+ S7 PDU for the old CPU state query
1494
1499
  """
1495
- # Simple CPU state request - in real S7 this would be a userdata function
1496
1500
  header = struct.pack(
1497
1501
  ">BBHHHH",
1498
1502
  0x32, # Protocol ID
@@ -1503,24 +1507,26 @@ class S7Protocol:
1503
1507
  0x0000, # Data length
1504
1508
  )
1505
1509
 
1506
- # Use a custom function code for CPU state
1507
- parameters = struct.pack(">B", 0x04) # Use READ_AREA function for simplicity
1510
+ parameters = struct.pack(">B", 0x04) # READ_AREA function code, nothing else
1508
1511
 
1509
1512
  return header + parameters
1510
1513
 
1511
1514
  def extract_cpu_state(self, response: Dict[str, Any]) -> str:
1512
1515
  """
1513
- Extract CPU state from response.
1516
+ Return ``"S7CpuStatusRun"`` whatever the response holds.
1517
+
1518
+ .. deprecated:: 3.5
1519
+ This never looked at the response. The clients read SZL 0x0424
1520
+ instead; see :func:`snap7.szl.parse_cpu_state_szl`. Kept for
1521
+ backwards compatibility.
1514
1522
 
1515
1523
  Args:
1516
- response: Parsed S7 response
1524
+ response: Parsed S7 response (ignored)
1517
1525
 
1518
1526
  Returns:
1519
- CPU state string in S7CpuStatus format (e.g., 'S7CpuStatusRun')
1527
+ Always ``"S7CpuStatusRun"``
1520
1528
  """
1521
- # Map internal states to S7 status format for API compatibility with master branch
1522
- # The cpu_statuses dict in type.py uses: {0: "S7CpuStatusUnknown", 4: "S7CpuStatusStop", 8: "S7CpuStatusRun"}
1523
- return "S7CpuStatusRun" # Default state for pure Python server
1529
+ return "S7CpuStatusRun"
1524
1530
 
1525
1531
  def parse_response(self, pdu: bytes) -> Dict[str, Any]:
1526
1532
  """
snap7/server/__init__.py CHANGED
@@ -1021,9 +1021,9 @@ class Server:
1021
1021
  )
1022
1022
  return (area, db_number, start, byte_count)
1023
1023
 
1024
- # Fallback to defaults if parsing failed
1025
- logger.warning("Using default address values - address parsing may have failed")
1026
- return (S7Area.DB, 1, 0, 4)
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)
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