-
Notifications
You must be signed in to change notification settings - Fork 91
/
testserver.py
647 lines (486 loc) · 21.7 KB
/
testserver.py
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
"""
Extended ADS TCP/IP server implementation to allow for functional testing of
the ADS protocol without connection to a physical device.
Consists of a server thread which will listen for connections and delegate
each new connection to a separate client thread, allowing for multiple clients
to connect at once.
Each client connection thread listens for incoming data, and delegates parsing
and response construction to the handler. A handler function is injectable at
server level by specifying the `handler` kwarg in the server constructor.
Author: David Browne <davidabrowne@gmail.com>
"""
from __future__ import absolute_import
import atexit
import logging
import select
import socket
import struct
import threading
from collections import namedtuple, defaultdict
from pyads import constants
# Log to stdout by default
logger = logging.getLogger(__name__)
formatter = logging.Formatter("%(levelname)s:%(message)s")
stdout_handler = logging.StreamHandler()
stdout_handler.setLevel(logging.DEBUG)
stdout_handler.setFormatter(formatter)
logger.addHandler(stdout_handler)
logger.setLevel(logging.DEBUG)
logger.propagate = False # "Overwrite" default handler
null_logger = logging.getLogger(__name__ + '_null')
null_logger.addHandler(logging.NullHandler())
ADS_PORT = 0xBF02
# Container for data in the 'AMS/TCP header' component of an AMS packet
AmsTcpHeader = namedtuple('AmsTcpHeader', ('length', ))
# Container for data in the 'AMS header' component of an AMS packet
AmsHeader = namedtuple(
'AmsHeader', (
'target_net_id', 'target_port', 'source_net_id', 'source_port',
'command_id', 'state_flags', 'length', 'error_code', 'invoke_id',
'data'
)
)
# Container for the entire AMS/TCP packet
AmsPacket = namedtuple('AmsPacket', ('tcp_header', 'ams_header'))
# Container for the data required to construct an AMS response given a request
AmsResponseData = namedtuple(
'AmsResponseData', ('state_flags', 'error_code', 'data')
)
class AdsTestServer(threading.Thread):
"""
:summary: Simple ADS testing server
:ivar function handler: Request handler (see `default_handler` for example)
:ivar str ip_address: Host address for server. Defaults to ''
:ivar int port: Host port to listen on, defaults to 48898
"""
def __init__(self, handler=None, ip_address='', port=ADS_PORT,
logging=True, *args, **kwargs):
self.handler = handler or BasicHandler()
self.ip_address = ip_address
self.port = port
self._run = True
global logger
logger = logger if logging else null_logger
# Keep track of all received AMS packets
self.request_history = []
# Initialize TCP/IP socket server
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Set option to allow instant socket reuse after shutdown
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.server.bind((self.ip_address, self.port))
# Make sure we clean up on exit
atexit.register(self.close)
# Daemonize the server thread
# Container for client connection threads
self.clients = []
super(AdsTestServer, self).__init__(*args, **kwargs)
self.daemon = True
def __enter__(self):
self.start()
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def stop(self):
"""
:summary: Close client connections and stop main server loop.
"""
# Close all client connections
for client in self.clients:
client.close()
self.clients = []
if self._run:
logger.info('Stopping server thread.')
# Stop server loop execution
self._run = False
self.server.close()
def close(self):
self.stop()
def run(self):
"""
:summary: Listen for incoming connections from clients.
"""
self._run = True
# Start server listening
self.server.listen(5)
logger.info('Server listening on {0}:{1}'.format(
self.ip_address or 'localhost', self.port
))
# Server loop
while self._run:
# Check for new connections at server socket
ready, _, _ = select.select([self.server], [], [], 0.1)
if ready:
# Accept connection from client
try:
client, address = self.server.accept()
except:
continue
logger.info('New connection from {0}:{1}'.format(*address))
# Delegate handling of connection to client thread
client_thread = AdsClientConnection(
handler=self.handler,
client=client,
address=address,
server=self,
)
client_thread.daemon = True
client_thread.start()
self.clients.append(client_thread)
class AdsClientConnection(threading.Thread):
def __init__(self, handler, client, address, server, *args, **kwargs):
self.handler = handler
self.server = server
self.client = client
self.client_address = address
# Make sure we clean up on exit
atexit.register(self.close)
# Server loop execution flag
self._run = True
super(AdsClientConnection, self).__init__(*args, **kwargs)
def stop(self):
if self._run:
logger.info(
'Closing client connection {0}:{1}.'
.format(*self.client_address)
)
self._run = False
self.join()
def close(self):
if self.is_alive():
self.stop()
self.client.close()
def run(self):
"""
:summary: Listen for data on client connection and delegate requests.
"""
self._run = True
# Main listening loop
while self._run:
ready, _, _ = select.select([self.client], [], [], 0.1)
if not ready:
continue
data, _ = self.client.recvfrom(4096)
if not data:
self.client.close()
self._run = False
continue
# Basic data validation
if len(data) < 38:
logger.warning(
'Malformed packet discarded from {0}:{1}:\n\t{data}'
.format(*self.client_address, data=data)
)
continue
# Construct AmsPacket tuple containing request data
request_packet = self.construct_request(data)
self.server.request_history.append(request_packet)
# Delegate request handling and get response data
response = self.handler.handle_request(request_packet)
if isinstance(response, (AmsResponseData, )):
# Convert request, response data (tuples) to a valid ADS
# response (bytes) to return to the client
response_bytes = self.construct_response(
response, request_packet
)
self.client.send(response_bytes)
continue
logger.error('Request handler failed to return a valid response.')
def construct_response(self, response_data, request):
"""
:summary: Construct binary AMS response to return to the client.
:param AmsResponseData response_data: Data to include in the response
:param AmsPacket request: The originating request for the response
"""
# Response gets returned to the source, so flip source and target
target_net_id = request.ams_header.source_net_id
target_port = request.ams_header.source_port
source_net_id = request.ams_header.target_net_id
source_port = request.ams_header.target_port
# Command ID and invoke ID should be same as in the request
command_id = request.ams_header.command_id
invoke_id = request.ams_header.invoke_id
# Use state flags as specified in response data
state_flags = response_data.state_flags
# Calculate payload length and unpack to binary data
ams_length = struct.pack('<I', len(response_data.data))
# Use error code specified in response data
error_code = response_data.error_code
data = response_data.data
# Below we [ab]use `encode` to get a py2/3 compatible binary object
# (str in py2, or bytes in py3)
# Concatenate ams header data into single binary object
ams_header = ''.encode('utf-8').join((
target_net_id, target_port, source_net_id, source_port,
command_id, state_flags, ams_length, error_code, invoke_id, data
))
ams_tcp_header = (
'\x00\x00'.encode('utf-8') + struct.pack('<I', len(ams_header))
)
return ams_tcp_header + ams_header
def construct_request(self, request_bytes):
"""
:summary: Unpack an AMS packet from binary data.
:param bytes request_bytes: The raw request data
:rtype AmsPacket:
:return: AmsPacket with fields populated from the binary data
"""
data = request_bytes # Use a shorter name for brevity
tcp_header = AmsTcpHeader(data[2:6])
ams_header = AmsHeader(
# Extract target/source net ID's and ports
data[6:12], data[12:14], data[14:20], data[20:22],
# Extract command ID, state flags, and data length
data[22:24], data[24:26], data[26:30],
# Extract error code, invoke ID, and data
data[30:34], data[34:38], data[38:]
)
return AmsPacket(tcp_header, ams_header)
class AbstractHandler:
"""
Abstract Handler class to provide a base class for handling requests.
"""
def handle_request(self, request):
"""
:param AmsPacket request: The request data received from the client
:rtype: AmsResponseData
:return: Data needed to construct the AMS response packet
"""
raise not NotImplementedError()
class BasicHandler(AbstractHandler):
"""
:summary: Basic request handler to print the request data and
return some default values.
"""
def handle_request(self, request):
# Extract command id from the request
command_id_bytes = request.ams_header.command_id
command_id = struct.unpack('<H', command_id_bytes)[0]
# Set AMS state correctly for response
state = struct.unpack('<H', request.ams_header.state_flags)[0]
state = state | 0x0001 # Set response flag
state = struct.pack('<H', state)
# Handle request
if command_id == constants.ADSCOMMAND_READDEVICEINFO:
logger.info('Command received: READ_DEVICE_INFO')
# Create dummy response: version 1.2.3, device name 'TestServer'
major_version = '\x01'.encode('utf-8')
minor_version = '\x02'.encode('utf-8')
version_build = '\x03\x00'.encode('utf-8')
device_name = 'TestServer\x00'.encode('utf-8')
response_content = major_version + minor_version + version_build + device_name
elif command_id == constants.ADSCOMMAND_READ:
logger.info('Command received: READ')
# Parse requested data length
response_length = struct.unpack('<I', request.ams_header.data[8:12])[0]
# Create response of repeated 0x0F with a null terminator for strings
response_value = (('\x0F' * (response_length - 1)) + '\x00').encode('utf-8')
response_content = struct.pack('<I', len(response_value)) + response_value
elif command_id == constants.ADSCOMMAND_WRITE:
logger.info('Command received: WRITE')
# No response data required
response_content = ''.encode('utf-8')
elif command_id == constants.ADSCOMMAND_READSTATE:
logger.info('Command received: READ_STATE')
ads_state = struct.pack('<I', constants.ADSSTATE_RUN)
# I don't know what an appropriate value for device state is.
# I suspect it may be unsued..
device_state = struct.pack('<I', 0)
response_content = ads_state + device_state
elif command_id == constants.ADSCOMMAND_WRITECTRL:
logger.info('Command received: WRITE_CONTROL')
# No response data required
response_content = ''.encode('utf-8')
elif command_id == constants.ADSCOMMAND_ADDDEVICENOTE:
logger.info('Command received: ADD_DEVICE_NOTIFICATION')
handle = ('\x0F' * 4).encode('utf-8')
response_content = handle
elif command_id == constants.ADSCOMMAND_DELDEVICENOTE:
logger.info('Command received: DELETE_DEVICE_NOTIFICATION')
# No response data required
response_content = ''.encode('utf-8')
elif command_id == constants.ADSCOMMAND_DEVICENOTE:
logger.info('Command received: DEVICE_NOTIFICATION')
# No response data required
response_content = ''.encode('utf-8')
elif command_id == constants.ADSCOMMAND_READWRITE:
logger.info('Command received: READ_WRITE')
# Parse requested data length
response_length = struct.unpack('<I', request.ams_header.data[8:12])[0]
# Create response of repeated 0x0F with a null terminator for strings
response_value = (('\x0F' * (response_length - 1)) + '\x00').encode('utf-8')
response_content = struct.pack('<I', len(response_value)) + response_value
else:
logger.info('Unknown Command: {0}'.format(hex(command_id)))
# Set error code to 'unknown command ID'
error_code = '\x08\x00\x00\x00'.encode('utf-8')
return AmsResponseData(state, error_code, ''.encode('utf-8'))
# Set no error in response
error_code = ('\x00' * 4).encode('utf-8')
response_data = error_code + response_content
return AmsResponseData(state, request.ams_header.error_code,
response_data)
class PLCVariable:
""" Storage item for named data """
def __init__(self, name, value):
self.name = name
self.value = value
class AdvancedHandler(AbstractHandler):
"""
The advanced handler allows to store and restore data via read, write and
read_write functions. There are two separate storage areas access by
address and access by name. The purpose of this handler to test read/write
access and test basic interaction.
"""
def __init__(self):
self._data = defaultdict(lambda: bytes(16))
self._named_data = []
def handle_request(self, request):
# Extract command id from the request
command_id_bytes = request.ams_header.command_id
command_id = struct.unpack('<H', command_id_bytes)[0]
# Set AMS state correctly for response
state = struct.unpack('<H', request.ams_header.state_flags)[0]
state = state | 0x0001 # Set response flag
state = struct.pack('<H', state)
def handle_read_device_info():
"""
Create dummy response: version 1.2.3, device name 'TestServer'
"""
logger.info('Command received: READ_DEVICE_INFO')
major_version = '\x01'.encode('utf-8')
minor_version = '\x02'.encode('utf-8')
version_build = '\x03\x00'.encode('utf-8')
device_name = 'TestServer\x00'.encode('utf-8')
response_content = (major_version + minor_version +
version_build + device_name)
return response_content
def handle_read():
data = request.ads_data
index_group = struct.unpack('<I', data[:4])[0]
index_offset = struct.unpack('<I', data[4:8])[0]
plc_datatype = struct.unpack('<I', data[8:12])[0]
logger.info(
('Command received: READ (index group={}, index offset={}, '
'data length={})').format(index_group, index_offset,
plc_datatype)
)
# value by handle is demanded return from named data store
if index_group == constants.ADSIGRP_SYM_VALBYHND:
response_value = self._named_data[index_offset].value
else:
# Create response of repeated 0x0F with a null
# terminator for strings
response_value = (
self._data[(index_group, index_offset)][:plc_datatype]
)
return (struct.pack('<I', len(response_value)) +
response_value)
def handle_write():
data = request.ams_header.data
index_group = struct.unpack('<I', data[:4])[0]
index_offset = struct.unpack('<I', data[4:8])[0]
plc_datatype = struct.unpack('<I', data[8:12])[0]
value = data[12:(12 + plc_datatype)]
logger.info(
('Command received: WRITE (index group={}, index offset={}, '
'data length={}, value={}')
.format(index_group, index_offset, plc_datatype, value)
)
if index_group == constants.ADSIGRP_SYM_RELEASEHND:
return b''
elif index_group == constants.ADSIGRP_SYM_VALBYHND:
self._named_data[index_offset].value = value
return b''
self._data[(index_group, index_offset)] = value
# no return value needed
return b''
def handle_read_write():
data = request.ams_header.data
# parse the request
index_group = struct.unpack('<I', data[:4])[0]
index_offset = struct.unpack('<I', data[4:8])[0]
read_length = struct.unpack('<I', data[8:12])[0]
write_length = struct.unpack('<I', data[12:16])[0]
write_data = data[16:(16 + write_length)]
logger.info(
('Command received: READWRITE '
'(index group={}, index offset={}, read length={}, '
'write length={}, write data={})')
.format(index_group, index_offset, read_length, write_length,
write_data)
)
# Get variable handle by name if demanded
# else just return the value stored
if index_group == constants.ADSIGRP_SYM_HNDBYNAME:
var_name = write_data.decode()
# Try to find var name in named vars
names = [x.name for x in self._named_data]
try:
handle = names.index(var_name)
except ValueError:
self._named_data.append(
PLCVariable(name=var_name, value=bytes(16))
)
handle = len(self._named_data) - 1
read_data = struct.pack('<I', handle)
else:
# read stored data
read_data = self._data[(index_group, index_offset)][:read_length]
# store write data
self._data[(index_group, index_offset)] = write_data
return struct.pack('<I', len(read_data)) + read_data
def handle_read_state():
logger.info('Command received: READ_STATE')
ads_state = struct.pack('<I', constants.ADSSTATE_RUN)
# I don't know what an appropriate value for device state is.
# I suspect it may be unsued..
device_state = struct.pack('<I', 0)
return ads_state + device_state
def handle_writectrl():
logger.info('Command received: WRITE_CONTROL')
# No response data required
return b''
def handle_add_devicenote():
logger.info('Command received: ADD_DEVICE_NOTIFICATION')
handle = ('\x0F' * 4).encode('utf-8')
return handle
def handle_delete_devicenote():
logger.info('Command received: DELETE_DEVICE_NOTIFICATION')
# No response data required
return b''
def handle_devicenote():
logger.info('Command received: DEVICE_NOTIFICATION')
# No response data required
return b''
# Function map
function_map = {
constants.ADSCOMMAND_READDEVICEINFO: handle_read_device_info,
constants.ADSCOMMAND_READ: handle_read,
constants.ADSCOMMAND_WRITE: handle_write,
constants.ADSCOMMAND_READWRITE: handle_read_write,
constants.ADSCOMMAND_READSTATE: handle_read_state,
constants.ADSCOMMAND_WRITECTRL: handle_writectrl,
constants.ADSCOMMAND_ADDDEVICENOTE: handle_add_devicenote,
constants.ADSCOMMAND_DELDEVICENOTE: handle_delete_devicenote,
constants.ADSCOMMAND_DEVICENOTE: handle_devicenote,
}
# Try to map the command id to a function, else return error code
try:
response_content = function_map[command_id]()
except KeyError:
logger.info('Unknown Command: {0}'.format(hex(command_id)))
# Set error code to 'unknown command ID'
error_code = '\x08\x00\x00\x00'.encode('utf-8')
return AmsResponseData(state, error_code, ''.encode('utf-8'))
# Set no error in response
error_code = ('\x00' * 4).encode('utf-8')
response_data = error_code + response_content
return AmsResponseData(state, request.ams_header.error_code,
response_data)
if __name__ == '__main__':
server = AdsTestServer(handler=AdvancedHandler())
try:
server.start()
server.join()
except:
server.close()