[英]python mqtt script on raspberry pi to send and receive messages
[英]Publishing MQTT messages from a Python script on a Raspberry Pi
我正在尝试配置Raspberry Pi(Raspbian,Jessie),以将温度数据从DS18B20传感器发送到我的MQTT代理。
我已经安装了mosquitto,mosquitto-clients和python-mosquitto。 我还安装了paho-mqtt。
蚊子似乎运转良好; 我可以从命令行发布,但无法获取我编写或发现要发布或订阅的任何python脚本。
为什么从命令行运行,
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也可以接收发布到它的消息。 但是,我仍然无法从脚本发布到外部代理。 所以现在我认为这是一个经纪人问题...
如评论中所述,您发布的代码确实有效,但是对于发布单个消息,此表单更好
#!/usr/bin/env python
import paho.mqtt.publish as publish
publish.single("test/test", "Hello world!", hostname="192.168.0.21")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.