From 58acd06765aa857f972462838597faa693f65c3e Mon Sep 17 00:00:00 2001 From: "dongwoo.koh" Date: Sun, 10 Feb 2019 05:32:02 +0000 Subject: [PATCH] [MQTT]Enhanced ttn-receiver.py to ttn_mqtt-receiver.py --- python/ttn_mqtt-receiver.py | 78 +++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 python/ttn_mqtt-receiver.py diff --git a/python/ttn_mqtt-receiver.py b/python/ttn_mqtt-receiver.py new file mode 100644 index 0000000..06bed2d --- /dev/null +++ b/python/ttn_mqtt-receiver.py @@ -0,0 +1,78 @@ +# node.py +# Simple Python client to show node activity from ttn MQTT brooker with credentials +# Author: R.Schimmel +# www.schimmel-bisolutions.nl +# first install paho.mqtt.client: pip install paho-mqtt +# +# Enhanced for lorawan in Digital Glarus by Nico Schottelius (nico.schottelius -at- ungleich.ch) +# +# Enhanced again lorawan in Digital Glarus by Dongwoo Koh (dongwoo.koh -at- ungleich.ch) + +import paho.mqtt.client as mqtt +import psycopg2 +import json +import base64 +import os +import logging +import lorautil + +def on_connect(mqttc,mosq,obj,rc): + log.debug("Connected with result code:"+str(rc)) + # subscribe for all devices of user + mqttc.subscribe('+/devices/+/up') + if rc==0: + print("connected OK Returned code=",rc) + else: + print("Bad connection Returned code=",rc) + +def on_message(mqttc,obj,msg): + print("msg:",msg) + myjson = msg.payload.decode('utf-8') + mydict = json.loads(myjson) + print("mydict:",mydict) + deveui = mydict['hardware_serial'] + try: + payload = base64.b64decode(mydict['payload_raw']).decode('utf-8') + except UnicodeDecodeError as e: + log.info("Cannot decode packet as utf-8") + payload = mydict['payload_raw'] + + log.info("Message received: {}: {}".format(deveui, payload)) + lorautil.db_insert_json("ttn", myjson, payload, deveui) + lorautil.db_notify("ttn", payload, deveui) + + +def on_log(mqttc,obj,level,buf): + log.debug("message:" + buf) + log.debug("userdata:" + str(obj)) + +def on_disconnect(mqttc, mosq, obj, rc): + log.debug("reconnecting...") + mqttc.reconnect() + +if __name__ == '__main__': + logging.root.setLevel(logging.INFO) + logging.basicConfig(format='%(levelname)s: %(message)s') + + log = logging.getLogger(__name__) + + mqttc= mqtt.Client() + mqttc.on_connect=on_connect + mqttc.on_message=on_message + mqttc.on_disconnect=on_disconnect + + log.debug("Connecting to ttn") + username="" #Put your username + password="" #Put your password + + mqttc.username_pw_set(username, password) + mqttc.connect("eu.thethings.network",1883,10) + logging.basicConfig(level=logging.DEBUG) + logger = logging.getLogger(__name__) + mqttc.enable_logger(logger) + + # and listen to server + log.info("Listening via mqtt") + run = True + while run: + mqttc.loop()