#include <RFM12B_arssi.h>
#include <SPI.h>
//#include <SPIFlash.h>

#define NODEID      1
#define NETWORKID   1
#define GATEWAYID   1
#define FREQUENCY   RF12_915MHZ //Match this with the version of your Moteino! (others: RF69_433MHZ, RF69_868MHZ)
#define KEY         "thisIsEncryptKey" //has to be same 16 characters/bytes on all nodes, not more not less!
#define RFM_CS_PIN  18 // RFM12B Chip Select Pin
#define RFM_IRQ_PIN 2  // RFM12B IRQ Pin
#define LED         9
#define SERIAL_BAUD 115200
#define ACK_TIME    30  // # of ms to wait for an ack

int TRANSMITPERIOD = 1000; //transmit a packet to gateway so often (in ms)
byte sendSize=0;
//SPIFlash flash(8, 0xEF30); //EF40 for 16mbit windbond chip
RFM12B radio;
long lastPeriod = -1;

typedef struct {		
  int           nodeId; //store this nodeId
  unsigned long uptime; //uptime in ms
  uint16_t      vcc;    // current Arduino VCC power 
  int16_t       temp;   // internal Arduino temperature 
} Payload;
Payload theData;

uint16_t vcc=0;
int16_t temperature=0;
volatile uint8_t  adc_irq_cnt;


/* ======================================================================
Function: Interrupt routine for ADC
Purpose : Fired when ADC interrupt occured (mainly end of convertion)
Input   : 
Output  : 
Comments: Used by readADCLowNoise
====================================================================== */
ISR(ADC_vect)  
{
  // Increment ADC sample count 
  // will check after wake up
  adc_irq_cnt++;
}

/* ======================================================================
Function: readADCLowNoise
Purpose : Read Analog Value with reducing noise for more accuracy
Input   : true return the average value, false return only the sum
Output  : average value read
Comments: hard coded to read 8 samples each time
          ADMUX Channel must have been set before this call
====================================================================== */
uint16_t readADCLowNoise(bool average)
{
  uint8_t low, high;
  uint16_t sum = 0;
  
  // Start 1st Conversion, but ignore it, can be hazardous
  ADCSRA |= _BV(ADSC); 
  
  // as we will enter into deep sleep mode, flush serial to avoid
  // data loss or corrupted
  Serial.flush();

  // wait for first dummy conversion
  while (bit_is_set(ADCSRA,ADSC));

  // Initialize ADC sample counter
  adc_irq_cnt = 0;

  // Want to have an interrupt when the conversion is done
  ADCSRA |= _BV( ADIE );
  
  // Loop thru samples
  do
  {
    // Enable Noise Reduction Sleep Mode
    set_sleep_mode( SLEEP_MODE_ADC );
    sleep_enable();

    // Wait until conversion is finished 
    do
    {
      // The following line of code is only important on the second pass.  For the first pass it has no effect.
      // Ensure interrupts are enabled before sleeping
      sei();
      // Sleep (MUST be called immediately after sei)
      sleep_cpu();
      // Checking the conversion status has to be done with interrupts disabled to avoid a race condition
      // Disable interrupts so the while below is performed without interruption
      cli();
    }
    while (bit_is_set(ADCSRA,ADSC));

    // No more sleeping
    sleep_disable();
    // Enable interrupts
    sei();
    
    // read low first
    low  = ADCL;
    high = ADCH;
    
    // Sum the total
    sum += ((high << 8) | low);
    
  }
  // Hard coded to read 8 samples
  while (adc_irq_cnt<8);
  
  // No more interrupts needed for this
  ADCSRA &= ~ _BV( ADIE );
  
  // Return the average divided by 8 (8 samples) if asked
  return ( average ? sum >> 3 : sum );
  
}

