从 Raspberry Pi 上的 Python 脚本发布 MQTT 消息 [英] Publishing MQTT messages from a Python script on a Raspberry Pi
问题描述
我正在尝试配置 Raspberry Pi(Raspbian、Jessie)以将温度数据从 DS18B20 传感器发送到我的 MQTT 代理.
I am trying to configure a Raspberry Pi (Raspbian, Jessie) to send temperature data from a DS18B20 sensor to my MQTT broker.
我已经安装了 mosquitto、mosquitto-clients 和 python-mosquitto.我也安装了 paho-mqtt.
I have installed mosquitto, mosquitto-clients, and python-mosquitto. I have also installed paho-mqtt.
Mosquitto 似乎工作正常;我可以从命令行发布,但我无法获得任何我编写或找到的要发布或订阅的 Python 脚本.
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!"
而这个脚本没有?
#!/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)
提前致谢!
通过实验,我发现通过将脚本中的 IP 更改为 Pi 本身的 IP,我可以发布 Pi 接收到的 MQTT.Pi 还可以接收发布到它的消息.但是,我仍然无法从脚本发布到外部代理.所以现在我认为这是经纪人问题...
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...
推荐答案
如评论中所述,您发布的代码确实有效,但用于发布 single 留言这种形式更好
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")
这篇关于从 Raspberry Pi 上的 Python 脚本发布 MQTT 消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!