Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python paho mqtt on_connect

import paho.mqtt.client as mqtt
import time

def on_connect(mqttc, userdata, rc):
    print("Connected with result code "+str(rc))
    if rc!=0 :
        mqttc.reconnect()

def on_publish(mqttc, userdata, mid):
    print "Published"

def on_disconnect(mqttc, userdata, rc):
    if rc != 0:
        print("Unexpected disconnection. Reconnecting...")
        mqttc.reconnect()
    else :
        print "Disconnected successfully"

# Setup MQTT
# broker='test.mosquitto.org'
broker = 'iot.eclipse.org'
broker_port=1883

# Create a client instance
mqttc=mqtt.Client(client_id="MyClient")
mqttc.on_connect = on_connect
mqttc.on_publish = on_publish
mqttc.on_disconnect = on_disconnect

while 1:

    mqttc.connect(broker, broker_port, 60)
    # print "Connected."    # I don't want this message. 
                            # Why isn't the on_connect callback invoked?

    try:
        topic = "this/is/a/test/topic"
        payload = "test_message"
        print "Publishing " + payload + " to topic: " + topic + " ..."
        mqttc.publish(topic, payload, 0)

    except Exception as e:
        print "exception"
        log_file=open("log.txt","w")
        log_file.write(str(time.time())+" "+e.__str__())
        log_file.close()

    mqttc.disconnect()
    print ""
    time.sleep(3)
Comment

PREVIOUS NEXT
Code Example
Python :: Connect to MySQL Using Connector Python C Extension 
Python :: DateEntry tkinter 
Python :: where is a package stored python 
Python :: change background create_text tkinter 
Python :: python ismatch 
Python :: pydub create empty track 
Python :: minio python remove a bucket 
Python :: scikit decision tree 
Python :: django search pagination 
Python :: 1d random walk in python stack exchange 
Python :: pandas series create 
Python :: pigeonhole sort python 
Python :: How to find the most similar word in a list in python 
Python :: binary search iterative python 
Python :: python list insert 
Python :: add space before and after string python 
Python :: django login required class based views 
Python :: python delete column 
Python :: how to decode recv data in python 
Python :: DJANGO model instance get by variable 
Python :: how to uninstall python 
Python :: python ordered indexs of a list 
Python :: convert blocks to mb python 
Python :: how to hello world in python 
Python :: python serial COM3 
Python :: create smtp server python 
Python :: tkinter window minsize 
Python :: convert pdf to word doc in python 
Python :: how to set class attributes with kwargs python 
Python :: pandas if nan, then the row above 
ADD CONTENT
Topic
Content
Source link
Name
6+8 =