Skip to content

Instantly share code, notes, and snippets.

@flamingm0e
Last active March 19, 2018 16:20
Show Gist options
  • Save flamingm0e/7b0591035db3842e0a33e28f8c3dede0 to your computer and use it in GitHub Desktop.
Save flamingm0e/7b0591035db3842e0a33e28f8c3dede0 to your computer and use it in GitHub Desktop.
import paho.mqtt.client as mqttClient
import time
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to broker")
global Connected #Use global variable
Connected = True #Signal connection
else:
print("Connection failed")
def on_message(client, userdata, message):
print "Topic: " + message.topic
print "Message: " + message.payload + "\n"
Connected = False #global variable for the state of the connection
broker_address= "IPADDRESSOFYOURBROKER" #Broker address
port = 1883 #Broker port
user = "yourUser" #Connection username
password = "yourPassword" #Connection password
client = mqttClient.Client("SOMENAMEFORYOURCLIENT") #create new instance
client.username_pw_set(user, password=password) #set username and password
client.on_connect= on_connect #attach function to callback
client.on_message= on_message #attach function to callback
client.connect(broker_address, port=port) #connect to broker
client.loop_start() #start the loop
while Connected != True: #Wait for connection
time.sleep(0.1)
client.subscribe([("sometopic/#", 0), ("someothertopic/#", 0) ])
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print "exiting"
client.disconnect()
client.loop_stop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment