python-snap7 3.5.0__py3-none-any.whl → 3.6.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-snap7
3
- Version: 3.5.0
3
+ Version: 3.6.0
4
4
  Summary: Pure Python S7 communication library for Siemens PLCs
5
5
  Author-email: Gijs Molenaar <gijsmolenaar@gmail.com>
6
6
  License-Expression: MIT
@@ -1,4 +1,4 @@
1
- python_snap7-3.5.0.dist-info/licenses/LICENSE,sha256=PIihE_yP-8gc-ff9ikvQQPOa0biOCZ6Bc-6h3G3xRUQ,1097
1
+ python_snap7-3.6.0.dist-info/licenses/LICENSE,sha256=PIihE_yP-8gc-ff9ikvQQPOa0biOCZ6Bc-6h3G3xRUQ,1097
2
2
  s7/__init__.py,sha256=q6E4rA1BDx36PPkJS55xv7XCxwlaQeEK6HNotFjLeYo,1096
3
3
  snap7/__init__.py,sha256=2NAAE1oaSSd7DqPl0dx7jNXtsM2PRBWRm9X-bkmgC6U,1275
4
4
  snap7/async_client.py,sha256=_cb17lJaXMApfAEOPzH9AZZa7QFE1TkvMLvY6ywNitE,66408
@@ -13,7 +13,7 @@ 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=YK6B2RedZ59kIIYH8fV70eVCz-T694Kl6c4ltcu61FQ,9944
16
- snap7/partner.py,sha256=NdRwithWSj7F8YxfgeDPtpZ4CG81CV-8E7QaDpAZch8,38194
16
+ snap7/partner.py,sha256=NhiYAZ8zN5DpnnsuVigaYCyGBQVRdNJgJcHQi_7HN-4,45698
17
17
  snap7/ppi.py,sha256=p0fVelfUQOT3QH5uuWOjpDxA5IyT3gx5FzCMaYYEuWQ,16070
18
18
  snap7/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
19
19
  snap7/rate_limiter.py,sha256=dnXCOJLWmszo8oskbFM0om0gPC4LHHCOr-Nt22tImeU,4151
@@ -21,14 +21,14 @@ snap7/s7protocol.py,sha256=kSKtJYBcSYLVSSMiVlDwjxZR7x6NyhGsft4oAMso-mg,71107
21
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=hiZ1-5d6PW3-6DX-3bFe62T66ergJjpgkkdxB70bx8I,118701
24
+ snap7/server/__init__.py,sha256=D47Huk07oeDB7YKfUxuf4i3-skXNJYisHTggqvEfv3c,120493
25
25
  snap7/server/__main__.py,sha256=OdOgyMmFThjSe2jSgvlbkquGYnZcBW6wubs2ldhNSOE,1206
26
26
  snap7/util/__init__.py,sha256=d6n2oy7tNYke1ia0TUyWz_ni3l0XN1qvilM5sW0T-Es,1874
27
27
  snap7/util/db.py,sha256=geesYS2oyOuTADOJa2me1p1rqJVzPuLTCfye6JIeav0,27120
28
28
  snap7/util/getters.py,sha256=UjojRLazJECrngor_8BI38R8VMEMdXusC95zqNEErJg,25767
29
29
  snap7/util/setters.py,sha256=InGXodcfGxNvdGQ5Y589aBOFqa-e2hIUqNCk-HqziiE,29335
30
- python_snap7-3.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,,
30
+ python_snap7-3.6.0.dist-info/METADATA,sha256=ooXfoftMoE-6h6_WlvjXk0FMYvlxcdoCTYaH-tIajxQ,4678
31
+ python_snap7-3.6.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
32
+ python_snap7-3.6.0.dist-info/entry_points.txt,sha256=IPZyYr1lKyavXXpAc4xO505afTGwTY8GmNFuy5lsSiM,75
33
+ python_snap7-3.6.0.dist-info/top_level.txt,sha256=PTgDoDG45QNL2XIE9RM7S_ZCdWQjtMMuXNyrI2UdnbU,9
34
+ python_snap7-3.6.0.dist-info/RECORD,,
snap7/partner.py CHANGED
@@ -88,6 +88,10 @@ class Partner:
88
88
  self._protocol = S7Protocol()
89
89
  self.pdu_length = 480
90
90
 
91
+ # Sequence counter
92
+ self.bsend_param_sequence = 1
93
+ self.du_ref_nr = 1
94
+
91
95
  # R-ID for bsend/brecv matching (default 0, can be set by caller)
92
96
  self.r_id: int = 0
93
97
 
@@ -261,19 +265,69 @@ class Partner:
261
265
  self.send_errors += 1
262
266
  raise S7ConnectionError("Not connected")
263
267
 
268
+ if len(self._send_data) > 65534:
269
+ self.send_errors += 1
270
+ raise ValueError("B_send data too long (>65534 bytes)")
271
+
264
272
  start_time = datetime.now()
265
273
 
266
- try:
267
- # Build partner data PDU
268
- pdu = self._build_partner_data_pdu(self._send_data)
274
+ du_ref_nr = self._next_du_ref_nr()
275
+ bsend_length = len(self._send_data)
269
276
 
270
- with self._io_lock:
271
- # Send via ISO connection
272
- self._connection.send_data(pdu)
277
+ fragmented = False
278
+ first_fragment = True
279
+ last_data_unit = False
280
+ curr_pos = 0
281
+ sequence_num = 0
282
+
283
+ # Max payload legnth
284
+ bsend_payload_length = self.pdu_length - 36
285
+ bsend_fragm_payload_length = self.pdu_length - 34
273
286
 
274
- # Wait for acknowledgment
275
- ack_data = self._connection.receive_data()
276
- self._parse_partner_ack(ack_data)
287
+ if bsend_length > bsend_payload_length:
288
+ fragmented = True
289
+
290
+ try:
291
+ with self._io_lock:
292
+ while not last_data_unit:
293
+ # parameters for the PDU
294
+ if first_fragment:
295
+ # the 1. fragment has the length field and 2 bytes less payload bytes
296
+ max_length = bsend_payload_length
297
+ else:
298
+ max_length = bsend_fragm_payload_length
299
+
300
+ if not fragmented:
301
+ last_data_unit = True
302
+ data = self._send_data
303
+ else:
304
+ if curr_pos + max_length >= bsend_length:
305
+ last_data_unit = True
306
+ data = self._send_data[curr_pos:]
307
+ else:
308
+ data = self._send_data[curr_pos : curr_pos + max_length]
309
+ curr_pos += max_length
310
+
311
+ # Build partner data PDU
312
+ pdu, send_pduref = self._build_partner_data_pdu(
313
+ data, sequence_num, du_ref_nr, bsend_length, last_data_unit, first_fragment
314
+ )
315
+ # Send via ISO connection
316
+ self._connection.send_data(pdu)
317
+
318
+ # Wait for acknowledgment
319
+ ack_data = self._connection.receive_data()
320
+ ack_pduref, sequence_num = self._parse_partner_ack(ack_data)
321
+
322
+ if ack_pduref == -1: # try agan
323
+ ack_data = self._connection.receive_data()
324
+ ack_pduref, sequence_num = self._parse_partner_ack(ack_data)
325
+
326
+ if send_pduref != ack_pduref:
327
+ raise S7Error("Send failed: received wrong pdu-referenze-number")
328
+
329
+ if first_fragment:
330
+ first_fragment = False
277
331
 
278
332
  self.bytes_sent += len(self._send_data)
279
333
  self.last_send_time = int((datetime.now() - start_time).total_seconds() * 1000)
@@ -303,24 +357,20 @@ class Partner:
303
357
 
304
358
  try:
305
359
  with self._io_lock:
306
- # Receive partner data
307
- data = self._connection.receive_data()
308
- received, r_id, pdu_ref = self._parse_partner_data_pdu(data)
360
+ received, r_id = self._b_recv_loop(self._connection)
309
361
 
310
- # Send acknowledgment with the same PDU reference
311
- ack = self._build_partner_ack(pdu_ref)
312
- self._connection.send_data(ack)
362
+ bytes_rcv = len(received)
313
363
 
314
- self.bytes_recv += len(received)
315
364
  self.last_recv_time = int((datetime.now() - start_time).total_seconds() * 1000)
316
365
  self._recv_data = received
317
366
  self._recv_r_id = r_id
367
+ self.bytes_recv += bytes_rcv
318
368
 
319
369
  # Call receive callback if set
320
370
  if self._recv_callback:
321
371
  self._recv_callback(received)
322
372
 
323
- logger.debug(f"Received {len(received)} bytes synchronously")
373
+ logger.debug(f"Received {bytes_rcv} bytes synchronously")
324
374
  return 0
325
375
 
326
376
  except socket.timeout:
@@ -333,6 +383,60 @@ class Partner:
333
383
  logger.error(f"Synchronous receive failed: {e}")
334
384
  return -1
335
385
 
386
+ def _b_recv_loop(self, conn: ISOTCPConnection, sock_timeout: Optional[float] = None) -> Tuple[bytes, int]:
387
+ """
388
+ Receives the frames and reassembles fragmented data
389
+
390
+ Args:
391
+ conn: The ISOTCPConnection
392
+ sock_timeout: Socket timeout from the 2nd and subsequent frames
393
+
394
+ Returns:
395
+ data
396
+ r_id
397
+ """
398
+ if not self.connected or conn is None or conn.socket is None:
399
+ raise S7ConnectionError("Not connected")
400
+
401
+ last_segment = False
402
+ fragmented = False
403
+ reassembled = bytearray()
404
+ bsend_lengh = 0
405
+
406
+ while not last_segment:
407
+ data = conn.receive_data()
408
+ received, r_id, pdu_ref, par_seq_num, _, par_last_unit, data_bsend_lengh = self._parse_partner_data_pdu(data)
409
+
410
+ if par_seq_num == 0:
411
+ sequence = self._next_bsend_param_sequence() # set sequence for new fragemneted transmission
412
+ bsend_lengh = data_bsend_lengh
413
+ else:
414
+ sequence = par_seq_num
415
+
416
+ ack = self._build_partner_ack(pdu_ref, sequence)
417
+ conn.send_data(ack)
418
+
419
+ if par_last_unit == 0:
420
+ last_segment = True
421
+ if fragmented:
422
+ reassembled += bytearray(received)
423
+ received = bytes(reassembled)
424
+ if bsend_lengh != len(received):
425
+ raise S7Error("Incorrect bsend-lenght")
426
+ else:
427
+ fragmented = True
428
+ reassembled += bytearray(received)
429
+ if sock_timeout is not None:
430
+ conn.socket.settimeout(sock_timeout) # Set timeout for next segment
431
+
432
+ if len(reassembled) > 65534 or len(received) > 65534:
433
+ raise S7Error("Received s_send data too long (>65534 bytes)")
434
+
435
+ if len(reassembled) > bsend_lengh:
436
+ raise S7Error("Received s_send data too long (>announced length)")
437
+
438
+ return received, r_id
439
+
336
440
  def as_b_send(self) -> int:
337
441
  """
338
442
  Send data asynchronously (non-blocking).
@@ -633,6 +737,20 @@ class Partner:
633
737
  """
634
738
  return self._recv_r_id
635
739
 
740
+ def _next_bsend_param_sequence(self) -> int:
741
+ """Get next sequence number for BSend parameter."""
742
+ self.bsend_param_sequence = (self.bsend_param_sequence + 1) & 0xFF
743
+ if self.bsend_param_sequence == 0: # must not be 0
744
+ self.bsend_param_sequence += 1
745
+ return self.bsend_param_sequence
746
+
747
+ def _next_du_ref_nr(self) -> int:
748
+ """Get next data unit reference number for BSend parameter."""
749
+ self.du_ref_nr = (self.du_ref_nr + 1) & 0xFF
750
+ if self.du_ref_nr == 0: # must not be 0
751
+ self.du_ref_nr += 1
752
+ return self.du_ref_nr
753
+
636
754
  def _connect_to_remote(self) -> None:
