Commit 48315147 authored by Marco Dallagiacoma's avatar Marco Dallagiacoma

First commit

parents
Pipeline #36908790 failed with stages
in 1 minute and 20 seconds
import time
import pycom
import struct
import socket
import ubinascii
from network import LoRa
from network import Bluetooth
bluetooth = Bluetooth()
bluetooth.start_scan(-1) # start scanning with no timeout
pycom.heartbeat(False) # Initialise built-in LED
# Initialise LoRa in LORAWAN mode
lora = LoRa(mode=LoRa.LORAWAN, device_class=LoRa.CLASS_C)
# Create an ABP authentication
# DEV ADDR=006a6ad1
# NWKSKEY=2cc23b080c141dc4abffb0fef7f7929c
# APPSKEY=7cc0a535f24adacb8095e1b070ea36ed
dev_addr = struct.unpack(">l", ubinascii.unhexlify('006a6ad1'))[0] # your device address here
nwk_swkey = ubinascii.unhexlify('2cc23b080c141dc4abffb0fef7f7929c') # your network session key here
app_swkey = ubinascii.unhexlify('7cc0a535f24adacb8095e1b070ea36ed') # your application session key here
# Join the network using ABP (Activation By Personalisation)
lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey))
# Remove all the non-default channels
for i in range(3, 16):
lora.remove_channel(i)
# Set the 3 default channels to the same frequency
lora.add_channel(0, frequency=868100000, dr_min=0, dr_max=5)
lora.add_channel(1, frequency=868100000, dr_min=0, dr_max=5)
lora.add_channel(2, frequency=868100000, dr_min=0, dr_max=5)
""" Your own code can be written below! """
# uplink sending and downlink receiving
i = 0;
while(True):
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # create a LoRa socket
s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) # set the LoRaWAN data rate
s.setblocking(False) # make the socket non-blocking
i +=1
# uplink sending
pkt = b'PKT #' + str(i)
# print("address"+ '||'.join(bluetooth.get_adv()))
print("address: {}".format(bluetooth.get_adv()))
s.send(pkt)
print(pkt + " sent")
time.sleep(6) # this dead-time is needed by the network to gather to your LoRa packets
# LED blinking
pycom.rgbled(0x000033)
time.sleep(1)
pycom.rgbled(0x000000)
# downlink receiving
rx, port = s.recvfrom(4096)
if rx:
print('Received: {}, on port: {}'.format(rx, port))
s.close() # close the LoRa socket
\ No newline at end of file
"""Python server consuming LoRaServer and InfluxDB APIs
Copyright (C) 2018 Eurac Research - Center for Sensing Solutions
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA"""
import requests
import warnings
import time
import json
# Global variables
loraAPI_url = "http://saocompute.eurac.edu/LoRaApp/api/"
influxAPI_url = "http://saocompute.eurac.edu/sensordb/query"
database = "loraton_sella" # the database name here
username = "sella" # your username here
password = "h7wGLgZ5MXtpvYEc" # your password here
dev_EUI = "0097da62c6b67443" # your device EUI here
TIME_SLEEP = 5
# JWT generation method needed to query the LoRa App Server API
def regenerateJWT(password,username):
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
url = loraAPI_url + 'internal/login'
data = {"password": password, "username": username}
response = postRequest(url, headers, data)
print(response.content)
if (response.status_code == 200):
new_jwt = json.loads(response.content.decode())['jwt']
return new_jwt
else:
print("Problems in generating a new JWT")
return -1
# Downlink building method
def sendDownlink(jwt, message):
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Grpc-Metadata-Authorization': 'Bearer ' + jwt
}
url = loraAPI_url + 'devices/' + dev_EUI + '/queue'
print(url)
data = {"deviceQueueItem": {"confirmed": True, "devEUI": dev_EUI,
"fCnt": getFrameUplink(jwt), "fPort": 2, "jsonObject": message}}
response = postRequest(url, headers, data)
if (response.status_code == 200):
print("Message sent")
else:
print(response.content)
print("Problems in sending message")
# Uplink-Downlink synchronization method
def getFrameUplink(jwt):
headers = {
'Accept': 'application/json',
'Grpc-Metadata-Authorization': 'Bearer ' + jwt
}
url = loraAPI_url + 'devices/' + dev_EUI + '/activation'
response = getRequest(url, headers)
frameuplink = json.loads(response.content.decode())['deviceActivation']['fCntUp']
if (response.status_code == 200):
#print("Frame uplink retrieved successfully")
return frameuplink
else:
print("Problem in retrieving the frame uplink.")
return 0
# GET request method
def getRequest(url, headers):
return requests.get(url, verify=False, headers=headers)
# POST request method
def postRequest(url, headers, data):
return requests.post(url, verify=False, headers=headers, json=data)
# Main body
warnings.filterwarnings("ignore")
current_jwt = regenerateJWT(password,username)
database = "?db="+database
username = "&u="+username
password = "&p="+password
first_loop = True
old_value = ""
if(current_jwt!=-1):
while (True):
warnings.filterwarnings("ignore")
# Query that retrieves the last value stored into the InfluxDB database
base_url = influxAPI_url + database + username + password
query_url = "SELECT device_name, value FROM device_frmpayload_data_message WHERE dev_eui='" + dev_EUI + "' ORDER BY time DESC LIMIT 1"
final_url = base_url + "&q=" + query_url
response = requests.get(final_url)
jsonresult = json.loads(response.content.decode())['results'][0]['series'][0]
print("DEV_NAME " + jsonresult['values'][0][1])
value = jsonresult['values'][0][2]
print("VALUE_STORED " + value)
if(first_loop):
old_value = value
first_loop = False
if(value != old_value):
downlink_msg = str('{"message":"'+value+'"}')
print(downlink_msg)
sendDownlink(current_jwt, downlink_msg)
old_value = value
else:
print("Same value")
print("----------------------------------------------------------")
time.sleep(TIME_SLEEP)
else:
print("Some problem occurred... exiting the script")
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment