Ttn - json -python (paho-mqtt)


(Dynamitron) #1

I an new from few day in ttn, so be patient with me.
I have a device which send a 2 bytes counter value.
I have the following payload decoder which work when I am testing it :

function Decoder(bytes, port) 
  {
    value = (bytes[0] << 8)|bytes[1];
    
    return {
      "value": String(value)
     }
  }

example :

payload = 64 64
result :
{
“value”: “25700”
}

After I use paho.mqtt in ptyhon scipt located on a remote raspberry.
Each time the script receives a upling it crash and says “TypeError: the JSON object must be str, not 'bytes”

Could someone tell me what is happening ?
The problem is on the ttn side or the python side.
all suggestion are welcomed and many thank in advance !!!

#! /usr/bin/env Python3.4
# -*- coding: UTF-8 -*-

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

APPEUI = "ABCDEFABCDEF0000"
APPID  = "dynamitron_test"
PSW    = 'ttn-account-v2.iNmvcWKseHAcqZ8z5BEBS8PpmZ86ePfBArQchAOppFc'

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

(Jac Kersing) #2

Being new does not mean you don’t have to format your messages. Next time use the hints posted here to improve readability.