637
755
  """Connect to remote partner (active mode).
638
756
 
@@ -758,10 +876,8 @@ class Partner:
758
876
  old_timeout = conn.socket.gettimeout()
759
877
  conn.socket.settimeout(self.recv_timeout)
760
878
  try:
761
- data = conn.receive_data()
762
- received, r_id, pdu_ref = self._parse_partner_data_pdu(data)
763
- ack = self._build_partner_ack(pdu_ref)
764
- conn.send_data(ack)
879
+ received, r_id = self._b_recv_loop(conn, old_timeout)
880
+
765
881
  finally:
766
882
  try:
767
883
  if conn.socket is not None:
@@ -922,7 +1038,16 @@ class Partner:
922
1038
  data.extend(chunk)
923
1039
  return bytes(data)
924
1040
 
925
- def _build_partner_data_pdu(self, data: bytes, r_id: Optional[int] = None) -> bytes:
1041
+ def _build_partner_data_pdu(
1042
+ self,
1043
+ data: bytes,
1044
+ sequence_nr: int,
1045
+ du_ref_nr: int,
1046
+ bsend_length: int,
1047
+ last_data_unit: bool,
1048
+ first_fragment: bool,
1049
+ r_id: Optional[int] = None,
1050
+ ) -> Tuple[bytes, int]:
926
1051
  """Build an S7 USERDATA PDU for partner data push (bsend).
927
1052
 
928
1053
  The PDU uses the standard S7 USERDATA header (10 bytes) followed by
@@ -932,15 +1057,26 @@ class Partner:
932
1057
 
933
1058
  Args:
934
1059
  data: Payload to send.
1060
+ serquence_nr: Sequence number. 0 if not fragemented or 1st fragmented PDU
1061
+ du_ref_nr: Data unit reference number
1062
+ bsend_length: >0 if not fragemented or 1st fragmented PDU
1063
+ last_data_unit: True ist not fragemented or last fragmented PDU
935
1064
  r_id: Request ID for bsend/brecv matching. Falls back to ``self.r_id``.
936
1065
 
937
1066
  Returns:
938
- Complete S7 PDU bytes (without COTP/TPKT framing).
1067
+ Complete S7 PDU bytes (without COTP/TPKT framing) + pdu-ref-nr
939
1068
  """
940
1069
  if r_id is None:
941
1070
  r_id = self.r_id
942
1071
 
943
1072
  sequence = self._protocol._next_sequence()
1073
+ if sequence == 0: # must not be 0
1074
+ sequence = self._protocol._next_sequence()
1075
+
1076
+ if last_data_unit:
1077
+ last_du = 0x00
1078
+ else:
1079
+ last_du = 0x01
944
1080
 
945
1081
  # Parameter section: USERDATA header (12 bytes)
946
1082
  param = struct.pack(
@@ -952,17 +1088,23 @@ class Partner:
952
1088
  0x12, # method: extended parameter
953
1089
  0x46, # type 4 (request) | group 6 (PBC BSEND)
954
1090
  _PUSH_SUBFUNCTION_BSEND,
955
- 0x00, # sequence number (always 0 for PBC)
956
- 0x00, # data unit reference number
957
- 0x00, # last data unit
1091
+ sequence_nr, # sequence number (always 0 for PBC)
1092
+ du_ref_nr, # data unit reference number
1093
+ last_du, # last data unit
958
1094
  0x0000, # error code
959
1095
  )
960
1096
 
961
1097
  # Data section: header + variable spec + R-ID + payload length + payload
962
1098
  # Variable specification: type=0x12, len=0x06, syntax_id=0x13, reserved=0x00
963
1099
  var_spec = struct.pack(">BBBB", 0x12, 0x06, 0x13, 0x00)
964
- # R-ID (4 bytes) + payload length (2 bytes)
965
- var_spec += struct.pack(">IH", r_id, len(data))
1100
+
1101
+ if first_fragment:
1102
+ # R-ID (4 bytes) + payload length (2 bytes)
1103
+ var_spec += struct.pack(">IH", r_id, bsend_length)
1104
+ else:
1105
+ # R-ID (4 bytes)
1106
+ var_spec += struct.pack(">I", r_id)
1107
+
966
1108
  # Data header: return_code=0xFF, transport_size=0x09, length=varspec+data
967
1109
  data_section = struct.pack(">BBH", 0xFF, 0x09, len(var_spec) + len(data)) + var_spec + data
968
1110
 
@@ -977,16 +1119,17 @@ class Partner:
977
1119
  len(data_section),
978
1120
  )
979
1121
 
980
- return header + param + data_section
1122
+ return header + param + data_section, sequence
981
1123
 
982
- def _parse_partner_data_pdu(self, pdu: bytes) -> Tuple[bytes, int, int]:
1124
+ def _parse_partner_data_pdu(self, pdu: bytes) -> Tuple[bytes, int, int, int, int, int, int]:
983
1125
  """Parse an incoming partner data push PDU and extract the payload.
