# Transfer data with MQTT and python

**URL:** <https://www.thethingsnetwork.org/forum/t/transfer-data-with-mqtt-and-python/53886>\
**Category:** Uncategorized\
**Created:** [December 14, 2021, 6:50pm UTC](https://www.thethingsnetwork.org/forum/t/transfer-data-with-mqtt-and-python/53886 "2021-12-14T18:50:50Z")\
**Posts on this page:** 8\
**Page:** 1

<div class="post-metadata">

**Author:** ![dynamitron](https://www.thethingsnetwork.org/forum/user_avatar/www.thethingsnetwork.org/dynamitron/32/35697_2.png) [@dynamitron](https://www.thethingsnetwork.org/forum/u/dynamitron)\
**Post date:** [December 14, 2021, 6:50pm UTC](https://www.thethingsnetwork.org/forum/t/transfer-data-with-mqtt-and-python/53886/1 "2021-12-14T18:50:50Z")

</div>

Hello,  
I have a tracker device that I have migrated to V3. Data are correctly arriving from my device into the TTN network as I can see them into the live data.  
I wish to transfer the data into a data base located in a linux device and for this, in V2 I was using MQTT and a pyhton script which is shown down here. This code was working perfect with V2  
In V3, I have created a new MQTT integration and change the APPEUI, APPID and PSW in the python code.  
I can see that my code is connecting to the server but the data are not arriving.  
What is wrong ?

```auto
# https://www.thethingsnetwork.org/forum/t/a-python-program-to-listen-to-your-devices-with-mqtt/9036/6
# Get data from MQTT server
# Run this with python 3, install paho.mqtt prior to use

import paho.mqtt.client as mqtt
import json
import base64
import haversine
from datetime import datetime as dt
#from haversine import haversine
from geojson import Feature, Point, dump

longitudep = 0
latitudep = 0
timep = dt.now()

APPEUI = "70b3d57ed0049e1c"
APPID = "dynamitrontracker@ttn"
#PSW = 'NNSXS.NLD6E3TOZYKFK6VU2XG7YJVCM3TCQB4BQFYJQEI.WSQX2B557JYQMRZ2BGHPWU7RDK3XVCUCKXZBSPXPBLGVZHXYQODA'
PSW = 'NNSXS.NLD6E3TOZYKFK6VU2XG7YJVCM3CQB4BQFYJQEI.WSQX2B557JYQMRZ2BGHPWU7RDK3XVCUCKXZBSPXPBLGVZHXYQODA'

#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/+/up')

# gives message from device
def on_message(mqttc,obj,msg):
    try:
        #print(msg.payload)
        x = json.loads(msg.payload.decode('utf-8'))
        device = x["dev_id"]
        counter = x["counter"]
        payload_raw = x["payload_raw"]
        payload_fields = x["payload_fields"]
        datetime = x["metadata"]["time"]
        gateways = x["metadata"]["gateways"]
        SF = x["metadata"]["data_rate"]
        y = json.dumps(payload_fields)
        y_dict = json.loads(y)
        latitude = y_dict["latitude"]
        longitude = y_dict["longitude"]
        dist = round((haversine((5.626525,4.44700),(latitude,longitude,))),3)  
        
        global longitudep
        global latitudep
        global timep       
             

        distp = round((haversine((latitudep,longitudep),(latitude,longitude))),3)
        time_delta = dt.now()-timep
        speed = distp /((time_delta.total_seconds())/3600)
        #print (longitudep)
        #print (latitudep)
        
        longitudep = longitude
        latitudep = latitude
        timep = dt.now()
        
        #print (longitudep)
        #print (latitudep)
        #print (distp)
        #print (speed)
        print (counter)
        #print ("\n\r")
      
        for gw in gateways:
            gateway_id = gw["gtw_id"]
            rssi = gw["rssi"]
            snr = gw["snr"]
            
        #print(datetime + ", " + device + ", " + str(counter) + ", "+ gateway_id + ", "+ str(rssi) + ", " + str(snr) + ", "+ str(payload_fields))
        #print(datetime + ", " + gateway_id + ", "+ str(rssi) + ", " + str(snr) + ", "+ str(SF)+ ", "+ str(round(latitude,6)) + ", "+ str(round(longitude,6)) + ", " + str(dist) + ", " +str(round(speed,1)))
        my_point = Point((longitude,latitude))
        my_feature = json.dumps(Feature(geometry=my_point, properties= {"datetime": str(datetime),"gateway_id": str (gateway_id),"rssi": str (rssi),"snr": str (snr),"SF": str (SF),"dist": str (dist),"speed":str (round(speed,1))}))
        #print (my_feature)
        if ((latitude!=0) and (longitude!=0) and (distp>0.015)):
            with open("track.geojson","a") as outfile:
                outfile.write (my_feature + '\n')
            outfile.close()
    except Exception as e:
        print(e)
        pass

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("eu1.cloud.thethings.network",1883,60)

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

```

---

<div class="post-metadata">

**Author:** ![gnsbglora](https://www.thethingsnetwork.org/forum/user_avatar/www.thethingsnetwork.org/gnsbglora/32/35697_2.png) [@gnsbglora](https://www.thethingsnetwork.org/forum/u/gnsbglora)\
**Post date:** [December 14, 2021, 8:35pm UTC](https://www.thethingsnetwork.org/forum/t/transfer-data-with-mqtt-and-python/53886/2 "2021-12-14T20:35:17Z")

</div>

The message structure changed a bit in V3. I think u can find it here:  
[https://www.thethingsindustries.com/docs/reference/data-formats/](https://www.thethingsindustries.com/docs/reference/data-formats/)

Also the subscribe string should be different:

> [@dynamitron](#):
>
> `mqttc.subscribe('+/devices/+/up')`

It should be mqttc.subscribe(‘v3/+/devices/+/up’)

---

<div class="post-metadata">

**Author:** ![descartes](https://www.thethingsnetwork.org/forum/user_avatar/www.thethingsnetwork.org/descartes/32/47220_2.png) [@descartes](https://www.thethingsnetwork.org/forum/u/descartes)\
**Post date:** [December 14, 2021, 10:20pm UTC](https://www.thethingsnetwork.org/forum/t/transfer-data-with-mqtt-and-python/53886/3 "2021-12-14T22:20:02Z")

</div>

Try this as a starter / reference:

> **[TheThingsStack-Integration-Starters/MQTT-to-Tab-Python3 at main ·...](https://github.com/descartes/TheThingsStack-Integration-Starters/tree/main/MQTT-to-Tab-Python3)**
>
> main/MQTT-to-Tab-Python3

---

<div class="post-metadata">

**Author:** ![dynamitron](https://www.thethingsnetwork.org/forum/user_avatar/www.thethingsnetwork.org/dynamitron/32/35697_2.png) [@dynamitron](https://www.thethingsnetwork.org/forum/u/dynamitron)\
**Post date:** [December 15, 2021, 2:16am UTC](https://www.thethingsnetwork.org/forum/t/transfer-data-with-mqtt-and-python/53886/4 "2021-12-15T02:16:08Z")

</div>

> [@gnsbglora](#):
>
> The message structure changed a bit in V3. I think u can find it here:  
> [https://www.thethingsindustries.com/docs/the-things-stack/concepts/data-formats/](https://www.thethingsindustries.com/docs/reference/data-formats/)
> 
> Also the subscribe string should be different:
> 
> > [@dynamitron](#):
> >
> > `mqttc.subscribe('+/devices/+/up')`
> 
> It should be mqttc.subscribe(‘v3/+/devices/+/up’)

Thank you, this is the solution. 👌 👍  
You are right, I had to rewrite the code to cope with the new V3 data format.

---

<div class="post-metadata">

**Author:** ![dynamitron](https://www.thethingsnetwork.org/forum/user_avatar/www.thethingsnetwork.org/dynamitron/32/35697_2.png) [@dynamitron](https://www.thethingsnetwork.org/forum/u/dynamitron)\
**Post date:** [December 15, 2021, 8:07pm UTC](https://www.thethingsnetwork.org/forum/t/transfer-data-with-mqtt-and-python/53886/5 "2021-12-15T20:07:51Z")

</div>

Nice !!!  
My tracker is back in line after migration to V3

![image](https://www.thethingsnetwork.org/forum/uploads/default/original/3X/5/a/5ace7464295358e9b6315c8efb6ab06196cc4e56.jpeg)

---

<div class="post-metadata">

**Author:** ![Johan\_Scheepers](https://www.thethingsnetwork.org/forum/user_avatar/www.thethingsnetwork.org/johan_scheepers/32/48536_2.png) [@Johan\_Scheepers](https://www.thethingsnetwork.org/forum/u/Johan_Scheepers)\
**Post date:** [December 15, 2021, 8:43pm UTC](https://www.thethingsnetwork.org/forum/t/transfer-data-with-mqtt-and-python/53886/6 "2021-12-15T20:43:55Z")

</div>

You are a few km/h off time travel 😇  
 ![image](https://www.thethingsnetwork.org/forum/uploads/default/original/3X/4/b/4bdfc4c49282d0af070fb680b63f8b912b4ea2da.png)

---

<div class="post-metadata">

**Author:** ![dynamitron](https://www.thethingsnetwork.org/forum/user_avatar/www.thethingsnetwork.org/dynamitron/32/35697_2.png) [@dynamitron](https://www.thethingsnetwork.org/forum/u/dynamitron)\
**Post date:** [December 15, 2021, 9:35pm UTC](https://www.thethingsnetwork.org/forum/t/transfer-data-with-mqtt-and-python/53886/7 "2021-12-15T21:35:05Z")

</div>

I kown, still a bug to solve… 😂

---

<div class="post-metadata">

**Author:** ![system](https://www.thethingsnetwork.org/forum/uploads/default/original/3X/6/2/6250ea44fd2b0d6259489e1a92748df681e1f970.png) [@system](https://www.thethingsnetwork.org/forum/u/system)\
**Post date:** [December 16, 2021, 9:35pm UTC](https://www.thethingsnetwork.org/forum/t/transfer-data-with-mqtt-and-python/53886/8 "2021-12-16T21:35:26Z")

</div>

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.
