Paho Python-MQTT-client eine Verbindung erfolgreich aber on_connect callback wird nicht aufgerufen

Ich habe ein einfaches script auf einem Raspberry Pi veröffentlicht, die eine Beispiel-Nachricht alle 3 Sekunden. Ich habe erklärt die Rückrufe on_connect, on_publish und on_disconnect. Dieser client verbindet sich erfolgreich, aber on_connect ist nicht genannt, veröffentlicht und on_publish genannt wird, trennt und on_disconnect genannt wird.

Dies ist mein Skript

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)   

Obwohl dieser kleine "bug" nicht auf die Nachricht zu veröffentlichen, ist hauptsächlich, was ich erreichen will, warum passiert es und wie kann ich es beheben?

InformationsquelleAutor evgi9 | 2016-04-05
Schreibe einen Kommentar