gate.py 4.46 KB
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Do not execute directly. 
Please execute gateway_http_downlink.py

Created on Tue Jun  8 16:37:22 2021

@author: Georges de Massol
"""

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/'


State = 0

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(Tn, endpoint):
    global T2, State
    print("Last State sss : %s" % State)
    if State != 0:
        print("probable error : message unexpected :")
        print("Last State sss : %s" % State)
        print("Current State : 0")
        #reset()
    T2 = Tn
    State = 0

def step1(data, endpoint):
    global T3, State, dTg
    T3 = data
    State = 1
    
    #time spent by gateway between uplink and downlink 
    dTg = T3+1
    print ("Tg : %s" % dTg.to_bytes(4, 'big'))
    downlink.FlushQueue(endpoint.EUI)
    # send all data for step 3
    downlink.Lorasend(endpoint.EUI, b'\x01' + dTg.to_bytes(4, 'big'))
    
def step2(endpoint, data):
    global State
    
    if State != 1:
        print("probable error : message unexpected :")
        print("Last State : %s" % State)
        print("Current State : 2")
        reset()
        
    State = 2

    dTe = int.from_bytes(data, 'big')
    dTv = (dTe - dTg)/2
    print("time of flight (samples number) : %s" % dTv)
    print("time of flight (microseconds)   : %s" % (dTv * 0.0005)) ## 1 sample = 500ns

def step3(endpoint):
    global State
    State = 3

    #reset the endpoint
    reset(endpoint)

def reset(endpoint):
    global State
    downlink.FlushQueue(endpoint.EUI)
    downlink.Lorasend(endpoint.EUI, b'\x55')#initialisation packet
    print("enpoint reset : %s" % endpoint.EUI)
    State = 0    
def postcompute(event, body, Tn):
    print("D")
    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()

        step = data[0]
        print("step : %s" % step)
        print("data : %s" % data[1:])
        if step == 0:
            step0(Tn, endpoint)
        elif step == 2:
            step2(endpoint, data[1:])
        else:
            print("error : uncovered step : %s" % step)
            reset(endpoint)
        print(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
        data = int.from_bytes(data, 'big')
        print("fin")
    elif event == 'txack':
        print("data sent to endpoint")
        if State == 0:
            step1(data, endpoint)
        elif State == 2:
            step3(endpoint)
        else:
            print('error : state %s not expected', 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)