-
Notifications
You must be signed in to change notification settings - Fork 7
/
main_mqtt.py
182 lines (152 loc) · 5.06 KB
/
main_mqtt.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
from __future__ import annotations
import argparse
import datetime
import json
import logging
import signal
import sys
import time
import paho.mqtt.client as mqtt
import serial
from han import autodecoder, hdlc
logging.basicConfig(
level=logging.DEBUG,
format="%(levelname)7s: %(message)s",
stream=sys.stderr,
)
LOG = logging.getLogger("")
def _get_arg_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser("read HAN port")
parser.add_argument("-v", dest="verbose", default=False)
parser.add_argument(
"-s", dest="serialport", required=True, help="input serial port"
)
parser.add_argument(
"-sp",
dest="ser_parity",
required=False,
choices=["N", "O", "E"],
help="input serial port parity",
)
parser.add_argument(
"-sb",
dest="ser_baudrate",
type=int,
required=False,
help="input serial port baud rate",
)
parser.add_argument("-mh", dest="mqtthost", default="localhost", help="mqtt host")
parser.add_argument(
"-mp", dest="mqttport", type=int, default=1883, help="mqtt port port"
)
parser.add_argument(
"-t", dest="mqtttopic", default="han", help="mqtt publish topic"
)
parser.add_argument(
"-dumpfile", dest="dumpfile", help="dump received bytes to file"
)
return parser
def _json_converter(o):
if isinstance(o, datetime.datetime):
return o.isoformat()
return None
def _signal_handler(signal_number, stack_frame):
LOG.info(
"%s signal received. Exiting gracefully.", signal.Signals(signal_number).name
)
_close_resources()
exit(0)
def _close_resources() -> None:
if ser is not None and ser.isOpen():
LOG.debug("Close serial port %s", ser.name)
ser.close()
if logfile is not None and logfile:
LOG.debug("Close frame logfile %s", logfile.name)
logfile.close()
if mqtt_client is not None:
LOG.debug("Close MQTT client")
mqtt_client.loop_stop()
def _dump_to_file(dump_data: bytes) -> None:
for b in dump_data:
is_flag = b == b"\x7e"[0]
if is_flag:
logfile.write("\n")
logfile.write(f"{b:02x}")
if is_flag:
logfile.write("\n")
def _hdlc_frame_received(frame: hdlc.HdlcFrame) -> None:
if frame.is_good_ffc and frame.is_expected_length:
LOG.debug("Got frame info content: %s", frame.payload.hex())
decoded_frame = decoder.decode_message_payload(frame.payload)
if decoded_frame:
json_frame = json.dumps(decoded_frame, default=_json_converter)
LOG.debug("Decoded frame: %s", json_frame)
mqtt_client.publish(args.mqtttopic, json_frame)
else:
LOG.error("Could not decode frame: %s", frame.as_bytes.hex())
else:
LOG.warning("Got invalid frame: %s", frame.as_bytes.hex())
if __name__ == "__main__":
args = _get_arg_parser().parse_args()
ser = None
mqtt_client: mqtt.Client | None = None
logfile = None
signal.signal(signal.SIGINT, _signal_handler)
try:
if args.dumpfile:
logfile = open(args.dumpfile, "w+")
decoder = autodecoder.AutoDecoder()
frame_reader = hdlc.HdlcFrameReader(False)
mqtt_client = mqtt.Client()
mqtt_client.enable_logger(LOG)
try:
mqtt_client.connect(args.mqtthost, port=args.mqttport)
except Exception as ex:
LOG.error(
"Could connect to MQTT host %s on port %s: %s",
args.mqtthost,
args.mqttport,
ex,
)
raise
mqtt_client.loop_start()
LOG.info("MQTT client connected to %s on port %s", args.mqtthost, args.mqttport)
ser = serial.Serial()
ser.port = args.serialport
if args.ser_parity:
ser.parity = args.ser_parity
if args.ser_baudrate:
ser.baudrate = args.ser_baudrate
ser.timeout = 0.5
try:
ser.open()
except serial.SerialException as ex:
LOG.error("Could not open serial: %s", ex.strerror)
raise
LOG.info(
"Serial port %s opened with baudrate %s and parity %s",
ser.name,
ser.baudrate,
ser.parity,
)
while True:
try:
if not ser.isOpen():
ser.open()
read_len = ser.in_waiting if ser.in_waiting > 0 else 1
data = ser.read(read_len)
except serial.SerialException as ex:
LOG.error("Trouble reading from serial port: %s", ex)
data = []
ser.close()
time.sleep(2)
if len(data) > 0:
if args.dumpfile:
_dump_to_file(data)
frames = frame_reader.read(data)
if len(frames):
for f in frames:
_hdlc_frame_received(f)
except Exception as ex:
LOG.error("Exception: %s", ex)
_close_resources()