984
1126
 
985
1127
  Returns:
986
- Tuple of (payload, r_id, pdu_ref). *r_id* and *pdu_ref* are
987
- extracted from the variable specification block and the S7
988
- header respectively. If the variable specification is absent
989
- both default to ``0``.
1128
+ Payload, r_id, pdu_ref, par_seq_num, par_duref_num, par_last_unit, data_bsend_lengh
1129
+
1130
+ *r_id* and *pdu_ref* are extracted from the variable
1131
+ specification block and the S7 header respectively.
1132
+ If the variable specification is absent both default to ``0``.
990
1133
  """
991
1134
  if len(pdu) < 6:
992
1135
  raise S7Error("Invalid partner PDU: too short")
@@ -1000,27 +1143,76 @@ class Partner:
1000
1143
  if len(pdu) < 10:
1001
1144
  raise S7Error("USERDATA partner PDU too short")
1002
1145
  _, _, _, pdu_ref, param_len, data_len = struct.unpack(">BBHHHH", pdu[:10])
1003
- data_offset = 10 + param_len
1004
- if data_offset + 4 > len(pdu):
1005
- raise S7Error("Partner data section too short")
1006
- # Skip 4-byte data section header (return_code, transport_size, length)
1007
- payload = pdu[data_offset + 4 : data_offset + 4 + data_len - 4] if data_len > 4 else b""
1008
- # Parse PBC variable specification block if present
1009
- # Format: 12 06 13 00 [R-ID 4 bytes] [length 2 bytes] = 10 bytes
1010
- r_id = 0
1011
- if len(payload) >= 2 and payload[0] == 0x12:
1012
- var_len = payload[1]
1013
- if var_len == 0x06 and len(payload) >= 8:
1014
- syntax_id = payload[2]
1015
- if syntax_id == 0x13:
1016
- (r_id,) = struct.unpack(">I", payload[4:8])
1017
- # skip var spec header (2) + body (var_len) + length field (2)
1018
- payload = payload[2 + var_len + 2 :]
1019
- return payload, r_id, pdu_ref
1146
+
1147
+ if len(pdu) < 10 + param_len + data_len:
1148
+ raise S7Error("USERDATA partner PDU too short")
1149
+
1150
+ param = pdu[10 : 10 + param_len]
1151
+ data = pdu[10 + param_len : 10 + param_len + data_len]
1152
+
1153
+ if len(param) < 5:
1154
+ raise S7Error("USERDATA bsend parameter block too short")
1155
+
1156
+ par_func, par_items, par_var_spec, par_addr_lengh, par_syntax_id = struct.unpack(">BBBBB", param[:5])
1157
+
1158
+ if (
1159
+ par_func == 0x00
1160
+ and par_items == 1
1161
+ and par_var_spec == 0x12
1162
+ and par_addr_lengh == 8
1163
+ and par_syntax_id == 0x12
1164
+ and data_len >= 13
1165
+ ): # BSend
1166
+ # BSend-data
1167
+ if len(param) < 12:
1168
+ raise S7Error("USERDATA bsend parameter block too short")
1169
+
1170
+ if len(data) < 12:
1171
+ raise S7Error("USERDATA bsend data block too short")
1172
+
1173
+ par_func_group, par_subfunc, par_seq_num, par_duref_num, par_last_unit, par_error_code = struct.unpack(
1174
+ ">BBBBBH", param[5:12]
1175
+ )
1176
+
1177
+ _, _, _, data_var_spec, data_var_len, data_syntax_id, _, data_r_id = struct.unpack(">BBHBBBBI", data[:12])
1178
+
1179
+ payload = bytes()
1180
+ r_id = 0
1181
+ data_bsend_lengh = 0
1182
+
1183
+ if (
1184
+ par_func_group == 0x46
1185
+ and par_subfunc == 0x01
1186
+ and par_error_code == 0
1187
+ and data_var_spec == 0x12
1188
+ and data_var_len == 0x06
1189
+ and data_syntax_id == 0x13
1190
+ ):
1191
+ if par_seq_num == 0x00: # not fragmented transmission or first segment of fragmented transmission
1192
+ if len(data) >= 14:
1193
+ data_bsend_lengh = struct.unpack(">H", data[12:14])[0]
1194
+ else:
1195
+ raise S7Error("USERDATA bsend data block too short")
1196
+ r_id = data_r_id
1197
+ # skip data header (6) + body (var_len) + length field (2)
1198
+ payload = data[6 + data_var_len + 2 :]
1199
+
1200
+ else: # next segment of fragmented transmission
1201
+ r_id = data_r_id
1202
+ # skip data header (6) + body (var_len)
1203
+ payload = data[6 + data_var_len :]
1204
+
1205
+ return payload, r_id, pdu_ref, par_seq_num, par_duref_num, par_last_unit, data_bsend_lengh
1206
+
1207
+ else:
1208
+ raise S7Error("Unsupported PDU function group, subfunction or b_send parameter")
1209
+
1210
+ else:
1211
+ raise S7Error("Unknown USERDATA-Type")
1020
1212
  else:
1021
1213
  raise S7Error(f"Unexpected PDU type in partner data: {pdu_type:#04x}")
1022
1214
 
1023
- def _build_partner_ack(self, pdu_ref: int = 0) -> bytes:
1215
+ def _build_partner_ack(self, pdu_ref: int = 0, sequence: int = 0) -> bytes:
1024
1216
  """Build an S7 USERDATA acknowledgment PDU for a received bsend.
