Search code examples
pythonmqttpaho

How to connect to a digitransit broker with a specific topic using paho mqtt client


I am pretty new to MQTT and I would like to establish a connection to a digitransit mqtt broker to receive public transportation data using python paho mqtt client. To connect to a broker the port and the topic is needed.

Regarding the information provided in the broker source I guess I need at least two pieces of information but I am not sure if something is missing. Please not that the script is executed via browser based jupyter notebook.

Broker source: https://digitransit.fi/en/developers/apis/4-realtime-api/vehicle-positions/ Paho documentation: https://www.eclipse.org/paho/index.php?page=clients/python/index.php

  • Port: 8883
  • Topic: /hfp/v2/journey/#
  • Broker: mqtt.hsl.fi

When running via command line the data can be received, e.g.

/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}}

You can try this out simply using two commands:

npm install -g mqtt
mqtt subscribe -h mqtt.hsl.fi -p 8883 -l mqtts -v -t "/hfp/v2/journey/#"

When running on a jupyter notebook or python script I only see the output that is defined on_connectmethod but no data shows up.

My code snippet is:

# 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()

Does anyone know what kind of detail is wrong or missing?

UPDATE: The accepted solution works for python scripts executed via python IDE like Pycharm or Visual Studio Code but not with browser based IDEs like Jupyter Notebook.


Solution

  • The problem is you have not told the Python Paho Client it needs to connect using TLS.

    Add the client.tls_set() before the call to connect()

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