import pycom
import ubinascii
import socket
import struct
import time

from network import LoRa
from generateID import generateID

# global dictionary
_G = {'RGB': 0x001100, 'DR': 5, 'SLEEP': 300}

# turn off lopy heartbeat (blinking led)
pycom.heartbeat(False)

lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)

# create an ABP authentication parameters
dev_addr = struct.unpack(">l", ubinascii.unhexlify(pycom.nvs_get("dev_addr")))[0]
nwk_swkey = ubinascii.unhexlify(pycom.nvs_get("nwk_swkey"))
app_swkey = ubinascii.unhexlify(pycom.nvs_get("app_swkey"))
# join a network using ABP (Activation By Personalization)
lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey))

# Blinking blue led if connecting
while not lora.has_joined():
    pycom.rgbled(0x000011)
    time.sleep(1)
    pycom.rgbled(0x000000)
    print("has not joined")
    time.sleep(1)

# Blue led when connected
pycom.rgbled(0x000011)
print("has joined")

# create socket to be used for LoRa communication
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setblocking(False)

def set_sleep_time(dr):
    if dr == 5:
        _G['SLEEP'] = 6
    if dr == 4:
        _G['SLEEP'] = 11
    if dr == 3:
        _G['SLEEP'] = 19
    if dr == 2:
        _G['SLEEP'] = 35
    if dr == 1:
        _G['SLEEP'] = 75
    if dr == 0:
        _G['SLEEP'] = 132

counter = 0
while True:
    if _G['DR'] < 0:
        pycom.rgbled(0x110000)
        time.sleep(0.5)
        pycom.rgbled(0x000000)
        time.sleep(0.5)
        pycom.rgbled(0x110000)
        time.sleep(0.5)
        pycom.rgbled(0x000000)
        time.sleep(0.5)
        pycom.rgbled(0x110000)
        time.sleep(0.5)
        pycom.rgbled(0x000000)
        time.sleep(0.5)
        break

    pycom.rgbled(0x001100)

    if counter == 0:
        s.setsockopt(socket.SOL_LORA, socket.SO_DR, _G['DR'])

    id = generateID()
    uplink = bytearray(id)

    # 00 01 - 1st location (nálepkova 71)
    # 00 02 - 2nd location (café louka)
    # 00 03 - 3rd location (rozhledna holedná)
    # 00 04 - 4th location (leso bar)
    # 00 05 - 5th location (nalepkova 71 snowing)
    # 00 06 - 6th location (campus inside/outside)
    # 00 07 - 7th location (efekt dance brno inside)
    # 00 08 - 8th location (efekt dance brno outside)
    # 00 09 - 9th location (uvoz)
    # 00 10 - 10th location (socha jana skacela)
    # 00 11 - 11th location (spilberk)
    # 00 12 - 12th location (nalepkova 71 outside)
    # 00 13 - 13th location (žabovřesky)
    uplink.extend(bytes([00, 01]))

    s.send(uplink)

    set_sleep_time(_G['DR'])
    time.sleep(_G['SLEEP'])

    counter = counter + 1
    if counter > 3:
        _G['DR'] = _G['DR'] - 1
        counter = 0
