MQTT subscription using python and paho MQTT

Hi,

I am working to the following code to subscribe MQTT topic called “test” to receive flow stats from application workflow. The below code not returning any outputs.

import paho.mqtt.client as mqtt

# MQTT broker information
mqtt_host = "mqtt://broker.losant.com"
mqtt_port = 1883
mqtt_client_id = "mqtt_66eaf9d2975adcda2edc253d"
username = "f7f1aaca-xxxx-xxxx-xxxx-0XXXXX"  
password = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"  

# Callback function for received messages
def on_message(client, userdata, msg):
    print(f"Received message on topic {msg.topic}: {str(msg.payload.decode('utf-8'))}")

def main():
    # Create MQTT client
    client = mqtt.Client(mqtt_client_id)
    client.on_message = on_message

    # Set username and password (if using Losant authentication)
    client.username_pw_set(username, password)

    # Connect to MQTT broker
    client.connect(mqtt_host, mqtt_port)

    # Subscribe to topics
    client.subscribe("test")  # Subscribe to all topics (replace with specific topics if needed)

    # Start the MQTT loop
    client.loop_forever()

if __name__ == "__main__":
    main()

Subrahmanyam

To connect to Losant’s broker, the client ID must be a device ID. Your client ID mqtt_66eaf9d2975adcda2edc253d is not a device ID.

I tried with Device Id as well. Still, it didn’t work. Two quick questions

  • I am publishing MQTT topic from application workflow. Do i still need to use to device id?
  • Do i need mqtt:// in "mqtt_host = “mqtt://broker.losant.com”. with mqtt, the code is not running.
    Sorry for the trouble, i am new to mqtt

I am publishing MQTT topic from application workflow. Do i still need to use to device id?

The device ID is required to connect to the broker using any external client. This python script is an external client and therefore requires the client ID to be set to a device ID. Workflows can just publish directly to the broker - you can think of them as already connected to the broker behind the scenes.

Do i need mqtt:// in "mqtt_host = “mqtt://broker.losant.com”. with mqtt, the code is not running.

It’s not needed. You can see an example here:

https://github.com/eclipse/paho.mqtt.python/blob/master/examples/client_sub.py

The other thing to check is that you’ve granted your access key and secret permission to subscribe to the test topic. By default, that is not allowed. Details can be found here:

https://docs.losant.com/applications/access-keys/#additional-mqtt-topics-access