-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.py
More file actions
388 lines (351 loc) · 11.3 KB
/
main.py
File metadata and controls
388 lines (351 loc) · 11.3 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
"""Pymodbus REPL Entry point."""
import logging
import pathlib
import click
from prompt_toolkit import PromptSession, print_formatted_text
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.formatted_text import HTML
from prompt_toolkit.history import FileHistory
from prompt_toolkit.key_binding import KeyBindings
from prompt_toolkit.lexers import PygmentsLexer
from pygments.lexers.python import PythonLexer
from pymodbus import __version__ as pymodbus_version
from pymodbus.exceptions import ParameterException
from pymodbus.framer import (
FramerAscii,
FramerRTU,
FramerSocket,
)
from pymodbus_repl import __VERSION__ as repl_version
from pymodbus_repl.client.mclient import ModbusSerialClient, ModbusTcpClient
from pymodbus_repl.lib.completer import (
CmdCompleter,
has_selected_completion,
)
from pymodbus_repl.lib.helper import CLIENT_ATTRIBUTES, Result, style
_logger = logging.getLogger()
TITLE = rf"""
----------------------------------------------------------------------------
__________ _____ .___ __________ .__
\______ \___.__. / \ ____ __| _/ \______ \ ____ ______ | |
| ___< | |/ \ / \ / _ \ / __ | | _// __ \\\____ \| |
| | \___ / Y ( <_> ) /_/ | | | \ ___/| |_> > |__
|____| / ____\____|__ /\____/\____ | /\ |____|_ /\___ > __/|____/
\/ \/ \/ \/ \/ \/|__|
v{repl_version} - Pymodbus-{pymodbus_version}
----------------------------------------------------------------------------
"""
def bottom_toolbar():
"""Do console toolbar.
:return:
"""
return HTML(
'Press <b><style bg="ansired">CTRL+D or exit </style></b>'
' to exit! Type "help" for list of available commands'
)
class NumericChoice(click.Choice):
"""Do numeric choice for click arguments and options."""
def __init__(self, choices, typ):
"""Initialize."""
self.typ = typ
super().__init__(choices)
def convert(self, value, param, ctx):
"""Convert."""
# Exact match
if value in self.choices:
return self.typ(value)
self.fail(
f"invalid choice: {value}. (choose from {', '.join(self.choices)})",
param,
ctx,
)
return None
def _process_args(args: list, string: bool = True):
"""Parse arguments provided on command line.
:param args: Array of argument values
:param string: True if arguments values are strings, false if argument values are integers
:return Tuple, where the first member is hash of parsed values, and second is boolean flag
indicating if parsing succeeded.
"""
kwargs = {}
execute = True
skip_index = None
def _parse_val(arg_name, val):
if not string:
if "," in val:
val = val.split(",")
val = [int(v, 0) for v in val]
else:
val = int(val, 0)
kwargs[arg_name] = val
for i, arg in enumerate(args):
if i == skip_index:
continue
arg = arg.strip()
if "=" in arg:
arg_name, val = arg.split("=")
_parse_val(arg_name, val)
else:
arg_name, val = arg, args[i + 1]
try:
_parse_val(arg_name, val)
skip_index = i + 1
except TypeError:
click.secho("Error parsing arguments!", fg="yellow")
execute = False
break
except ValueError:
click.secho("Error parsing argument", fg="yellow")
execute = False
break
return kwargs, execute
class CLI: # pylint: disable=too-few-public-methods
"""Client definition."""
def __init__(self, client):
"""Set up client and keybindings."""
use_keys = KeyBindings()
history_file = pathlib.Path.home().joinpath(".pymodhis")
self.client = client
@use_keys.add("c-space")
def _(event):
"""Initialize autocompletion, or select the next completion."""
buff = event.app.current_buffer
if buff.complete_state:
buff.complete_next()
else:
buff.start_completion(select_first=False)
@use_keys.add("enter", filter=has_selected_completion)
def _(event):
"""Make the enter key work as the tab key only when showing the menu."""
event.current_buffer.complete_state = None
buffer = event.cli.current_buffer
buffer.complete_state = None
self.session = PromptSession(
lexer=PygmentsLexer(PythonLexer),
completer=CmdCompleter(client),
style=style,
complete_while_typing=True,
bottom_toolbar=bottom_toolbar,
key_bindings=use_keys,
history=FileHistory(history_file),
auto_suggest=AutoSuggestFromHistory(),
)
click.secho(TITLE, fg="green")
def _print_command_help(self, commands):
"""Print a list of commands with help text."""
for cmd, obj in sorted(commands.items()):
if cmd != "help":
print_formatted_text(
HTML(
f"<skyblue>{cmd:45s}</skyblue>"
f"<seagreen>{obj.help_text:100s}"
"</seagreen>"
)
)
def _process_client(self, text, client) -> Result:
"""Process client commands."""
text = text.strip().split()
cmd = text[0].split(".")[1]
args = text[1:]
kwargs, execute = _process_args(args, string=False)
if execute:
if text[0] in CLIENT_ATTRIBUTES:
result = Result(getattr(client, cmd))
else:
result = Result(getattr(client, cmd)(**kwargs))
result.print_result()
return result
def _process_result(self, text, result):
"""Process result commands."""
words = text.split()
if words[0] == "result.raw":
result.raw()
if words[0] == "result.decode":
args = words[1:]
kwargs, execute = _process_args(args)
if execute:
result.decode(**kwargs)
def run(self):
"""Run the REPL."""
result = None
while True:
try:
text = self.session.prompt("> ", complete_while_typing=True)
if text.strip().lower() == "help":
print_formatted_text(HTML("<u>Available commands:</u>"))
self._print_command_help(self.session.completer.commands)
elif text.strip().lower() == "exit":
raise EOFError()
elif text.strip().lower().startswith("client."):
result = self._process_client(text, self.client)
elif text.strip().lower().startswith("result.") and result:
self._process_result(text, result)
except KeyboardInterrupt:
continue # Control-C pressed. Try again.
except EOFError:
break # Control-D pressed.
except Exception as exc: # pylint: disable=broad-except
click.secho(str(exc), fg="red")
click.secho("GoodBye!", fg="blue")
@click.group("pymodbus-repl")
@click.version_option(str(pymodbus_version), message=TITLE)
@click.option("--verbose", is_flag=True, default=False, help="Verbose logs")
@click.option("--retries", default=3, help="Retry count")
@click.pass_context
def main(
ctx,
verbose,
retries,
):
"""Run Main."""
if verbose:
use_format = (
"%(asctime)-15s %(threadName)-15s "
"%(levelname)-8s %(module)-15s:%(lineno)-8s %(message)s"
)
logging.basicConfig(format=use_format)
_logger.setLevel(logging.DEBUG)
ctx.obj = {
"retries": retries,
}
@main.command("tcp")
@click.pass_context
@click.option("--host", default="localhost", help="Modbus TCP IP ")
@click.option(
"--port",
default=502,
type=int,
help="Modbus TCP port",
)
@click.option(
"--framer",
default="tcp",
type=str,
help="Override the default packet framer tcp|rtu",
)
def tcp(ctx, host, port, framer):
"""Define TCP."""
kwargs = {"host": host, "port": port}
kwargs.update(**ctx.obj)
if framer == "rtu":
kwargs["framer"] = FramerRTU
client = ModbusTcpClient(**kwargs)
cli = CLI(client)
cli.run()
@main.command("serial")
@click.pass_context
@click.option(
"--method",
default="rtu",
type=str,
help="Modbus Serial Mode (rtu/ascii)",
)
@click.option(
"--port",
default=None,
type=str,
help="Modbus RTU port",
)
@click.option(
"--baudrate",
help="Modbus RTU serial baudrate to use.",
default=9600,
type=int,
)
@click.option(
"--bytesize",
help="Modbus RTU serial Number of data bits. "
"Possible values: FIVEBITS, SIXBITS, SEVENBITS, "
"EIGHTBITS.",
type=NumericChoice(["5", "6", "7", "8"], int),
default="8",
)
@click.option(
"--parity",
help="Modbus RTU serial parity. "
" Enable parity checking. Possible values: "
"PARITY_NONE, PARITY_EVEN, PARITY_ODD PARITY_MARK, "
'PARITY_SPACE. Default to "N"',
default="N",
type=click.Choice(["N", "E", "O", "M", "S"], case_sensitive=False),
)
@click.option(
"--stopbits",
help="Modbus RTU serial stop bits. "
"Number of stop bits. Possible values: STOPBITS_ONE, "
'STOPBITS_ONE_POINT_FIVE, STOPBITS_TWO. Default to "1"',
default="1",
type=NumericChoice(["1", "1.5", "2"], float),
)
@click.option(
"--xonxoff",
help="Modbus RTU serial xonxoff. Enable software flow control.",
default=0,
type=int,
)
@click.option(
"--rtscts",
help="Modbus RTU serial rtscts. Enable hardware (RTS/CTS) flow " "control.",
default=0,
type=int,
)
@click.option(
"--dsrdtr",
help="Modbus RTU serial dsrdtr. Enable hardware (DSR/DTR) flow " "control.",
default=0,
type=int,
)
@click.option(
"--timeout",
help="Modbus RTU serial read timeout.",
default=0.25,
type=float,
)
@click.option(
"--write-timeout",
help="Modbus RTU serial write timeout.",
default=2,
type=float,
)
def serial( # pylint: disable=too-many-arguments
ctx,
method,
port,
baudrate,
bytesize,
parity,
stopbits,
xonxoff,
rtscts,
dsrdtr,
timeout,
write_timeout,
):
"""Define serial communication."""
method = method.lower()
if method == "ascii":
framer = FramerAscii
elif method == "rtu":
framer = FramerRTU
elif method == "socket":
framer = FramerSocket
else:
raise ParameterException("Invalid framer method requested")
client = ModbusSerialClient(
framer=framer,
port=port,
baudrate=baudrate,
bytesize=bytesize,
parity=parity,
stopbits=stopbits,
xonxoff=xonxoff,
rtscts=rtscts,
dsrdtr=dsrdtr,
timeout=timeout,
write_timeout=write_timeout,
**ctx.obj,
)
cli = CLI(client)
cli.run()
if __name__ == "__main__":
main() # pylint: disable=no-value-for-parameter