Skip to content
Browse files

Moved to use the signal module to handle signalling (ie, from start-s…

…top-daemon)
  • Loading branch information...
1 parent 18153e2 commit 4a4c9e9d29b835852e7aeb0af8f402b17ae4067c @kylegordon committed Sep 25, 2012
Showing with 21 additions and 30 deletions.
  1. +21 −30 mqtt-republisher.py
View
51 mqtt-republisher.py
@@ -9,8 +9,9 @@
import time
import csv
import logging
+import signal
-MQTT_HOST="localhost"
+MQTT_HOST="10.8.0.1"
MQTT_PORT=1883
MQTT_TOPIC="/raw/#"
MAPFILE='/etc/mqtt-republisher/map.csv'
@@ -34,9 +35,10 @@
logging.info('INFO MODE')
logging.debug('DEBUG MODE')
-def cleanup():
+def cleanup(signum, frame):
logging.info("Disconnecting from broker")
mqttc.disconnect()
+ logging.info("Exiting on signal " + str(signum))
# Turn the mapping file into a dictionary for internal use
# Valid from Python 2.7.1 onwards
@@ -62,31 +64,20 @@ def on_message(msg):
mqttc.publish("/unsorted" + msg.topic, msg.payload)
logging.debug("Unknown: " + msg.topic)
-try:
- #connect to broker
- mqttc.connect(MQTT_HOST, MQTT_PORT, 60, True)
-
- #define the callbacks
- mqttc.on_message = on_message
- mqttc.on_connect = on_connect
-
- mqttc.subscribe(MQTT_TOPIC, 2)
-
- #remain connected and publish
- while mqttc.loop() == 0:
- try:
- logging.debug("Looping")
- pass
- except (KeyboardInterrupt):
- logging.info("Keyboard interrupt received")
- cleanup()
- except (RuntimeError):
- logging.info("Program crashed")
- cleanup()
-
-except (KeyboardInterrupt):
- logging.info("Keyboard interrupt received")
- cleanup()
-except (RuntimeError):
- logging.info("Program crashed")
- cleanup()
+# Use the signal module to handle signals
+signal.signal(signal.SIGTERM, cleanup)
+signal.signal(signal.SIGINT, cleanup)
+
+#connect to broker
+mqttc.connect(MQTT_HOST, MQTT_PORT, 60, True)
+
+#define the callbacks
+mqttc.on_message = on_message
+mqttc.on_connect = on_connect
+
+mqttc.subscribe(MQTT_TOPIC, 2)
+
+#remain connected and publish
+while mqttc.loop() == 0:
+ logging.debug("Looping")
+ pass

0 comments on commit 4a4c9e9

Please sign in to comment.
Something went wrong with that request. Please try again.