#include <Arduino.h>
#include "LoRaRadio.h"
#include "PayloadFormatter.h"

u1_t dio[3] = {26,33,32};

void os_getArtEui (u1_t* buf) { }
void os_getDevEui (u1_t* buf) { }
void os_getDevKey (u1_t* buf) { }

static u1_t NWKSKEY[16] = { 0x1F, 0x9E, 0xE2, 0x7A, 0xC8, 0xBA, 0xE8, 0xEA, 0xF5, 0xC2, 0x5E, 0x47, 0x5D, 0xE0, 0x77, 0x55 };
static u1_t APPSKEY[16] = { 0x3B, 0x89, 0x86, 0x96, 0xBB, 0xAA, 0x38, 0x1E, 0x1F, 0xC4, 0xAD, 0x03, 0xEF, 0x3F, 0x56, 0x12 };
static u4_t DEVADDR = 0x260113D3;//0x03FF0001 ; // <-- Change this address for every node!

unsigned long lapse(0);

PinMap pinMap(18, LMIC_UNUSED_PIN, 14, dio);
LoRaRadio radio(pinMap);

PayloadFormatter pf(1,4);
DateTime payloadDate(2020,12,26,8,42);
double temps[4] = {21.31, 20.35, 21.25, 21.36};

void setup()
{
  Serial.begin(115200);
  Serial.println("Starting setup");
  radio.init();
  radio.setTTNSession(0x1, DEVADDR, NWKSKEY, APPSKEY);
  radio.setRadioEUChannels();
  radio.setMCUClockError();
  lapse = millis();
  Serial.println("Ending setup");
}

void loop()
{
  radio.run();
  if(millis() - lapse > 30000)
  {
    Serial.printf("Building payload\n");
    pf.startSession(1);
    uint8_t *p(NULL);
    uint8_t size = pf.buildPayload(&p, &payloadDate,temps);
    pf.endSession();
    Serial.printf("Sending data\n");
    radio.send(1, p, size);
    lapse = millis();
  }
}
