/**
 * Cet exemple correspond à l'application de test de la bibliothèque MeasureUnit qui
 * permet de calculer la température qui est fonction de la résistance d'une matrice de thermistance 
 * 
 * Anatole SCHRAMM-HENRY
 * 17/12/2019
 */
#include <Wire.h>
#include <WiFi.h>
#include <RTClib.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "MeasureUnit.h"
#include "PayloadFormatter.h"
#include "Ads1115.h"
#include "LoRaRadio.h"

#define RADIO_ENABLED
#define PUSH_BUTTON 0

uint8_t analogInput[] = {0,1,2,3,4,5,6,7};
double *tempArray = NULL;
char screenTxt[30] = "LES ALEAS DU DIRECT";

/*
 * Liste des offsets trouvés
 * |  -0.49  |  0.36  |  -0.29  |  0.38  |  0.44  |  -0.35  |  -0.21  |  0.14  |
 * |  -0.72  |  0.07  |  -0.52  |  -0.01  |  2.38  |  -0.65  |  -0.44  |  -0.11  |
 * |  -0.99  |  -0.06  |  -0.74  |  2.24  |  0.73  |  -0.86  |  -0.68  |  0.35  |
 * |  -0.53  |  -0.49  |  -0.27  |  1.17  |  0.07  |  0.14  |  -0.02  |  -0.08  |
 * |  -0.62  |  -0.73  |  1.58  |  0.42  |  -0.27  |  0.09  |  -0.25  |  -0.21  |

 * 
 */

//Objet de calcule de la temperature
ThermistorSetting thermistorSetting(3380, 10000);
//ThermistorSetting thermistorSetting(3650, 470);
//AdcSetting adcSetting(3300.0, 12, 310, 3);
AdcSetting adcSetting(3310, 15, 6, 10);
Ads1115 adc;
MeasureUnit measureUnit(analogInput, 8, 990, thermistorSetting, adc);
//MeasureUnit measureUnit(analogInput, 8, 99, thermistorSetting, adc);
//Objet de création des trames LoRa
PayloadFormatter payloadFormatter(2,4);

RTC_DS3231 rtc;
DateTime payloadDate;
TwoWire sc(1);
Adafruit_SSD1306 display(128,64,&sc, 16);

boolean data(false);
uint8_t *payload(NULL), _timeCounter(0), size(0), _channel(0);
boolean calibrer(false);
unsigned long _time(0);
/*
 * Radio Part
*/
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!

u1_t dio[3] = {26,33,32};
PinMap pinMap(18, LMIC_UNUSED_PIN, 14, dio);
LoRaRadio radio(pinMap);

void downlinkHandler(u1_t length, u1_t dataBeg, u1_t *data)
{
  Serial.println("Downlink received : ");
  for(uint8_t i(0); i < length; i++)
  {
    Serial.printf("%u -> %d\n",i,data[dataBeg + i]);
  }
  Serial.println();

  //Action en fonction de l'octet de commande
  switch(data[dataBeg+0])
  {
    case 0x01://Mise à jour de l'heure
      //Octets suivants:
      //2 jour 3 mois 4 année 5 heures 6 minutes
      if(length == 6)
      {
        Serial.printf("dd: %u, m: %u, yyyy: %d, hh: %u, mm: %u\n", data[dataBeg+1], data[dataBeg+2], data[dataBeg+3]+2000, data[dataBeg+4], data[dataBeg+5]);
      }
      else
        Serial.println("Action réglage RTC : paramètres insuffisants");
      break;
    case 0x02:
      memcpy(screenTxt,(data+dataBeg+1), length-1);
      screenTxt[length-1] = '\0';
      display.stopscroll();
      display.clearDisplay();
      display.setTextColor(WHITE);
      display.setCursor(0,15);
      display.setTextSize(2);
      display.print(screenTxt);
      display.display();
      display.startscrollleft(0,16);
      break;
    default:
      Serial.println("Action inconnue");
  }
}

void setup() {
  Serial.begin(115200);
  delay(1000);
  Serial.println("Start setup");
  WiFi.mode(WIFI_OFF);
  pinMode(PUSH_BUTTON, INPUT);
  //Partie concernant l'initialisation de la radio
  #ifdef RADIO_ENABLED
  radio.init();
  radio.setTTNSession(0x1, DEVADDR, NWKSKEY, APPSKEY);
  radio.setRadioEUChannels();
  /*
   * La directive setMCUClockError() permet de laisser une fenêtre plus grande pour le slot de
   * réception (Downlink). En effet ce slot doit durer 2 secondes et il peut durer moins en raison
   * d'imprécisions d'horloge.
   */
  radio.setMCUClockError(50);
  radio.setDownlinkHandler(&(downlinkHandler));
  #endif
  //Adc init
  adc.setAdcSetting(adcSetting);
  //measureUnit.setGlobalTempOffset(-17);
  _time = millis();
  
  if(rtc.begin())Serial.println("RTC Ok!");
  else Serial.println("RTC Fail!");
  sc.begin(4, 15);
  if(display.begin(SSD1306_SWITCHCAPVCC,0x3C))
  {
    Serial.println("SCREEN Ok!");
    display.clearDisplay();
    display.setTextColor(WHITE);
    display.setCursor(0,15);
    display.setTextSize(2);
    display.print(screenTxt);
    display.display();
  }
  else Serial.println("SCREEN Fail!");
  
  display.startscrollleft(0,16);
  Serial.println("End setup");
  measureUnit.init();
  Serial.println("|   T1    |   T2    |   T3    |   T4    |   T5    |   T6    |   T7    |   T8    |");

}

void loop() {
  //Version asynchrone :
  measureUnit.startTemperatureMeasurement();

  //On peut tester si la conversion est terminée avec :
  //if(measureUnit.isMeasurementReady())
  
  //measureUnit.getAsyncTemperatures() renvoie NULL si la recupération de la température n'est pas terminée
  tempArray = measureUnit.getAsyncTemperatures();
  
  if(tempArray != NULL)
  {
    Serial.print("|");
    for(int i(0); i < 8; i++)
    {
      if(i != 7)
      {
        Serial.print("  ");Serial.print(tempArray[i],2);Serial.print("  |");
      }
      else
      {
        Serial.print("  ");Serial.print(tempArray[i],2);Serial.print("  |");
      }
    }

    //On affiche la trame associée:
    payloadFormatter.startSession(1);
    payloadDate = rtc.now();
    size = payloadFormatter.buildPayload(&payload, &payloadDate,tempArray);
    if(size != 0)
    {
      //Serial.print("LoRa packet --> ");Serial.print("size : ");Serial.print(size);Serial.println(" bytes");
      for(int i(0); i < size; i++)
      {
        payload[i] <= 0x0F ? Serial.print("0") : Serial.print(""); Serial.print(payload[i], HEX); Serial.print(" ");
      }
      Serial.printf("|%u-%u-%u %u:%u \n", payloadDate.day(),payloadDate.month(),payloadDate.year(),payloadDate.hour(),payloadDate.minute());
    }
    else
      Serial.print("Failed to build LoRa packet");
    
    payloadFormatter.endSession();
    
    #ifdef RADIO_ENABLED
    if(_timeCounter == 30 && size != 0)
    {
      _timeCounter = 0;
      Serial.printf("Sending data\n");
      radio.send(1, payload, size);
    }
    
    _timeCounter++;
    #endif
  }

  //On effectue la calibration
  if(digitalRead(PUSH_BUTTON) == 0)
  {
    delay(500);
    measureUnit.startOffsetComputing();
  }
  #ifdef RADIO_ENABLED
  radio.run();
  #endif
  measureUnit.run();
}
