gat.py 3.37 KB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Do not execute directly. 
Please execute gateway_http_uplink.py

Created on Mon Oct 19 2021

@author: ALKADRI Mohammad
"""

from gateway_http_downlink import Downlink

from Endpoint import Endpoint

import time
from datetime import datetime
import os
import json
import base64


APIKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcGlfa2V5X2lkIjoiYzA2ZGY1MDMtNjE5Zi00ZjI2LTgxNzEtYTU0OTRmMWJmYmRmIiwiYXVkIjoiYXMiLCJpc3MiOiJhcyIsIm5iZiI6MTYyMjY1MzMzMSwic3ViIjoiYXBpX2tleSJ9.23eLyvgd5zheP9hDM0acCAl9ojhQjLTZAU77IKqhvQY'
server = 'localhost:8080'
#just defining an instance to be used
downlink = Downlink(server, APIKey)
directory = '/home/pi/python/'



def WriteFile(body, event):
    filename = directory + "log/" + \
        time.strftime("%Y_%m_%d_%H-%M-%S") + '_' + event
    # in case of unexisting folder 'log'
    if not os.path.exists(directory + 'log'):
        os.mkdir(directory + 'log')
    # in case of already existing file :
    if os.path.exists(filename + ".json"):
        i = 2
        while(os.path.exists(filename + '_' + str(i) + ".json")):
            i += 1
        path = filename + '_' + str(i) + ".json"
    else:
        path = filename + ".json"

    f = open(path, "a")
    f.write(body.decode("utf-8"))
    f.close()
    print("file written : %s" % path)


def step0(endpoint):
	downlink.FlushQueue(endpoint.EUI)
	downlink.Lorasend(endpoint.EUI, b'\x46')
	print("State: The data sent by Gateway")


def step1(endpoint):
	T3 = 222333 
	T4 = 1112223
	print ("T3 : %s" % T3.to_bytes(4, 'big'))
	print ("T4 : %s" % T4.to_bytes(4, 'big'))
	T = T4 << 32| T3
	print ("T : %s" % T)
	print ("T : %s" % T.to_bytes(8, 'big'))
	downlink.FlushQueue(endpoint.EUI)
	# send all data
	downlink.Lorasend(endpoint.EUI, T.to_bytes(8, 'big'))


def reset(endpoint):
	downlink.FlushQueue(endpoint.EUI)
	downlink.Lorasend(endpoint.EUI, b'\x55') #initialisation packet
	print("enpoint reset : %s" % endpoint.EUI)


def postcompute(event, body, Tn):
	global data
	print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])

	json_ = json.loads(body)
	endpoint = Endpoint()
	endpoint.EUIfromjson(json_)

	print("request from :\nEUI   : %s" % endpoint.EUI)
	print("name  : %s" % json_['deviceName'])
	# write json in a file
	WriteFile(body, event)

	print("event : %s " % event)
	print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
	#treat all cases
	if event == 'up':
		#b64 to bytes
		data = base64.b64decode(json_["data"])
		#bytes to integer
		#integer = int.from_bytes(data, 'big')
		print("data received from Endpoint : ")
		print("base 64 : %s" % json_["data"])
		print("bytes   : %s" % data)
		#print("int     : %s" % integer)
		print()
		print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
		data = int.from_bytes(data, 'big')
		print("data  : %s" % data)
		print("fin")
	elif event == 'txack':
		print("data  : %s" % data)
		if data == 0x5374617274 : 	# 0x5374617274 : Start
			step0(endpoint)
		elif data == 0x54696D6573: 	# 0x54696D6573 : Times
			step1(endpoint)
		else:
			print("error : uncovered State")
			reset(endpoint)
	elif event == 'error':
		print('error : ' + json_["error"])
	else:
		print("possible error : uncovered event")
		print(body)
		reset(endpoint)
	print()

print("Chirpstack server for downlink  : %s" % downlink.server)