Last active
April 11, 2018 20:06
-
-
Save marquesghm/00696c0b813ae500257f52859a22588e to your computer and use it in GitHub Desktop.
Exemplo Cliente Subscribe MQTT - Python
This file contains hidden or 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 | |
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 "Message received: " + message.payload | |
Connected = False #global variable for the state of the connection | |
#broker_address= "m11.cloudmqtt.com" #Broker address | |
broker_address = "localhost" | |
port = 1883 #Broker port | |
#user = "yourUser" #Connection username | |
#password = "yourPassword" #Connection password | |
client = mqttClient.Client("PythonMQTT") #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("iseed/test") | |
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