-
Notifications
You must be signed in to change notification settings - Fork 883
/
message_parser.py
executable file
·170 lines (145 loc) · 5.06 KB
/
message_parser.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
#!/usr/bin/env python3
"""Modbus Message Parser.
The following is an example of how to parse modbus messages
using the supplied framers.
"""
import argparse
import codecs as c
import collections
import logging
import textwrap
from pymodbus.factory import ClientDecoder, ServerDecoder
from pymodbus.transaction import (
ModbusAsciiFramer,
ModbusBinaryFramer,
ModbusRtuFramer,
ModbusSocketFramer,
)
_logger = logging.getLogger(__file__)
def get_commandline(cmdline):
"""Parse the command line options."""
parser = argparse.ArgumentParser()
parser.add_argument(
"--framer",
choices=["ascii", "binary", "rtu", "socket"],
help="set framer, default is rtu",
type=str,
default="rtu",
dest="framer",
)
parser.add_argument(
"-l",
"--log",
choices=["critical", "error", "warning", "info", "debug"],
help="set log level, default is info",
default="info",
type=str,
dest="log",
)
parser.add_argument(
"-m",
"--message",
help="The message to parse",
type=str,
default=None,
dest="message",
)
return parser.parse_args(cmdline)
class Decoder:
"""Decoder.
build custom wrapper around the framers
"""
def __init__(self, framer, encode=False):
"""Initialize a new instance of the decoder."""
self.framer = framer
self.encode = encode
def decode(self, message):
"""Attempt to decode the supplied message."""
value = message if self.encode else c.encode(message, "hex_codec")
print("=" * 80)
print(f"Decoding Message {value}")
print("=" * 80)
decoders = [
self.framer(ServerDecoder(), client=None),
self.framer(ClientDecoder(), client=None),
]
for decoder in decoders:
print(f"{decoder.decoder.__class__.__name__}")
print("-" * 80)
try:
decoder.addToFrame(message)
if decoder.checkFrame(): # pragma no cover
slave = decoder._header.get( # pylint: disable=protected-access
"uid", 0x00
)
decoder.advanceFrame()
decoder.processIncomingPacket(message, self.report, slave)
else: # pragma no cover
self.check_errors(decoder, message)
except Exception: # pylint: disable=broad-except
self.check_errors(decoder, message)
def check_errors(self, decoder, message):
"""Attempt to find message errors."""
txt = f"Unable to parse message - {message} with {decoder}"
_logger.error(txt)
def report(self, message): # pragma no cover
"""Print the message information."""
print(
"%-15s = %s" # pylint: disable=consider-using-f-string
% (
"name",
message.__class__.__name__,
)
)
for k_dict, v_dict in message.__dict__.items():
if isinstance(v_dict, dict):
print("%-15s =" % k_dict) # pylint: disable=consider-using-f-string
for k_item, v_item in v_dict.items():
print(
" %-12s => %s" # pylint: disable=consider-using-f-string
% (k_item, v_item)
)
elif isinstance(v_dict, collections.abc.Iterable):
print("%-15s =" % k_dict) # pylint: disable=consider-using-f-string
value = str([int(x) for x in v_dict])
for line in textwrap.wrap(value, 60):
print(
"%-15s . %s" # pylint: disable=consider-using-f-string
% ("", line)
)
else:
print(
"%-15s = %s" # pylint: disable=consider-using-f-string
% (k_dict, hex(v_dict))
)
print(
"%-15s = %s" # pylint: disable=consider-using-f-string
% (
"documentation",
message.__doc__,
)
)
# -------------------------------------------------------------------------- #
# and decode our message
# -------------------------------------------------------------------------- #
def parse_messages(cmdline=None):
"""Do a helper method to generate the messages to parse."""
args = get_commandline(cmdline=cmdline)
_logger.setLevel(args.log.upper())
if not args.message: # pragma no cover
_logger.error("Missing --message.")
return
framer = {
"ascii": ModbusAsciiFramer,
"binary": ModbusBinaryFramer,
"rtu": ModbusRtuFramer,
"socket": ModbusSocketFramer,
}[args.framer]
decoder = Decoder(framer)
raw_message = c.decode(args.message.encode(), "hex_codec")
decoder.decode(raw_message)
def main(cmdline=None):
"""Run program."""
parse_messages(cmdline=cmdline)
if __name__ == "__main__":
main() # pragma: no cover