![](/img/trans.png)
[英]How to connect to multiple instances of MQTT broker with Paho Python client?
[英]How to connect to a digitransit broker with a specific topic using paho mqtt client
我对 MQTT 很陌生,我想建立与 digittransit mqtt 代理的连接,以使用 python paho mqtt 客户端接收公共交通数据。 要连接到代理,需要端口和主题。
关于经纪人来源中提供的信息,我想我至少需要两条信息,但我不确定是否缺少某些东西。 请注意,该脚本是通过基于浏览器的 jupyter notebook 执行的。
经纪人来源: https: //digitransit.fi/en/developers/apis/4-realtime-api/vehicle-positions/ Paho 文档: https ://www.eclipse.org/paho/index.php?page=clients/ 蟒蛇/index.php
通过命令行运行时,可以接收数据,例如
/hfp/v2/journey/ongoing/vp/bus/0022/01281/1040/2/Elielinaukio/14:29/1140118/0//// {"VP":{"desi":"40","dir":"2","oper":22,"veh":1281,"tst":"2022-07-06T11:56:53.417Z","tsi":1657108613,"spd":null,"hdg":null,"lat":null,"long":null,"acc":null,"dl":-101,"odo":8530,"drst":0,"oday":"2022-07-06","jrn":2646,"line":62,"start":"14:29","loc":"ODO","stop":null,"route":"1040","occu":0}}
您可以简单地使用两个命令来尝试一下:
npm install -g mqtt
mqtt subscribe -h mqtt.hsl.fi -p 8883 -l mqtts -v -t "/hfp/v2/journey/#"
在 jupyter notebook 或 python 脚本上运行时,我只看到定义on_connect
方法的输出,但没有显示数据。
我的代码片段是:
# pip install paho-mqtt
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+ str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("/hfp/v2/journey/#")
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.tls_set()
client.connect("mqtt.hsl.fi", 8883, 60)
client.loop_forever()
有谁知道什么样的细节是错误的或遗漏的?
更新:接受的解决方案适用于通过 python IDE(如 Pycharm 或 Visual Studio Code)执行的 python 脚本,但不适用于基于浏览器的 IDE,如 Jupyter Notebook。
问题是您没有告诉 Python Paho 客户端它需要使用 TLS 进行连接。
在调用connect()
client.tls_set()
)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.tls_set()
client.connect("mqtt.hsl.fi", 8883, 60)
client.loop_forever()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.