1025
1217
 
1026
1218
  The PLC expects the same PDU reference in the ACK as in the
@@ -1028,11 +1220,11 @@ class Partner:
1028
1220
 
1029
1221
  Args:
1030
1222
  pdu_ref: Protocol Data Unit reference echoed from the data PDU.
1223
+ sequence: Sequence number
1031
1224
 
1032
1225
  Returns:
1033
1226
  Complete S7 PDU bytes.
1034
1227
  """
1035
- sequence = self._protocol._next_sequence()
1036
1228
 
1037
1229
  param = struct.pack(
1038
1230
  ">BBBBBBBB",
@@ -1062,11 +1254,15 @@ class Partner:
1062
1254
 
1063
1255
  return header + param + data
1064
1256
 
1065
- def _parse_partner_ack(self, pdu: bytes) -> None:
1257
+ def _parse_partner_ack(self, pdu: bytes) -> Tuple[int, int]:
1066
1258
  """Parse a partner acknowledgment PDU.
1067
1259
 
1068
1260
  Validates that the PDU is a proper S7 USERDATA response for a push
1069
1261
  acknowledgment and checks for error codes.
1262
+
1263
+ Returns:
1264
+ DPU-Ref + sequence number (for fragmented Bsend transfers).
1265
+
1070
1266
  """
1071
1267
  if len(pdu) < 6:
1072
1268
  raise S7Error("Invalid partner ACK: too short")
@@ -1078,19 +1274,28 @@ class Partner:
1078
1274
  if pdu_type != S7PDUType.USERDATA:
1079
1275
  raise S7Error(f"Expected partner ACK (USERDATA), got {pdu_type:#04x}")
1080
1276
 
1277
+ pdu_ref = 0
1081
1278
  # Check for error code in parameter section
1279
+
1280
+ sequence_num = 0
1082
1281
  if len(pdu) >= 10:
1083
- _, _, _, _, param_len, _ = struct.unpack(">BBHHHH", pdu[:10])
1282
+ _, _, _, pdu_ref, param_len, _ = struct.unpack(">BBHHHH", pdu[:10])
1084
1283
  param = pdu[10 : 10 + param_len]
1085
1284
  # Parameter layout: 00 01 12 LL [method tg sf seq ...] [error_code]
1086
1285
  if len(param) >= 4:
1087
1286
  sub_len = param[3]
1088
1287
  if sub_len >= 8 and len(param) >= 12:
1288
+ if param[5] != 0x86: # not a bsend-ack
1289
+ return -1, -1
1290
+ # Sequence number is at offset 7 within param
1291
+ sequence_num = struct.unpack(">B", param[7:8])[0]
1089
1292
  # Error code is at offset 10-11 within param (bytes 6-7 after 12 LL)
1090
1293
  error_code = struct.unpack(">H", param[10:12])[0]
1091
1294
  if error_code != 0:
1092
1295
  raise S7Error(f"Partner ACK error: {error_code:#06x}")
1093
1296
 
1297
+ return pdu_ref, sequence_num
1298
+
1094
1299
  def __enter__(self) -> "Partner":
1095
1300
  """Context manager entry."""
1096
1301
  return self
snap7/server/__init__.py CHANGED
@@ -14,7 +14,7 @@ import time
14
14
  from ctypes import Array, c_char
15
15
  from enum import IntEnum
16
16
  from types import TracebackType
17
- from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
17
+ from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type, Union
18
18
 
19
19
  from ..datatypes import S7Area, S7WordLen
20
20
  from ..error import S7ConnectionError, S7ProtocolError
@@ -37,6 +37,11 @@ EVC_DATA_WRITE = 0x00040000
37
37
 
38
38
  _EVENT_QUEUE_CAPACITY = 1024
39
39
 
40
+ # Item return code "accessing the object not allowed". An S7-1214C V4.2 answers a
41
+ # Write Var to a write-protected DB with it, at item level and without a header
42
+ # error (capture in python-snap7 issue #976).
43
+ _ITEM_ACCESS_NOT_ALLOWED = 0x03
44
+
40
45
 
41
46
  class ServerState(IntEnum):
42
47
  """S7 server states."""
@@ -94,6 +99,7 @@ class Server:
94
99
  # Memory areas
95
100
  self.memory_areas: Dict[Tuple[S7Area, int], bytearray] = {}
96
101
  self.area_locks: Dict[Tuple[S7Area, int], threading.Lock] = {}
102
+ self._read_only_areas: Set[Tuple[S7Area, int]] = set()
97
103
  self._upload_contexts: Dict[Tuple[str, int], Dict[str, Any]] = {}
98
104
  self._download_contexts: Dict[Tuple[str, int], Dict[str, Any]] = {}
99
105
 
@@ -211,7 +217,9 @@ class Server:
211
217
  logger.info("S7 Server stopped")
212
218
  return 0
213
219
 
214
- def register_area(self, area: SrvArea, index: int, userdata: Union[bytearray, "Array[c_char]"]) -> int:
220
+ def register_area(
221
+ self, area: SrvArea, index: int, userdata: Union[bytearray, "Array[c_char]"], *, read_only: bool = False
222
+ ) -> int:
215
223
  """
