from loranode import RN2483Controller
import platform
from commands import *
import time
if __name__ == "__main__":
    set_debug_level(Level.DEBUG)
    port = "COM3"
    nwkskey = "58AA52E96035Axxxxxxxxxxxxxxxxxxxx"
    appskey = "381B1C9206E9BE9xxxxxxxxxxxxxxxxxxx"
    devaddr = "B639xxxx"
    
    lc = None
    
    try:
      
      lc = RN2483Controller(port)
      if lc.test():
        printd("[+] Connected to LoRa RN2483 device", Level.INFO)
        lc.serial_sr(CMD_GET_VERSION)
        lc.serial_sr(CMD_GET_HWEUI)
        lc.get_freq()
      else:
        printd(clr(Color.YELLOW, "[-] Failed to get version from LoRa device"), Level.WARNING)
    except Exception, e:
      print "Error: " + str(e)
    if lc is None:
      printd(Color.YELLOW, "Error: cannot connect to device")
      exit()
    lc.set_adr(False)
    lc.set_pwr(15)
    lc.serial_sr(CMD_MAC_PAUSE)
    lc.serial_sr(CMD_SET_SF, "sf12") 
    lc.serial_sr(CMD_MAC_RESUME)
    
    if lc.join_abp(nwkskey, appskey, devaddr):
        printd("[+] Connected to gateway", Level.INFO)
        
        
        printd("[+] Sending packet #1", Level.INFO)
        timeStr = time.strftime("%H%M", time.gmtime())
        if lc.send(timeStr, ack=False):
          printd(clr(Color.GREEN, "[+] Send-1 succeeded"), Level.CRITICAL)
        else:
          printd(clr(Color.RED, "[+] Send-1 failed"), Level.CRITICAL)
        time.sleep(15)
        
        printd("[+] Sending packet #2", Level.INFO)
        timeStr = time.strftime("%H%M", time.gmtime())
        if lc.send(timeStr, ack=False):
          printd(clr(Color.GREEN, "[+] Send-2 succeeded"), Level.CRITICAL)
        else:
          printd(clr(Color.RED, "[+] Send-2 failed"), Level.CRITICAL)
        time.sleep(15)
        del lc
        exit()
    printd(clr(Color.RED, "[-] Test failed"), Level.CRITICAL)
    del lc