lorawan/python/ttn-receiver.py

75 lines
1.9 KiB
Python
Raw Normal View History

2016-10-10 13:27:55 +00:00
# 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)
#
2016-10-10 13:27:55 +00:00
import paho.mqtt.client as mqtt
import psycopg2
import json
import base64
import os
2016-11-03 09:18:42 +00:00
import logging
2016-10-10 13:27:55 +00:00
2016-11-02 16:13:04 +00:00
import lorautil
2016-11-13 19:41:22 +00:00
2016-11-13 18:47:23 +00:00
log = logging.getLogger(__name__)
2016-11-03 09:18:42 +00:00
2016-10-10 13:27:55 +00:00
#Call back functions
# gives connection message
def on_connect(client,userdata,rc):
print("Connected with result code:"+str(rc))
# subscribe for all devices of user
client.subscribe('+/devices/+/up')
# gives message from device
def on_message(client,userdata,msg):
myjson = msg.payload.decode('utf-8')
mydict = json.loads(myjson)
deveui = mydict['dev_eui']
2016-11-13 18:54:48 +00:00
try:
payload = base64.b64decode(mydict['payload']).decode('utf-8')
except UnicodeDecodeError as e:
log.info("Cannot decode packet as utf-8")
payload = mydict['payload']
2016-11-03 09:18:42 +00:00
log.info("Message received: {}: {}".format(deveui, payload))
2016-11-02 16:13:04 +00:00
lorautil.db_insert_json("ttn", myjson, payload, deveui)
lorautil.db_notify("ttn", payload, deveui)
2016-10-10 13:27:55 +00:00
def on_log(client,userdata,level,buf):
2016-11-03 09:18:42 +00:00
log.debug("message:" + msg)
log.debug("userdata:" + str(userdata))
2016-10-10 13:27:55 +00:00
2016-11-03 09:18:42 +00:00
def on_disconnect(client, userdata, rc):
log.debug("reconnecting...")
client.reconnect()
2016-11-02 15:43:30 +00:00
2016-10-10 13:27:55 +00:00
if __name__ == '__main__':
2016-11-13 19:41:22 +00:00
logging.root.setLevel(logging.DEBUG)
2016-11-13 19:43:51 +00:00
log.setLevel(logging.DEBUG)
2016-11-13 19:41:22 +00:00
2016-10-10 13:27:55 +00:00
mqttc= mqtt.Client()
mqttc.on_connect=on_connect
mqttc.on_message=on_message
2016-11-03 09:18:42 +00:00
mqttc.on_disconnect=on_disconnect
2016-10-10 13:27:55 +00:00
2016-11-13 19:43:51 +00:00
log.debug("Connecting to ttn")
2016-10-10 13:27:55 +00:00
username=os.environ['ttn_user']
password=os.environ['ttn_password']
mqttc.username_pw_set(username, password)
mqttc.connect("staging.thethingsnetwork.org",1883,10)
# and listen to server
2016-11-13 18:47:23 +00:00
log.info("Listening via mqtt")
2016-10-10 13:27:55 +00:00
run = True
while run:
mqttc.loop()