简体   繁体   中英

Python MQTT to publish multiple message with same topic

I am trying to publish a multiple random data using mqtt to the broker. Below is the script for the publish part.

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

I ran the script and there is error like below:

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'     

I searched about the publish multiple message with mqtt but did not find any good reference. I also included my mqtt subscribe part for receiving the multiple messages. I did search about this part too but did not find any good reference.

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

Does anyone have any experience doing it? Thank you in advance.

What makes you think client.publish() will accept an array?

The doc's ( https://pypi.python.org/pypi/paho-mqtt/1.1#publishing ) don't mention anything about publishing multiple messages, you will have to call client.publish() once for every message you want to send.

You should also be calling client.loop() in your while true loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM