Python MQTT发布具有相同主题的多条消息

时间:2016-12-07 17:38:20

标签: python mqtt

我正在尝试使用mqtt向代理发布多个随机数据。下面是发布部分的脚本。

A=A'; A2=A2';

for i=1:size(A,2)
    A(2:size(B,1)+1,i)=B(:,i);
end

A2(2:size(B,1)+1,:)=zeros(size(B,1),size(B,2));

for i=size(A2,2)
    for j=size(A,2)
        if A2(1,i)==A(1,j)
            A2(2:end,i)=A(2:end,j);
        end
    end
end

B2 = A2(2:end,:);

我运行了脚本,出现如下错误:

import paho.mqtt.client as mqtt
import json, schedule, time, random

client = mqtt.Client()
client.connect("<broker address", 1883, 60)

def pub_message():
        tempreading = random.uniform(0, 100)
        pHreading = random.uniform(1,14)
        oxyreading = random.uniform(0, 100)


        data_string1 = str(oxyreading)
        data_string2 = str(pHreading)
        data_string3 = str(tempreading)

        msgs = [("randomdata", data_string1),("randomdata", data_string2),("randomdata", data_string3)]
        client.publish(msgs)

schedule.every(1).minutes.do(pub_message)

while True:
        schedule.run_pending()
        time.sleep(1)

client.disconnect()

我用mqtt搜索了发布多条消息,但没有找到任何好的参考。我还包括我的mqtt订阅部分,用于接收多条消息。我也搜索了这部分,但没有找到任何好的参考。

Traceback (most recent call last):
  File "mqttpub.py", line 27, in <module>
schedule.run_pending()
  File "/usr/local/lib/python2.7/dist-packages/schedule/__init__.py", line 462, in run_pending
default_scheduler.run_pending()
  File "/usr/local/lib/python2.7/dist-packages/schedule/__init__.py", line 75, in run_pending
self._run_job(job)
  File "/usr/local/lib/python2.7/dist-packages/schedule/__init__.py", line 129, in _run_job
ret = job.run()
  File "/usr/local/lib/python2.7/dist-packages/schedule/__init__.py", line 377, in run
ret = self.job_func()
  File "mqttpub.py", line 22, in pub_message
client.publish(msgs)
  File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 980, in publish
rc = self._send_publish(local_mid, topic, local_payload, qos, retain, False, info)
  File "/usr/local/lib/python2.7/dist-packages/paho/mqtt/client.py", line 1979, in _send_publish
utopic = topic.encode('utf-8')
AttributeError: 'list' object has no attribute 'encode'     

有没有人有这方面的经验?先感谢您。

1 个答案:

答案 0 :(得分:2)

是什么让你认为client.publish()会接受数组?

文档(https://pypi.python.org/pypi/paho-mqtt/1.1#publishing)没有提及发布多封邮件的任何内容,您必须为要发送的每封邮件调用client.publish()一次。

您还应该在while while循环中调用client.loop()

while True:
    schedule.run_pending()
    client.loop()
    time.sleep(1)