IoT Cisco LoRaWan Project

From packets2photons
Jump to navigation Jump to search

Cisco Gateway configuration

Command to make pkt_forwarder work:

pkt_forwarder -c /tools/config.json -g/dev/ttyS1 &

Links to code

Client side

Server side


Raspberry Pi configuration

Some early sample LoraWan IoT code:

"""
Example for using the RFM9x Radio with Raspberry Pi and LoRaWAN

Adapted by: https://learn.adafruit.com/lora-and-lorawan-for-raspberry-pi
And from work by Author: Brent Rubell for Adafruit Industries
"""
import threading
import time
import subprocess
import busio
from digitalio import DigitalInOut, Direction, Pull
import board
# Import thte SSD1306 module.
import adafruit_ssd1306
# Import Adafruit TinyLoRa
from adafruit_tinylora.adafruit_tinylora import TTN, TinyLoRa
import os
import glob
import base64

print ("Directory cleanup")
os.system('rm /home/pi/camera/*')
print ("Taking photo")
os.system('raspistill -o /home/pi/camera/cam.jpg')
print ("Downscaling image")
#os.system('convert -resize 10% cam.jpg cam.jpg')
os.system('mogrify -quality 80 -resize 80 /home/pi/camera/cam.jpg')
#print ("removing cam.jpg")
#os.system('rm /home/pi/camera/cam.jpg')

def split_by_n(seq, n):
#    A generator to divide a sequence into chunks of n units.
    while seq:
        yield seq[:n]
        seq = seq[n:]


# Button A
btnA = DigitalInOut(board.D5)
btnA.direction = Direction.INPUT
btnA.pull = Pull.UP

# Button B
btnB = DigitalInOut(board.D6)
btnB.direction = Direction.INPUT
btnB.pull = Pull.UP

# Button C
btnC = DigitalInOut(board.D12)
btnC.direction = Direction.INPUT
btnC.pull = Pull.UP

# Create the I2C interface.
i2c = busio.I2C(board.SCL, board.SDA)

# 128x32 OLED Display
display = adafruit_ssd1306.SSD1306_I2C(128, 32, i2c, addr=0x3c)
# Clear the display.
display.fill(0)
display.show()
width = display.width
height = display.height

# TinyLoRa Configuration
spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
cs = DigitalInOut(board.CE1)
irq = DigitalInOut(board.D22)
rst = DigitalInOut(board.D4)

# TTN Device Address, 4 Bytes, MSB
devaddr = bytearray([ 0x00, 0x00, 0x00, 0x00 ])
# TTN Network Key, 16 Bytes, MSB
nwkey = bytearray([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ])

# TTN Application Key, 16 Bytess, MSB
app = bytearray([ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ])

    # Initialize ThingsNetwork configuration
ttn_config = TTN(devaddr, nwkey, app, country='AU')
# Initialize lora object
lora = TinyLoRa(spi, cs, irq, rst, ttn_config)
# 2b array to store sensor data

count=0
lora.frame_counter = 0
txchars = 58

with open('/home/pi/camera/cam.jpg', "rb") as imageFile:
    base64str = base64.b64encode(imageFile.read())
    length = (len(base64str))
    #start_del = ("Beginning of Base64 image, estimated " +str (length) + " chars ==\n")
    #print ("Filename:" + (file))
    #print (file)
    start_del = ("Beginning of Base64 image==")
    print (base64str)
    print ("The file is: " + str(length) + " chars")
    num_lines = length/txchars
    print (str(length) + "chars so " + str(num_lines) + " lines to send")
    end_del = ("==End of Base 64 image")

packet = None

while packet == None:

    # check for packet rx
    #packet = rfm69.receive()
    if packet is None:
        print ("test1")
        info = list(split_by_n(base64str, txchars)) 
        print ("test2")
        #print (info)
        print (start_del)
        
        send_file = bytes((start_del), "utf-8")
        lora.send_data(send_file, len(send_file), lora.frame_counter)
        lora.frame_counter += 1
       
        time.sleep(2)
        for x in info:
            #print ((x), end = '')
            print (x)
            send_file = bytes(str(x), "utf-8")
            #send_file = str(bytes((x)), "utf-8")
            lora.send_data(send_file, len(send_file), lora.frame_counter)
            lora.frame_counter += 1
            time.sleep(0.2)

        send_file = bytes((end_del), "utf-8")
        lora.send_data(send_file, len(send_file), lora.frame_counter)
        lora.frame_counter += 1
        print (end_del)
        packet = 1

    time.sleep(1)

