-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmqtt-republisher.py
executable file
·238 lines (197 loc) · 6.96 KB
/
mqtt-republisher.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
#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
__author__ = "Kyle Gordon"
__copyright__ = "Copyright (C) Kyle Gordon"
import os
import csv
import logging
import signal
import time
import socket
import sys
import mosquitto
import ConfigParser
import setproctitle
# Read the config file
config = ConfigParser.RawConfigParser()
config.read("/etc/mqtt-republisher/mqtt-republisher.cfg")
#Use ConfigParser to pick out the settings
DEBUG = config.getboolean("global", "debug")
LOGFILE = config.get("global", "logfile")
MAPFILE = config.get("global", "mapfile")
MQTT_HOST = config.get("global", "mqtt_host")
MQTT_PORT = config.getint("global", "mqtt_port")
MQTT_TOPIC = config.get("global", "mqtt_topic")
APPNAME = "mqtt-republisher"
PRESENCETOPIC = "clients/" + socket.getfqdn() + "/" + APPNAME + "/state"
setproctitle.setproctitle(APPNAME)
client_id = APPNAME + "_%d" % os.getpid()
mqttc = mosquitto.Mosquitto(client_id)
LOGFORMAT = '%(asctime)-15s %(message)s'
if DEBUG:
logging.basicConfig(filename=LOGFILE,
level=logging.DEBUG,
format=LOGFORMAT)
else:
logging.basicConfig(filename=LOGFILE,
level=logging.INFO,
format=LOGFORMAT)
logging.info("Starting " + APPNAME)
logging.info("INFO MODE")
logging.debug("DEBUG MODE")
# All the MQTT callbacks start here
def on_publish(mosq, obj, mid):
"""
What to do when a message is published
"""
logging.debug("MID " + str(mid) + " published.")
def on_subscribe(mosq, obj, mid, qos_list):
"""
What to do in the event of subscribing to a topic"
"""
logging.debug("Subscribe with mid " + str(mid) + " received.")
def on_unsubscribe(mosq, obj, mid):
"""
What to do in the event of unsubscribing from a topic
"""
logging.debug("Unsubscribe with mid " + str(mid) + " received.")
def on_connect(mosq, obj, result_code):
"""
Handle connections (or failures) to the broker.
This is called after the client has received a CONNACK message
from the broker in response to calling connect().
The parameter rc is an integer giving the return code:
0: Success
1: Refused – unacceptable protocol version
2: Refused – identifier rejected
3: Refused – server unavailable
4: Refused – bad user name or password (MQTT v3.1 broker only)
5: Refused – not authorised (MQTT v3.1 broker only)
"""
logging.debug("on_connect RC: " + str(result_code))
if result_code == 0:
logging.info("Connected to %s:%s", MQTT_HOST, MQTT_PORT)
# Publish retained LWT as per
# http://stackoverflow.com/q/97694
# See also the will_set function in connect() below
mqttc.publish(PRESENCETOPIC, "1", retain=True)
process_connection()
elif result_code == 1:
logging.info("Connection refused - unacceptable protocol version")
cleanup()
elif result_code == 2:
logging.info("Connection refused - identifier rejected")
cleanup()
elif result_code == 3:
logging.info("Connection refused - server unavailable")
logging.info("Retrying in 30 seconds")
time.sleep(30)
elif result_code == 4:
logging.info("Connection refused - bad user name or password")
cleanup()
elif result_code == 5:
logging.info("Connection refused - not authorised")
cleanup()
else:
logging.warning("Something went wrong. RC:" + str(result_code))
cleanup()
def on_disconnect(mosq, obj, result_code):
"""
Handle disconnections from the broker
"""
if result_code == 0:
logging.info("Clean disconnection")
else:
logging.info("Unexpected disconnection! Reconnecting in 5 seconds")
logging.debug("Result code: %s", result_code)
time.sleep(5)
def on_message(mosq, obj, msg):
"""
What to do when the client recieves a message from the broker
"""
logging.debug("Received: " + msg.payload +
" received on topic " + msg.topic +
" with QoS " + str(msg.qos))
process_message(msg)
def on_log(mosq, obj, level, string):
"""
What to do with debug log output from the MQTT library
"""
logging.debug(string)
# End of MQTT callbacks
def cleanup(signum, frame):
"""
Signal handler to ensure we disconnect cleanly
in the event of a SIGTERM or SIGINT.
"""
logging.info("Disconnecting from broker")
# Publish a retained message to state that this client is offline
mqttc.publish(PRESENCETOPIC, "0", retain=True)
mqttc.disconnect()
logging.info("Exiting on signal %d", signum)
sys.exit(signum)
def connect():
"""
Connect to the broker, define the callbacks, and subscribe
This will also set the Last Will and Testament (LWT)
The LWT will be published in the event of an unclean or
unexpected disconnection.
"""
logging.debug("Connecting to %s:%s", MQTT_HOST, MQTT_PORT)
# Set the Last Will and Testament (LWT) *before* connecting
mqttc.will_set(PRESENCETOPIC, "0", qos=0, retain=True)
result = mqttc.connect(MQTT_HOST, MQTT_PORT, 60, True)
if result != 0:
logging.info("Connection failed with error code %s. Retrying", result)
time.sleep(10)
connect()
# Define the callbacks
mqttc.on_connect = on_connect
mqttc.on_disconnect = on_disconnect
mqttc.on_publish = on_publish
mqttc.on_subscribe = on_subscribe
mqttc.on_unsubscribe = on_unsubscribe
mqttc.on_message = on_message
if DEBUG:
mqttc.on_log = on_log
class RepublishingMap:
"""
Read the named mapfile into a dictionary for internal lookups
"""
with open(MAPFILE, mode="r") as inputfile:
reader = csv.reader(inputfile)
mapdict = dict((rows[0], rows[1]) for rows in reader)
def process_connection():
"""
What to do when a new connection is established
"""
logging.debug("Processing new connection")
mqttc.subscribe(MQTT_TOPIC, 2)
def process_message(msg):
"""
What to do with the message that's arrived
"""
logging.debug("Received: %s", msg.topic)
if msg.topic in RepublishingMap.mapdict:
## Found an item. Replace it with one from the dictionary
mqttc.publish(RepublishingMap.mapdict[msg.topic], msg.payload)
logging.debug("Republishing: %s -> %s",
msg.topic,
RepublishingMap.mapdict[msg.topic])
else:
# Received something with a /raw/ topic, but it didn't match.
# Push it out with /unsorted/ prepended
mqttc.publish("/unsorted" + msg.topic, msg.payload)
logging.debug("Unknown: %s", msg.topic)
# Use the signal module to handle signals
signal.signal(signal.SIGTERM, cleanup)
signal.signal(signal.SIGINT, cleanup)
# Connect to the broker
connect()
# Try to loop_forever until interrupted
try:
mqttc.loop_forever()
except KeyboardInterrupt:
logging.info("Interrupted by keypress")
sys.exit(0)