forked from favalex/modbus-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
access.py
323 lines (251 loc) · 10.6 KB
/
access.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
import struct
from itertools import zip_longest, groupby
import logging
import re
import fnmatch
import umodbus.exceptions
from .definitions import REGISTER_RE
def grouper(iterable, n, fillvalue=None):
'Collect data into fixed-length chunks or blocks'
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
def dump(xs):
return ' '.join('{:02x}'.format(x) for x in xs)
class Access:
def __init__(self, modbus_type, addresses, pack_types, values=None, names=None, presenters=None, byte_order='be', silent=False):
self.modbus_type = modbus_type
self.values_to_write = values or [None] * len(addresses)
self.addresses = addresses
self.pack_types = pack_types
self.names = names or [None] * len(addresses)
self.presenters = presenters or [None] * len(addresses)
self.byte_order = byte_order
self.silent = silent
def address(self):
return self.addresses[0]
def pack_type(self):
return self.pack_types[0]
def presenter(self):
return self.presenters[0]
def endianness(self):
return self.pack_type()[0]
@property
def write(self):
return any(x is not None for x in self.values_to_write)
def size(self):
"""Number of registers"""
total = 0
for p in self.pack_types:
size = struct.calcsize(p)
if self.modbus_type in ('h', 'H', 'i'):
assert size % 2 == 0
size //= 2
total += size
return total
def operations(self):
if self.write:
return zip(self.pack_types, self.values_to_write)
else:
return self.pack_types
def append(self, other):
self.names.extend(other.names)
self.pack_types.extend(other.pack_types)
self.addresses.extend(other.addresses)
self.presenters.extend(other.presenters)
if self.write:
self.values_to_write.extend(other.values_to_write)
def labels(self):
return (name or address for (name, address) in zip(self.names, self.addresses))
def print_values(self, definitions=None):
for label, value, presenter in zip(self.labels(), self.values, self.presenters):
if len(value) == 1:
value = value[0]
if self.silent:
logging.info('{}'.format(value))
else:
logging.info('{}: {} {}'.format(label, value, self.present_value(value, presenter, definitions)))
def present_value(self, value, presenter, definitions):
if type(value) != int:
return ''
presentation = [hex(value)]
if presenter:
if presenter[0] == ':':
presentation.append(definitions.presenters[presenter][value])
elif presenter[0] == '|':
names = []
for bit, name in definitions.presenters[presenter].items():
if value & (1 << bit):
names.append(name)
presentation.append(' | '.join(names))
return ' '.join(presentation)
def perform(self, modbus):
if self.write:
self.write_registers_send(modbus)
self.write_registers_receive(modbus)
else:
self.read_registers_send(modbus)
self.read_registers_receive(modbus)
def read_registers_send(self, modbus):
if self.modbus_type in 'cCd':
n_registers = 0
for pack_type in self.pack_types:
n_registers += struct.calcsize(pack_type)
else:
n_bytes = 0
for pack_type in self.pack_types:
n_bytes += struct.calcsize(pack_type)
assert n_bytes % 2 == 0
n_registers = n_bytes // 2
reader = {
'c': 'read_coils',
'C': 'read_coils',
'd': 'read_discrete_inputs',
'h': 'read_holding_registers',
'H': 'read_holding_registers',
'i': 'read_input_registers',
}[self.modbus_type]
self.request = getattr(modbus.protocol, reader)(modbus.slave_id, self.address(), n_registers)
logging.debug('→ < %s >', dump(self.request))
modbus.send(self.request)
def read_registers_receive(self, modbus):
try:
words = modbus.receive(self.request)
except umodbus.exceptions.IllegalDataAddressError:
self.values = ('Invalid address', )
return
except umodbus.exceptions.IllegalFunctionError:
self.values = ('Invalid modbus type', )
return
logging.debug('← %s', words)
if self.modbus_type in 'cd':
self.values = [(w,) for w in words]
else:
if self.byte_order == 'mixed':
# reinterpret each big endian register as little endian
repack_byte_order = '<'
else:
# just pack it again to the same stream of bytes we read
repack_byte_order = '>'
packed = struct.pack('{}{}H'.format(repack_byte_order, len(words)), *words)
self.values = []
for pack in self.pack_types:
size = struct.calcsize(pack)
self.values.append(struct.unpack(pack, packed[:size]))
packed = packed[size:]
def write_registers_send(self, modbus):
if self.modbus_type == 'c':
if len(self.values_to_write) == 1:
# TODO validate value, should be boolean
message = modbus.protocol.write_single_coil(
modbus.slave_id, self.address(), int(self.values_to_write[0]))
else:
message = modbus.protocol.write_multiple_coils(modbus.slave_id, self.address(),
[int(v) for v in self.values_to_write])
elif self.modbus_type == 'C':
message = modbus.protocol.write_multiple_coils(modbus.slave_id, self.address(),
[int(v) for v in self.values_to_write])
else:
words = []
if self.byte_order == 'mixed':
register_fmt = '<H'
else:
register_fmt = '>H'
for pack_type, value in zip(self.pack_types, self.values_to_write):
n_bytes = struct.calcsize(pack_type)
assert n_bytes % 2 == 0
if 'f' in pack_type or 'd' in pack_type:
value = float(value)
else:
value = int(value, 0)
words.extend([
struct.unpack(register_fmt, bytes(byte_pair))[0]
for byte_pair in grouper(struct.pack(pack_type, value), 2)
])
if self.modbus_type == 'h' and len(words) == 1:
message = modbus.protocol.write_single_register(modbus.slave_id, self.address(), words[0])
else:
message = modbus.protocol.write_multiple_registers(modbus.slave_id, self.address(), words)
logging.debug('→ < %s >', dump(message))
self.request = message
return modbus.send(message)
def write_registers_receive(self, modbus):
modbus.receive(self.request)
def __str__(self):
return '{}@{}/{}{}'.format(self.modbus_type,
self.address(),
self.pack_types,
'={}'.format(self.values_to_write) if self.write else '')
def __repr__(self):
return 'Access({!r}, {!r}, {!r}, {!r}, {!r})'.format(
self.modbus_type, self.addresses, self.pack_types, self.values_to_write, self.names)
def by_type(access):
return access.modbus_type, access.write, access.endianness()
def by_address(access):
return access.address()
def group_accesses(accesses):
grouped = []
for (modbus_type, write, _), xs in groupby(sorted(accesses, key=by_type), key=by_type):
xs = sorted(xs, key=by_address)
while len(xs):
first = xs.pop(0)
while len(xs):
second = xs[0]
if first.address() + first.size() == second.address():
first.append(second)
xs.pop(0)
else:
break
grouped.append(first)
return grouped
def parse_access(register, name, write, value, byte_order, silent):
modbus_type, address, pack_type, presenter = re.match(REGISTER_RE, register).groups()
if not address:
logging.warn('%r is not a known named register nor a valid register definition. Skipping it.', register)
return None
if not modbus_type:
modbus_type = 'h'
else:
modbus_type = modbus_type[:-1]
if not pack_type:
if modbus_type in 'cCd':
pack_type = 'B'
else:
pack_type = 'H'
else:
pack_type = pack_type[1:]
address = int(address)
if pack_type[0] not in '@=<>!':
if byte_order in ('le', 'mixed'):
pack_type = '<' + pack_type
elif byte_order == 'be':
pack_type = '!' + pack_type
if modbus_type not in 'cCdhHi':
raise ValueError("Invalid Modbus type '{}'. Valid ones are 'cCdhHi'".format(modbus_type))
if write and modbus_type not in 'cChH':
raise ValueError("Invalid Modbus type '{}'. Only coils and holding registers are writable".format(modbus_type))
return Access(modbus_type, [address], [pack_type], [value],
names=[name], presenters=[presenter], byte_order=byte_order, silent=silent)
def parse_accesses(s, definitions, byte_order='be', silent=False):
accesses = []
for access in s:
parts = access.split('=')
if len(parts) == 1:
register = parts[0]
value = None
write = False
else:
register, value = parts
write = True
if re.fullmatch(REGISTER_RE, register):
access = parse_access(register, None, write, value, byte_order, silent)
if access:
accesses.append(access)
else:
register_re = re.compile(fnmatch.translate(register))
for name, definition in definitions.registers.items():
if register_re.match(name):
access = parse_access(definition, name, write, value, byte_order, silent)
if access:
accesses.append(access)
return group_accesses(accesses)