/* ======================================================================
Function: readVcc
Purpose : Read and Calculate V powered, the Voltage on Arduino VCC pin
Input   : -
Output  : value readed in mV
Comments: ADC Channel input is modified
====================================================================== */
uint16_t readVcc() 
{
  uint16_t value; 
  
  // Indicate RFM12B IRQ we're doing conversion 
  // so it should not doing any RSSI acquisition in the interval
  // we're using the ADC
  radio.noRSSI(true);
  
  // Read 1.1V reference against AVcc
  // REFS1 REFS0          --> 0 1, AVcc external ref. -Selects AVcc external reference
  // MUX3 MUX2 MUX1 MUX0  --> 1110 1.1V (VBG)         -Selects channel 14, bandgap voltage, to measure
  ADMUX = (0<<REFS1) | (1<<REFS0) | (0<<ADLAR) | (1<<MUX3) | (1<<MUX2) | (1<<MUX1) | (0<<MUX0);

  // Take care, changing reference from VCC to 1.1V bandgap can take some time, this is due
  // to the fact that the capacitor on aref pin need to discharge or to charge 
  delay(10);  

  // read value
  value = readADCLowNoise(true);
  
  // we done with ADC
  radio.noRSSI(false);
  
  // Vcc reference in millivolts
  // can be adjusted 1100L if 1V1 reference but has tolerance of 10% so you can measure it
  // and change it there, or better use it as parameter
  return ( (( 1023L * 1100L) / value) ); 
}

/* ======================================================================
Function: readInternalTemperature
Purpose : Read and Calculate Arduino Internal Temperature
Input   : -
Output  : value readed in °C (*10) ie 210 is 21.0 °C
Comments: ADC Channel input is modified
====================================================================== */
int16_t readInternalTemperature(void)
{
  uint16_t adc_value; 
  float temp;
  
  // Indicate RFM12B IRQ we're doing conversion 
  // so it should not doing any RSSI acquisition in the interval
  // we're using the ADC
  radio.noRSSI(true);
  
  // Read 1.1V reference against AVcc
  // REFS1 REFS0          --> 1 1, 1V1 internal ref.  -Selects AVcc external reference
  // MUX3 MUX2 MUX1 MUX0  --> 1000 Temp               -Selects channel 8, internal temperature 
  ADMUX = (1<<REFS1) | (1<<REFS0) | (0<<ADLAR) | (1<<MUX3) | (0<<MUX2) | (0<<MUX1) | (0<<MUX0);

  // Take care, changing reference from VCC to 1.1V can take some time, this is due
  // to the fact that the capacitor on aref pin need to discharge or to charge 
  delay(10);  

  // read value
  adc_value = readADCLowNoise(true);
  
  // we done with ADC
  radio.noRSSI(false);
  
  // The offset of 324.31 could be wrong. It is just an indication.
  temp = (adc_value - 324.31 ) / 1.22;

  // The returned temperature is in degrees Celcius.
  return ((int16_t) (temp*10));
}

/* ======================================================================
Function: setup
Purpose : Configuration of Arduino I/O and other stuff
Input   : -
Output  : -
Comments: 
====================================================================== */
void setup() {
  Serial.begin(SERIAL_BAUD);
  
  Serial.println(F("RFM12B Node Sample"));

  
  // Try to detect and Init On moteino RF12 device SS is D10 and IRQ D2 (default)
  // So the parameters are optional
  // if radio.isPresent()
  if ( radio.isPresent( RFM_CS_PIN, RFM_IRQ_PIN) )
    Serial.println(F("RFM12B Detected OK!"));
  else
    Serial.println(F("RFM12B Detection FAIL! (is chip present?)"));
  
  radio.Initialize(NODEID, FREQUENCY, NETWORKID, 0);
  //radio.Encrypt((byte*)KEY);
  
  Serial.print(F("Recieving at "));
  Serial.print(FREQUENCY==RF12_433MHZ ? 433 : FREQUENCY==RF12_868MHZ ? 868 : 915);
  Serial.println(F("Mhz..."));

 
  
}

/* ======================================================================
Function: loop
Purpose : really need explanations ???
Input   : -
Output  : -
Comments: 
====================================================================== */
void loop() {
  //process any serial input
  
  //check for any received packets
  if (radio.ReceiveComplete())
  {
    if (radio.CRCPass())
    {
      int8_t rssi, k;
      
     Serial.println ("Receiving data...");
      
     for (byte i = 0; i < *radio.DataLen; i++) //can also use radio.GetDataLen() if you don't like pointers
        Serial.print((char)radio.Data[i]);

      if (radio.ACKRequested())
      {
        radio.SendACK();
        Serial.print(" - ACK sent");
      }
      Serial.println ("");
     
    }
  }
  
 
}

