How to check meshtastic mqtt messages in Python

Hi guys,

I was just playing around with my new Meshtastic devices and now wondering how to read public messages from python without using a Meshtastic device, since Meshtastic uses mqtt, any mqtt client should have access to its public mqtt service. Right?

Here is my code:

import paho.mqtt.client as mqtt

############## Subscribe #######################
def on_message(mosq, obj, msg):
    print("%-20s %d %s" % (msg.topic, msg.qos, msg.payload))
    mosq.publish('pong', 'ack', 0)

def on_publish(mosq, obj, mid):
    pass

if __name__ == '__main__':
    client = mqtt.Client()
    client.on_message = on_message
    client.on_publish = on_publish

    client.connect("mqtt.meshtastic.org", 1883, 60)

    client.subscribe("msh/", 0)

    while client.loop() == 0:
        pass

What’s wrong?

have not tried it. very likely you need to provide username and password. and the subscribe string may likely be “msh/#”, or better something more specific (you will realize when you receive some topics).

Have a look at this new community project that does exactly this using Python.

1 Like

Ok I update the code:

import paho.mqtt.client as mqtt

        

############## Subscribe #######################
def on_message(mosq, obj, msg):
    print(f"Topic: {msg.topic}")
    print(f"Qos: {msg.qos}")
    print(f"Payload: {msg.payload}")
    mosq.publish('pong', 'ack', 0)

def on_publish(mosq, obj, mid):
    pass

if __name__ == '__main__':
    client = mqtt.Client()
    client.on_message = on_message
    client.on_publish = on_publish

    # Set username and password
    MQTT_USERNAME = "meshdev"
    MQTT_PASSWORD = "large4cats"
    client.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD)

    client.connect("mqtt.meshtastic.org", 1883, 60)

    client.subscribe("msh/2/c/LongFast/#", 0)

    while client.loop() == 0:
        pass

It’s working but the message is encrypted.
I was expecting decoding it with .decode('utf-8') but look more complicated when I see the way it’s decoded on meshtastic-mqtt-connect.py from the project provided by @GUVWAV.