【问题标题】:Python MQTT: TypeError: coercing to Unicode: need string or buffer, bool foundPython MQTT: TypeError: coercing to Unicode: need string or buffer, bool found
【发布时间】:2013-10-26 21:19:31
【问题描述】:

当我的 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 天前给我这个它可以工作。

【问题讨论】:

  • 请编辑以包含回溯。这将告诉我们 哪一行 引发了这个错误。
  • 在哪一行?在 mosquitto 示例中,connect 方法中缺少“True”

标签: python unicode typeerror mqtt mosquitto


【解决方案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,并减少发生冲突的机会经纪人。

【讨论】:

    猜你喜欢
    • 2015-03-21
    • 2015-08-20
    • 2021-08-05
    • 2021-10-10
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 2013-06-27
    • 1970-01-01
    相关资源
    最近更新 更多