编译MQTT Python客户端时出错

时间:2017-12-12 13:21:30

标签: python raspberry-pi client mqtt paho

我在Raspberry上安装MQTT代理(Mosquitto)并将安装客户端(Paho Client Python),我尝试启动我的客户端,但是在编译我的文件时出现此错误。



  File "client_mqtt.py", line 38, in <module>
    client = mqtt.client()
AttributeError: 'module' object has no attribute 'client'
&#13;
&#13;
&#13;

我的完整档案是

import paho.mqtt.client as mqtt
import sys

#definicoes: 
Broker            = "localhost"
username          = "mosquitto"
password          = "mqtt"
PortaBroker       = 1883
KeepAliveBroker   = 60
client_name       = "Local"

topic_casa = "casa" 
topic_mcu  = "mcu" 


#Callback - conexao ao broker realizada
def on_connect(client, userdata, flags, rc):
    print("[STATUS] Conectado ao Broker. Resultado de conexao: "+str(rc))
    client.subscribe(topic_mcu)
    client.subscribe(topic_casa)


#Callback - mensagem recebida do broker
def on_message(client, userdata, msg):
    MensagemRecebida = str(msg.payload)

    print("[MSG RECEBIDA] Topico: "+msg.topic+" / Mensagem: "+MensagemRecebida)


def on_disconnect(client, userdata, rc):
    if rc != 0:
        print("Unexpected disconnection.")  

#programa principal:
try:
        print("[STATUS] Inicializando MQTT...")
        #inicializa MQTT:
        client = mqtt.Client()
        client.username_pw_set(username, password)
        client.on_connect     = on_connect
        client.on_message     = on_message
        client.on_disconnect  = on_disconnect

        client.connect(Broker, PortaBroker, KeepAliveBroker)
        client.loop_forever()
except KeyboardInterrupt:
        print "\nCtrl+C pressionado, encerrando aplicacao e saindo..."
        sys.exit(0)

3 个答案:

答案 0 :(得分:0)

该错误与您发布的代码不符。

错误表示您使用mqtt.client()而不是mqtt.Client()

答案 1 :(得分:0)

Tks hardillb,但我尝试用

client = mqtt.Client()
 client = mqtt.client()

client = mqtt.Client(“”)
 client = mqtt.client(“”)

并没有解决它,我将测试什么?

答案 2 :(得分:0)

我有同样的问题,

   File "random.py", line 3, in <module>
     import paho.mqtt.client as mqtt
AttributeError: 'module' object has no attribute 'client'

发生这种情况是因为我当前的文件名是random.py。尝试重命名您的client_mqtt.py,也许它可以解决您的问题。