-
-
Notifications
You must be signed in to change notification settings - Fork 266
Expand file tree
/
Copy pathclient.py
More file actions
486 lines (384 loc) · 16.2 KB
/
client.py
File metadata and controls
486 lines (384 loc) · 16.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
"""
S7CommPlus client for S7-1200/1500 PLCs.
Provides high-level operations over the S7CommPlus protocol, similar to
the existing snap7.Client but targeting S7-1200/1500 PLCs with full
engineering access (symbolic addressing, optimized data blocks, etc.).
Supports all S7CommPlus protocol versions (V1/V2/V3/TLS). The protocol
version is auto-detected from the PLC's CreateObject response during
connection setup.
When a PLC does not support S7CommPlus data operations (e.g. PLCs that
accept S7CommPlus sessions but return ERROR2 for GetMultiVariables),
the client transparently falls back to the legacy S7 protocol for
data block read/write operations.
Status: V1 and V2 connections are functional. V3/TLS authentication planned.
Reference: thomas-v2/S7CommPlusDriver (C#, LGPL-3.0)
"""
import logging
import struct
from typing import Any, Optional
from .connection import S7CommPlusConnection
from .protocol import FunctionCode, Ids
from .vlq import encode_uint32_vlq, decode_uint32_vlq, decode_uint64_vlq
from .codec import (
encode_item_address,
encode_object_qualifier,
encode_pvalue_blob,
decode_pvalue_to_bytes,
)
logger = logging.getLogger(__name__)
class S7CommPlusClient:
"""S7CommPlus client for S7-1200/1500 PLCs.
Supports all S7CommPlus protocol versions:
- V1: S7-1200 FW V4.0+
- V2: S7-1200/1500 with older firmware
- V3: S7-1200/1500 pre-TIA Portal V17
- V3 + TLS: TIA Portal V17+ (recommended)
The protocol version is auto-detected during connection.
When the PLC does not support S7CommPlus data operations, the client
automatically falls back to legacy S7 protocol for db_read/db_write.
Example::
client = S7CommPlusClient()
client.connect("192.168.1.10")
# Read raw bytes from DB1
data = client.db_read(1, 0, 4)
# Write raw bytes to DB1
client.db_write(1, 0, struct.pack(">f", 23.5))
client.disconnect()
"""
def __init__(self) -> None:
self._connection: Optional[S7CommPlusConnection] = None
self._legacy_client: Optional[Any] = None
self._use_legacy_data: bool = False
self._host: str = ""
self._port: int = 102
self._rack: int = 0
self._slot: int = 1
@property
def connected(self) -> bool:
if self._use_legacy_data and self._legacy_client is not None:
return bool(self._legacy_client.connected)
return self._connection is not None and self._connection.connected
@property
def protocol_version(self) -> int:
"""Protocol version negotiated with the PLC."""
if self._connection is None:
return 0
return self._connection.protocol_version
@property
def session_id(self) -> int:
"""Session ID assigned by the PLC."""
if self._connection is None:
return 0
return self._connection.session_id
@property
def using_legacy_fallback(self) -> bool:
"""Whether the client is using legacy S7 protocol for data operations."""
return self._use_legacy_data
def connect(
self,
host: str,
port: int = 102,
rack: int = 0,
slot: int = 1,
use_tls: bool = False,
tls_cert: Optional[str] = None,
tls_key: Optional[str] = None,
tls_ca: Optional[str] = None,
password: Optional[str] = None,
) -> None:
"""Connect to an S7-1200/1500 PLC using S7CommPlus.
If the PLC does not support S7CommPlus data operations, a secondary
legacy S7 connection is established transparently for data access.
Args:
host: PLC IP address or hostname
port: TCP port (default 102)
rack: PLC rack number
slot: PLC slot number
use_tls: Whether to activate TLS (required for V2)
tls_cert: Path to client TLS certificate (PEM)
tls_key: Path to client private key (PEM)
tls_ca: Path to CA certificate for PLC verification (PEM)
password: PLC password for legitimation (V2+ with TLS)
"""
self._host = host
self._port = port
self._rack = rack
self._slot = slot
self._connection = S7CommPlusConnection(
host=host,
port=port,
)
self._connection.connect(
use_tls=use_tls,
tls_cert=tls_cert,
tls_key=tls_key,
tls_ca=tls_ca,
)
# Handle legitimation for password-protected PLCs
if password is not None and self._connection.tls_active:
logger.info("Performing PLC legitimation (password authentication)")
self._connection.authenticate(password)
# Check if S7CommPlus session setup succeeded. If the PLC accepted the
# ServerSessionVersion echo, data operations should work. If it returned
# an error (e.g. ERROR2), fall back to legacy S7 protocol.
if not self._connection.session_setup_ok:
logger.info("S7CommPlus session setup failed, falling back to legacy S7 protocol")
self._setup_legacy_fallback()
def _setup_legacy_fallback(self) -> None:
"""Establish a secondary legacy S7 connection for data operations."""
from ..client import Client
self._legacy_client = Client()
self._legacy_client.connect(self._host, self._rack, self._slot, self._port)
self._use_legacy_data = True
logger.info(f"Legacy S7 fallback connected to {self._host}:{self._port}")
def disconnect(self) -> None:
"""Disconnect from PLC."""
if self._legacy_client is not None:
try:
self._legacy_client.disconnect()
except Exception:
pass
self._legacy_client = None
self._use_legacy_data = False
if self._connection:
self._connection.disconnect()
self._connection = None
# -- Data block read/write --
def db_read(self, db_number: int, start: int, size: int) -> bytes:
"""Read raw bytes from a data block.
Uses S7CommPlus protocol when supported, otherwise falls back to
legacy S7 protocol transparently.
Args:
db_number: Data block number
start: Start byte offset
size: Number of bytes to read
Returns:
Raw bytes read from the data block
"""
if self._use_legacy_data and self._legacy_client is not None:
return bytes(self._legacy_client.db_read(db_number, start, size))
if self._connection is None:
raise RuntimeError("Not connected")
payload = _build_read_payload([(db_number, start, size)])
logger.debug(f"db_read: db={db_number} start={start} size={size} payload={payload.hex(' ')}")
response = self._connection.send_request(FunctionCode.GET_MULTI_VARIABLES, payload)
logger.debug(f"db_read: response ({len(response)} bytes): {response.hex(' ')}")
results = _parse_read_response(response)
if not results:
raise RuntimeError("Read returned no data")
if results[0] is None:
raise RuntimeError("Read failed: PLC returned error for item")
return results[0]
def db_write(self, db_number: int, start: int, data: bytes) -> None:
"""Write raw bytes to a data block.
Uses S7CommPlus protocol when supported, otherwise falls back to
legacy S7 protocol transparently.
Args:
db_number: Data block number
start: Start byte offset
data: Bytes to write
"""
if self._use_legacy_data and self._legacy_client is not None:
self._legacy_client.db_write(db_number, start, bytearray(data))
return
if self._connection is None:
raise RuntimeError("Not connected")
payload = _build_write_payload([(db_number, start, data)])
logger.debug(
f"db_write: db={db_number} start={start} data_len={len(data)} data={data.hex(' ')} payload={payload.hex(' ')}"
)
response = self._connection.send_request(FunctionCode.SET_MULTI_VARIABLES, payload)
logger.debug(f"db_write: response ({len(response)} bytes): {response.hex(' ')}")
_parse_write_response(response)
def db_read_multi(self, items: list[tuple[int, int, int]]) -> list[bytes]:
"""Read multiple data block regions in a single request.
Uses S7CommPlus protocol when supported, otherwise falls back to
legacy S7 protocol (individual reads) transparently.
Args:
items: List of (db_number, start_offset, size) tuples
Returns:
List of raw bytes for each item
"""
if self._use_legacy_data and self._legacy_client is not None:
results = []
for db_number, start, size in items:
data = self._legacy_client.db_read(db_number, start, size)
results.append(bytes(data))
return results
if self._connection is None:
raise RuntimeError("Not connected")
payload = _build_read_payload(items)
logger.debug(f"db_read_multi: {len(items)} items: {items} payload={payload.hex(' ')}")
response = self._connection.send_request(FunctionCode.GET_MULTI_VARIABLES, payload)
logger.debug(f"db_read_multi: response ({len(response)} bytes): {response.hex(' ')}")
parsed = _parse_read_response(response)
return [r if r is not None else b"" for r in parsed]
# -- Explore (browse PLC object tree) --
def explore(self) -> bytes:
"""Browse the PLC object tree.
Returns the raw Explore response payload for parsing.
Full symbolic exploration will be implemented in a future version.
Returns:
Raw response payload
"""
if self._connection is None:
raise RuntimeError("Not connected")
response = self._connection.send_request(FunctionCode.EXPLORE, b"")
logger.debug(f"explore: response ({len(response)} bytes): {response.hex(' ')}")
return response
# -- Context manager --
def __enter__(self) -> "S7CommPlusClient":
return self
def __exit__(self, *args: Any) -> None:
self.disconnect()
# -- Request/response builders (module-level for reuse by async client) --
def _build_read_payload(items: list[tuple[int, int, int]]) -> bytes:
"""Build a GetMultiVariables request payload.
Args:
items: List of (db_number, start_offset, size) tuples
Returns:
Encoded payload bytes (after the 14-byte request header)
Reference: thomas-v2/S7CommPlusDriver/Core/GetMultiVariablesRequest.cs
"""
# Encode all item addresses and compute total field count
addresses: list[bytes] = []
total_field_count = 0
for db_number, start, size in items:
access_area = Ids.DB_ACCESS_AREA_BASE + (db_number & 0xFFFF)
addr_bytes, field_count = encode_item_address(
access_area=access_area,
access_sub_area=Ids.DB_VALUE_ACTUAL,
lids=[start + 1, size], # LID byte offsets are 1-based in S7CommPlus
)
addresses.append(addr_bytes)
total_field_count += field_count
payload = bytearray()
# LinkId (UInt32 fixed = 0, for reading variables)
payload += struct.pack(">I", 0)
# Item count
payload += encode_uint32_vlq(len(items))
# Total field count across all items
payload += encode_uint32_vlq(total_field_count)
# Item addresses
for addr in addresses:
payload += addr
# ObjectQualifier
payload += encode_object_qualifier()
# Padding
payload += struct.pack(">I", 0)
return bytes(payload)
def _parse_read_response(response: bytes) -> list[Optional[bytes]]:
"""Parse a GetMultiVariables response payload.
Args:
response: Response payload (after the 14-byte response header)
Returns:
List of raw bytes per item (None for errored items)
Reference: thomas-v2/S7CommPlusDriver/Core/GetMultiVariablesResponse.cs
"""
offset = 0
# ReturnValue (UInt64 VLQ)
return_value, consumed = decode_uint64_vlq(response, offset)
offset += consumed
logger.debug(f"_parse_read_response: return_value={return_value}")
if return_value != 0:
logger.error(f"_parse_read_response: PLC returned error: {return_value}")
return []
# Value list: ItemNumber (VLQ) + PValue, terminated by ItemNumber=0
values: dict[int, bytes] = {}
while offset < len(response):
item_nr, consumed = decode_uint32_vlq(response, offset)
offset += consumed
if item_nr == 0:
break
raw_bytes, consumed = decode_pvalue_to_bytes(response, offset)
offset += consumed
values[item_nr] = raw_bytes
# Error list: ErrorItemNumber (VLQ) + ErrorReturnValue (UInt64 VLQ), terminated by 0
errors: dict[int, int] = {}
while offset < len(response):
err_item_nr, consumed = decode_uint32_vlq(response, offset)
offset += consumed
if err_item_nr == 0:
break
err_value, consumed = decode_uint64_vlq(response, offset)
offset += consumed
errors[err_item_nr] = err_value
logger.debug(f"_parse_read_response: error item {err_item_nr}: {err_value}")
# Build result list (1-based item numbers)
max_item = max(max(values.keys(), default=0), max(errors.keys(), default=0))
results: list[Optional[bytes]] = []
for i in range(1, max_item + 1):
if i in values:
results.append(values[i])
else:
results.append(None)
return results
def _build_write_payload(items: list[tuple[int, int, bytes]]) -> bytes:
"""Build a SetMultiVariables request payload.
Args:
items: List of (db_number, start_offset, data) tuples
Returns:
Encoded payload bytes
Reference: thomas-v2/S7CommPlusDriver/Core/SetMultiVariablesRequest.cs
"""
# Encode all item addresses and compute total field count
addresses: list[bytes] = []
total_field_count = 0
for db_number, start, data in items:
access_area = Ids.DB_ACCESS_AREA_BASE + (db_number & 0xFFFF)
addr_bytes, field_count = encode_item_address(
access_area=access_area,
access_sub_area=Ids.DB_VALUE_ACTUAL,
lids=[start + 1, len(data)], # LID byte offsets are 1-based in S7CommPlus
)
addresses.append(addr_bytes)
total_field_count += field_count
payload = bytearray()
# InObjectId (UInt32 fixed = 0, for plain variable writes)
payload += struct.pack(">I", 0)
# Item count
payload += encode_uint32_vlq(len(items))
# Total field count
payload += encode_uint32_vlq(total_field_count)
# Item addresses
for addr in addresses:
payload += addr
# Value list: ItemNumber (1-based) + PValue
for i, (_, _, data) in enumerate(items, 1):
payload += encode_uint32_vlq(i)
payload += encode_pvalue_blob(data)
# Fill byte
payload += bytes([0x00])
# ObjectQualifier
payload += encode_object_qualifier()
# Padding
payload += struct.pack(">I", 0)
return bytes(payload)
def _parse_write_response(response: bytes) -> None:
"""Parse a SetMultiVariables response payload.
Args:
response: Response payload (after the 14-byte response header)
Raises:
RuntimeError: If the write failed
Reference: thomas-v2/S7CommPlusDriver/Core/SetMultiVariablesResponse.cs
"""
offset = 0
# ReturnValue (UInt64 VLQ)
return_value, consumed = decode_uint64_vlq(response, offset)
offset += consumed
logger.debug(f"_parse_write_response: return_value={return_value}")
if return_value != 0:
raise RuntimeError(f"Write failed with return value {return_value}")
# Error list: ErrorItemNumber (VLQ) + ErrorReturnValue (UInt64 VLQ)
errors: list[tuple[int, int]] = []
while offset < len(response):
err_item_nr, consumed = decode_uint32_vlq(response, offset)
offset += consumed
if err_item_nr == 0:
break
err_value, consumed = decode_uint64_vlq(response, offset)
offset += consumed
errors.append((err_item_nr, err_value))
if errors:
err_str = ", ".join(f"item {nr}: error {val}" for nr, val in errors)
raise RuntimeError(f"Write failed: {err_str}")