-
Notifications
You must be signed in to change notification settings - Fork 0
/
tcpSlave100.py
93 lines (75 loc) · 2.81 KB
/
tcpSlave100.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
# -*- coding: utf_8 -*-
import sys
import modbus_tk
import modbus_tk.defines as cst
from modbus_tk import modbus_tcp
from time import sleep
def shift(l, n):
return l[n:] + l[:n]
def main():
"""main"""
logger = modbus_tk.utils.create_logger(name="console", record_format="%(message)s")
try:
#Create the server
server = modbus_tcp.TcpServer()
logger.info("running...")
logger.info("enter 'quit' for closing the server")
server.start()
slave_1 = server.add_slave(1)
slave_1.add_block('1', cst.HOLDING_REGISTERS, 100, 100)
slave_id = 1
name = '1'
address = 100
values = range(10)
slave = server.get_slave(slave_id)
l = len(values)
while 1:
slave.set_values(name, address, values)
values = slave.get_values(name, address, l)
#sys.stdout.write('done: values written: %s\r\n' % str(values))
values = shift(values,1)
sleep(1.0)
while True:
cmd = sys.stdin.readline()
args = cmd.split(' ')
if cmd.find('quit') == 0:
sys.stdout.write('bye-bye\r\n')
break
elif args[0] == 'add_slave':
slave_id = int(args[1])
server.add_slave(slave_id)
sys.stdout.write('done: slave %d added\r\n' % slave_id)
elif args[0] == 'add_block':
slave_id = int(args[1])
name = args[2]
block_type = int(args[3])
starting_address = int(args[4])
length = int(args[5])
slave = server.get_slave(slave_id)
slave.add_block(name, block_type, starting_address, length)
sys.stdout.write('done: block %s added\r\n' % name)
elif args[0] == 'set_values':
slave_id = int(args[1])
name = args[2]
address = int(args[3])
values = []
for val in args[4:]:
values.append(int(val))
slave = server.get_slave(slave_id)
slave.set_values(name, address, values)
values = slave.get_values(name, address, len(values))
sys.stdout.write('done: values written: %s\r\n' % str(values))
elif args[0] == 'get_values':
slave_id = int(args[1])
name = args[2]
address = int(args[3])
length = int(args[4])
slave = server.get_slave(slave_id)
values = slave.get_values(name, address, length)
sys.stdout.write('done: values read: %s\r\n' % str(values))
else:
sys.stdout.write("unknown command %s\r\n" % args[0])
finally:
server.stop()
if __name__ == "__main__":
main()