【问题标题】:Python MQTT to publish multiple message with same topicPython MQTT 发布具有相同主题的多条消息
【发布时间】:2016-12-07 17:38:19
【问题描述】:

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

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()

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

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'     

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

import paho.mqtt.client as mqtt
from models import *
from sqlalchemy.orm import sessionmaker
import json

def on_connect(client, userdata, rc):
        print("connected with result code" + str(rc))

        client.subscribe("randomdata")

def on_message(client, userdata, msg):
        print "Topic:", msg.topic + " " + "Message:" + " " + "Value1:" + str(msg.payload1) + " " + "Value2:" + str(msg.payload2) + " " + "Value3:" + str(msg.payload3) 

        engine = create_engine('postgresql://user:password@localhost/mydatabase')
        Base.metadata.bind = engine
        DBSession = sessionmaker(bind=engine)

        session = DBSession()
        # store message received into database
        raw_data = _Data(Value1=msg.payload1, Value2=msg.payload2, Value3=msg.payload3, time=msg.timestamp)
        session.add(raw_data)
        session.commit()


client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("<broker address>",1883, 60)

client.loop_forever()

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

【问题讨论】:

    标签: python mqtt


    【解决方案1】:

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

    文档 (https://pypi.python.org/pypi/paho-mqtt/1.1#publishing) 没有提及发布多条消息,您必须为每条要发送的消息调用一次 client.publish()

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

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

    【讨论】:

    • 我在网上搜索时发现了这个。 nullege.com/codes/search/paho.mqtt.publish.multiple 认为同样的例子也可以。但无论如何,我是否必须将 client.publish 函数全部放在 schedule.every().minute 函数之前?
    • paho.mqtt.publish.multiple() 方法更适合一次性发送多条消息,因为它在每次调用时都会建立和断开与代理的连接。对于这个用例,为每条消息调用 paho.mqtt.client.publish 更有意义。
    猜你喜欢
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    • 1970-01-01
    • 2021-10-09
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多