2013-10-26 47 views
0

当我的Python代码尝试连接到MQTT经纪人它给了我这种类型的错误:Python的MQTT:类型错误:胁迫为Unicode:需要字符串或缓冲区,布尔发现

更新 - 我加了完整的错误

Traceback (most recent call last): 
    File "test.py", line 20, in <module> 
    mqttc.connect(broker, 1883, 60, True) 
    File "/usr/local/lib/python2.7/dist-packages/mosquitto.py", line 563, in connect 
    return self.reconnect() 
    File "/usr/local/lib/python2.7/dist-packages/mosquitto.py", line 632, in reconnect 
    self._sock = socket.create_connection((self._host, self._port), source_address=(self._bind_address, 0)) 
    File "/usr/lib/python2.7/socket.py", line 561, in create_connection 
    sock.bind(source_address) 
    File "/usr/lib/python2.7/socket.py", line 224, in meth 
    return getattr(self._sock,name)(*args) 
TypeError: coercing to Unicode: need string or buffer, bool found 

蟒蛇文件的代码是:

#! /usr/bin/python 
import mosquitto 
broker = "localhost" 
#define what happens after connection 
    def on_connect(rc): 
     print "Connected" 
#On recipt of a message do action 
    def on_message(msg): 
     n = msg.payload 
     t = msg.topic 
     if t == "/test/topic": 
      if n == "test": 
     print "test message received" 

# create broker 
mqttc = mosquitto.Mosquitto("python_sub") 
#define callbacks 
mqttc.on_message = on_message 
mqttc.on_connect = on_connect 
#connect 
mqttc.connect(broker, 1883, 60, True) 
#Subscribe to topic 
mqttc.subscribe("/test/topic", 2) 

#keep connected 
while mqttc.loop() == 0: 
    pass  

我不知道为什么它给我这个工作,这3天前。

+1

请编辑以包含回溯。这将告诉我们*哪条线正在引发这个错误。 –

+1

在哪一行?在mosquitto示例中,连接方法中缺少“True” – cox

回答

1

我的猜测是您正在使用Debian测试。 Debian的蚊子包最终从旧的0.15升级到1.2.1。 1.0版本的变化之一是API的调整。

这意味着您的通话

mqttc.connect(broker, 1883, 60, True) 

应该成为

mqttc.connect(broker, 1883, 60) 

True从原来的呼叫设置clean_session参数,它被认为是客户的财产(所以有转移到Mosquitto()构造函数)而不是连接参数。

1.2版将bind_address参数添加到connect()调用中。这需要一个字符串,因此你需要一个字符串但有一个bool的错误。

你可能会发现有用的其他东西 - 如果你没有指定一个客户端ID(在你的例子中为python_sub),那么蚊子模块会为你生成一个随机ID,并给出一个更小的碰撞机会经纪人。

相关问题