Publishing MQTT messages from a Python script on a Raspberry Pi

我们两清 提交于 2019-12-01 08:17:36

问题


I am trying to configure a Raspberry Pi (Raspbian, Jessie) to send temperature data from a DS18B20 sensor to my MQTT broker.

I have installed mosquitto, mosquitto-clients, and python-mosquitto. I have also installed paho-mqtt.

Mosquitto seems to be working fine; I can publish from the command line but I can not get ANY python script I've written or found to publish or subscribe.

Why does this work from the command line,

mosquitto_pub -h 192.168.0.21 -d -t test/test -m "Hello world!"

while this script does not?

 #!/usr/bin/env python

 import paho.mqtt.client as mqtt

 # set up the mqtt client
 mqttc = mqtt.Client("python_pub")

 # the server to publish to, and corresponding port
 mqttc.connect("192.168.0.21", 1883)

 # the topic to publish to, and the message to publish
 mqttc.publish("test/test", "Hello world!")

 # establish a two-second timeout
 mqttc.loop(2)

Thanks in advance!

EDIT: Experimenting, I found that by changing the IP in the script to that of the Pi itself, I CAN publish MQTT that is received by the Pi. The Pi can also receive messages published to it. I still, however, can't publish from a script to an external broker. So now I'm thinking it's a broker issue...


回答1:


As mentioned in the comment, the code you posted does work, but for publishing a single message this form is better

#!/usr/bin/env python
import paho.mqtt.publish as publish

publish.single("test/test", "Hello world!", hostname="192.168.0.21")


来源:https://stackoverflow.com/questions/38733589/publishing-mqtt-messages-from-a-python-script-on-a-raspberry-pi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!