'''
    send_file = bytes((info), "utf-8")
    #rfm69.send(send_file)

    lora.send_data(send_file, len(send_file), lora.frame_counter)
    lora.frame_counter += 1
    time.sleep(1)

RAK Node Tx



Adafruit Node Tx



Server image recieve


import time
import ttn
import base64
import re
import os

start_del = ("=SD")
end_del = ("=KA")
tx_success = ("=txSuccess")

app_id = "dave-rpi-node"
access_key = "ttn-account-v2.lIeThVwIHD_NBSE0W0W4mHY5QDnAqYkgycVb2FdCLPA"

dev_id='null'

process_string = str("rm /home/ubuntu/zr*")
os.system(process_string)

process_string = str("/home/ubuntu/clean_outputs")
os.system(process_string)

def uplink_callback(msg, client):

    try:
        packet_text = (re.findall(r'\'(.*?)\'', str(msg.payload_fields)))
        packet_text = (', '.join(packet_text))
        #print (payload)
        rec = packet_text.split(",")
        filename=rec[0]
        #f=open(rec[0],"a+")
        #f.write(rec[1]+","+rec[2]+"\n")

        if (rec[1] == start_del):
            process_string = str("rm /home/ubuntu/" + rec[0])
            print("Start Del Recieved")
            os.system(process_string)

        elif (rec[1] == end_del): #if we recieve a keep alive
            process_string = str("/home/ubuntu/process_output " + str(filename))
            print (process_string)
            os.system(process_string)
            #print the contents of missing
            send_line = (str(rec[0]))
            dev_id = str(rec[0])
            print(dev_id)
            dev_id = dev_id[:3]
            print(dev_id)
            missing_filename=("missing"+str(filename))
            if (os.stat(missing_filename).st_size > 0):
                send_line = str(rec[0])
                m=open(missing_filename,"r")
                m1=m.readlines()
                i=0
                for l in m1:
                    send_line = send_line + "," + str(l.strip())
                    i+=1
                    if (i%6==0):
                        i=0
                        send_line = str(send_line.strip())
                        print("TX: " + send_line)
                        payload=base64.b64encode(send_line)
                        mqtt_client.send(dev_id, payload, port=1)
                        #time.sleep(3)
                        send_line = str(rec[0])
                
                if (i>0):
                    send_line = str(send_line.strip())
                    send_line = (send_line + ",0")
                    print("TX: " + send_line)
                    payload=base64.b64encode(send_line)
                    mqtt_client.send(dev_id, payload, port=1)
                
                #time.sleep(5)

            else:
                send_line = rec[0] + "," + tx_success
                print("TX: " + send_line)
                payload=base64.b64encode(send_line)
                mqtt_client.send(dev_id, payload, port=1)
                #time.sleep(4)

        else: #this is not the end or start frame delimiter
            f=open(rec[0],"a+")
            f.write(rec[1]+","+rec[2]+"\n")
            print (packet_text)
    
    except UnicodeError:
        print("string is not UTF-8")


#def downlink_callback(mid, client):
#  print("downlink called")
#  dummy=0
i = 0
handler = ttn.HandlerClient(app_id, access_key)

# using mqtt client
mqtt_client = handler.data()
mqtt_client.set_uplink_callback(uplink_callback)
#mqtt_client.set_downlink_callback(downlink_callback)
mqtt_client.connect()
while True:
    time.sleep(0.1)
#mqtt_client.close()
#  print("Sending\n")
#  dev_id='pyimage'
  #payload={ "led_state": "on", "counter": 1 }
#  payload=base64.b64encode(b'a')
#  mqtt_client.send(dev_id, payload, port=1)

Server spatial Multiplexing code