216
224
  Register a memory area with the server.
217
225
 
@@ -219,6 +227,11 @@ class Server:
219
227
  area: Memory area type
220
228
  index: Area index/number
221
229
  userdata: Initial data for the area (bytearray or ctypes array)
230
+ read_only: Refuse client writes (Write Var) to this area with item
231
+ return code ``0x03``, "accessing the object not allowed", as an
232
+ S7-1200 does for a write-protected DB. Reads still work, and so
233
+ do a block download and changes the server side makes to
234
+ ``userdata``. Registering the area again replaces the flag.
222
235
 
223
236
  Returns:
224
237
  0 on success
@@ -246,8 +259,12 @@ class Server:
246
259
  area_key = (s7_area, index)
247
260
  self.memory_areas[area_key] = data
248
261
  self.area_locks[area_key] = threading.Lock()
262
+ if read_only:
263
+ self._read_only_areas.add(area_key)
264
+ else:
265
+ self._read_only_areas.discard(area_key)
249
266
 
250
- logger.info(f"Registered area {area.name} index {index}, size {len(data)}")
267
+ logger.info(f"Registered area {area.name} index {index}, size {len(data)}{', read-only' if read_only else ''}")
251
268
  return 0
252
269
 
253
270
  def unregister_area(self, area: SrvArea, index: int) -> int:
@@ -278,6 +295,7 @@ class Server:
278
295
  if area_key in self.memory_areas:
279
296
  del self.memory_areas[area_key]
280
297
  del self.area_locks[area_key]
298
+ self._read_only_areas.discard(area_key)
281
299
  logger.info(f"Unregistered area {area.name} index {index}")
282
300
 
283
301
  return 0
@@ -1083,10 +1101,16 @@ class Server:
1083
1101
 
1084
1102
  area, db_number, start, count, write_data = addr_info
1085
1103
 
1086
- # Write data to registered memory area
1087
- success = self._write_to_memory_area(area, db_number, start, write_data)
1088
- if not success:
1089
- return self._build_error_response(request, 0x8404) # Area not found or write error
1104
+ # A read-only area refuses the write at item level, with no header
1105
+ # error, as a real S7-1200 does for a write-protected DB.
1106
+ read_only = (area, db_number) in self._read_only_areas
1107
+ if read_only:
1108
+ logger.warning(f"Write to read-only area {area}#{db_number} refused")
1109
+ else:
1110
+ # Write data to registered memory area
1111
+ success = self._write_to_memory_area(area, db_number, start, write_data)
1112
+ if not success:
1113
+ return self._build_error_response(request, 0x8404) # Area not found or write error
1090
1114
 
1091
1115
  # Build successful response with error bytes
1092
1116
  header = struct.pack(
@@ -1109,6 +1133,9 @@ class Server:
1109
1133
  )
1110
1134
 
1111
1135
  # Data section (write response)
1136
+ if read_only:
1137
+ return header + parameters + bytes((_ITEM_ACCESS_NOT_ALLOWED,))
1138
+
1112
1139
  data_section = b"\xff" # Success return code
1113
1140
 
1114
1141
  self._emit_event(
@@ -1310,8 +1337,10 @@ class Server:
1310
1337
 
1311
1338
  Returns:
1312
1339
  Item return code: ``0xFF`` on success, ``0x0A`` when the area is not
1313
- registered, and ``0x05`` when the range is outside the registered area.
1314
- Nothing is written unless the whole item fits.
1340
+ registered, ``0x03`` when it is read-only, and ``0x05`` when the range
1341
+ is outside the registered area. Nothing is written unless the whole
1342
+ item fits. That read-only is checked before the range is a choice:
1343
+ there is no capture of an out-of-range write to a protected DB.
1315
1344
  """
1316
1345
  try:
1317
1346
  area_key = (area, db_number)
@@ -1320,6 +1349,10 @@ class Server:
1320
1349
  logger.warning(f"Memory area {area}#{db_number} not registered for write")
1321
1350
  return 0x0A
1322
1351
 
1352
+ if area_key in self._read_only_areas:
1353
+ logger.warning(f"Write to read-only area {area}#{db_number} refused")
1354
+ return _ITEM_ACCESS_NOT_ALLOWED
1355
+
1323
1356
  with self.area_locks[area_key]:
1324
1357
  area_data = self.memory_areas[area_key]
1325
1358