Skip to content

Instantly share code, notes, and snippets.

Created December 22, 2014 16:46
Show Gist options
  • Save dbonino/e33b499f31f5b886f425 to your computer and use it in GitHub Desktop.
Save dbonino/e33b499f31f5b886f425 to your computer and use it in GitHub Desktop.
MQTT Dump utility using Eclipse PAHO client
Created on Nov 4, 2014
@author: bonino
import paho.mqtt.client as mqtt
import time
import getopt
import sys
mqtt_broker = "localhost"
mqtt_port = 1883
mqtt_topic = "/#"
mqttc = mqtt.Client("mosquitto_dump",True,None,mqtt.MQTTv31)
def on_message(mqttc, obj, msg):
payload = str(msg.payload)
print(msg.topic + " Payload -> \n" + payload)
def on_connect(mqttc, userdata, flags, rc):
print ("rc= %s")%rc
print "connected, now subscribing..."
topics = mqtt_topic.split(";")
for topic in topics:
mqttc.subscribe(topic, 0)
def on_disconnect(client, userdata, rc):
print "re-connecting..."
mqttc.connect(mqtt_broker, mqtt_port, 60)
def usage():
print "Mosquitto Dump utility"
print "Usage: mosquitto_dump -h mqtt_broker -p port -t topic"
def main():
#reference to the global variables
global mqtt_broker
global mqtt_port
global mqtt_topic
opts, args = getopt.getopt(sys.argv[1:], "h:p:t:", ["mqttbroker=", "port=", "topic="])
except getopt.GetoptError as err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
#handle options
for o, a in opts:
if o in ("-h", "--mqttbroker"):
mqtt_broker = a
elif o in ("-p", "--port"):
mqtt_port = a
elif o in ("-t", "--topic"):
mqtt_topic = a
assert False, "unhandled option"
#business logic to build the mqtt client
#building the client
print "building the client"
mqttc.on_message = on_message
mqttc.on_connect = on_connect
print "connecting..."
mqttc.connect(mqtt_broker, mqtt_port, 60)
except KeyboardInterrupt:
print "stopped"
if __name__ == '__main__':
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment