Publishing MQTT messages from a Python script on a

2019-02-19 15:20发布

问题:

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