0

当我的 python 代码尝试连接到 MQTT 代理时,它给了我这个类型错误:

更新-我添加了完整错误

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

python文件的代码是:

#! /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    

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

4

1 回答 1

1

我的猜测是您正在使用 Debian 测试。mosquitto 的 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()调用中。这需要一个字符串,因此您需要一个字符串但有一个布尔值的错误。

您可能会发现其他一些有用的东西 - 如果您没有指定客户端 ID(python_sub在您的示例中),那么 mosquitto 模块将为您生成一个随机 ID,并减少代理发生冲突的可能性。

于 2013-10-26T21:50:22.027 回答