Created
December 22, 2014 16:46
-
-
Save dbonino/e33b499f31f5b886f425 to your computer and use it in GitHub Desktop.
MQTT Dump utility using Eclipse PAHO client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
''' | |
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): | |
time.sleep(10) | |
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 | |
try: | |
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" | |
usage() | |
sys.exit(2) | |
#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 | |
else: | |
assert False, "unhandled option" | |
#business logic to build the mqtt client | |
try: | |
#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) | |
mqttc.loop_forever() | |
except KeyboardInterrupt: | |
print "stopped" | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment