# A Python program to listen to your devices with MQTT

**URL:** <https://www.thethingsnetwork.org/forum/t/a-python-program-to-listen-to-your-devices-with-mqtt/9036>\
**Category:** Application Development\
**Created:** [July 3, 2016, 8:33pm UTC](https://www.thethingsnetwork.org/forum/t/a-python-program-to-listen-to-your-devices-with-mqtt/9036 "2016-07-03T20:33:45Z")\
**Posts on this page:** 1\
**Showing post:** 6

<div class="post-metadata">

**Author:** ![mrTheWheel](https://www.thethingsnetwork.org/forum/user_avatar/www.thethingsnetwork.org/mrthewheel/32/6404_2.png) [@mrTheWheel](https://www.thethingsnetwork.org/forum/u/mrTheWheel)\
**Post date:** [August 21, 2017, 11:11am UTC](https://www.thethingsnetwork.org/forum/t/a-python-program-to-listen-to-your-devices-with-mqtt/9036/6 "2017-08-21T11:11:12Z")

</div>

Ok, thanks again for all the help!

It seems TTN authentification does not like an Application and Device with the same name ☹

So I added an other application with the name “my\_second\_lora\_app” and connected the original “loraexplora” device at it.

Than, with this program I can connect to the MQTT server and decode the send messages:

```
#!/<path-to>/python
# Get date from MQTT server

import paho.mqtt.client as mqtt
import json
import base64

APPEUI = "70B3D57EF00069A3"
APPID = "my_second_lora_app"
PSW = 'ttn-account-v2.<lots-of-chars>'

#Call back functions 

# gives connection message
def on_connect(mqttc, mosq, obj,rc):
    print("Connected with result code:"+str(rc))
    # subscribe for all devices of user
    mqttc.subscribe('+/devices/#')

# gives message from device
def on_message(mqttc,obj,msg):
    x = json.loads(msg.payload)
    device = x["dev_id"]
    payload_raw = x["payload_raw"]
    payload_plain = base64.b64decode(payload_raw)
    datetime = x["metadata"]["time"]
    #rssi = x["metadata"]["gateways"]["rssi"] # <== this raises an error (why?)
    rssi = -1
    print(device + ": " + payload_raw + " ==> " + payload_plain + ", RSSI ["+ str(rssi) + "] @" + datetime )

def on_publish(mosq, obj, mid):
    print("mid: " + str(mid))

def on_subscribe(mosq, obj, mid, granted_qos):
    print("Subscribed: " + str(mid) + " " + str(granted_qos))

def on_log(mqttc,obj,level,buf):
    print("message:" + str(buf))
    print("userdata:" + str(obj))
    
mqttc= mqtt.Client()
# Assign event callbacks
mqttc.on_connect=on_connect
mqttc.on_message=on_message

mqttc.username_pw_set(APPID, PSW)
mqttc.connect("eu.thethings.network",1883,60)

# and listen to server
run = True
while run:
    mqttc.loop()
```

---

_[View the full topic](https://www.thethingsnetwork.org/forum/t/a-python-program-to-listen-to-your-devices-with-mqtt/9036)._
