#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h" //Activate for NRF-debug (printf_begin(); in setup() followed by radio.printDetails();)

#define CE_PIN   9
#define CSN_PIN 10
//
// Hardware configuration
//

// Set up nRF24L01 radio on SPI bus plus pins 9 & 10

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

// Radio pipe addresses 1 node to communicate.
//const uint64_t Address = 0xAABBCC22LL; //5-byte address "LL" is for long (if more than one node:)
//const uint64_t pipes[2] = { 0xAABBCC11LL, 0xAABBCC22LL }; //Pipes 1-5 must share the first 4 bytes. Only the least significant byte should be unique!
const uint64_t pipes[3] = { 0xBABBCCDD00LL, //Writing pipe (not used)
                            0xAABBCCDD11LL, //Meter A's writing pipe
                            0xAABBCCDD22LL  //Meter B's writing pipe
                          }; //First letter is address to energ-meter

float ReadData[3] = {0, 0, 0};
uint8_t TempStatus;
uint8_t CH;
uint8_t data[2];

void setup(void)
{

  Serial.begin(57600);
  //printf_begin();
  Serial.println("Start: ");
  //
  // Setup and configure rf radio
   radio.begin();
  
  //
  //********* Optional settings for nrf below see: http://maniacbug.github.io/RF24/classRF24.html
  //
  
  // increase the delay between retries & # of retries
  radio.setRetries(15,15);

  // reduce the payload size. (3 floates = 3*4=12 Bytes)
  radio.setPayloadSize(12);
  
  //Set speed of transmission (250kbps only works on the "+"-version!!! slower increases range!
  radio.setDataRate(RF24_250KBPS);
  
  //Set Power Amplifier (PA) level to high to increase range!
  radio.setPALevel(RF24_PA_HIGH);
  
  
  //Awesome feature that lets us send a package in return when receiving something without changing to transmitter!
  radio.enableAckPayload();
  
  //
  //********* End of optional settings********* 
  //
  
  //Addresses has to be set last!
  //radio.openWritingPipe(pipes[0]);
  radio.openReadingPipe(1,pipes[1]);
  radio.openReadingPipe(2,pipes[2]);

  //Start listening for incoming data
  radio.startListening();

  //
  // Dump the configuration of the rf unit for debugging
  //

   //read_register(CONFI); //read out the status register to decide which channel that's transmitting data //change RF24.h in libraries (remove "public:", "protected:" and change "private:" to "public:) to use this function!
   //Serial.println(radio.get_status(),BIN);
   //Serial.println(radio.read_register(RF_SETUP),BIN);
  Serial.println("Type: 2:3 to change the intervall of meter 2 to ~3s");
  //radio.writeAckPayload( 1, &AverageMax, sizeof(AverageMax) );
  //radio.writeAckPayload( 2, &AverageMax, sizeof(AverageMax) );
}

void loop(void)
{
    // if data is received to the nRF
    if ( radio.available() )
    {
      // Dump the payloads until we've gotten everything
      bool done = false;
      while (!done)
      {
        Serial.println(" ");
        //Serial.println(radio.get_status(),BIN); 
        // read out the status register to decide which channel that's transmitting data 
        //change RF24.h in libraries (remove "public:", "protected:" and change "private:" to "public:) to use this function!
        CH = 0;  
        CH = ((radio.get_status() & 0b00001110) >> 1); //extract bit 1-3 (the channels) to CH and move them one step to right to get it in decimal 
        
        // Fetch the payload, and see if this was the last one.
        done = radio.read( ReadData, sizeof(ReadData) );
        
        //Print out details
        Serial.print("Energy meter: ");
        Serial.println(CH); 
        
        //When meter reads 0W it sometimes shows ~6000W
        if(ReadData[2]<4000){
        Serial.print(ReadData[0],0);
        Serial.println(" V");
        Serial.print(ReadData[1],1);
        Serial.println(" W");
        Serial.print(ReadData[2],2);
        Serial.println(" W-Max");
        }
        else{
          Serial.print(ReadData[0],0);
          Serial.println(" V");
          Serial.print(0.0,0);
          Serial.println(" W");
        }
        delay(20);
        //Reset STATUS-register:
        //radio.write_register(STATUS, _BV(RX_DR) | _BV(TX_DS) | _BV(MAX_RT) );
      }
     }

}

//Interrupt ocures whenever you type anything in the serial-monitor. 
//To change the data sending interval of an energy meter, in the serial monitor type:
//2:3
//to change the channel 2-energy meter to ~3s interval. 
void serialEvent() {
  while (Serial.available()) {
    // Reads the the bytes until it reaches an non-integer value ":"
    int CH = Serial.parseInt();
    byte skipp = Serial.read();
    int AverageMax = Serial.parseInt();
    if(Serial.available()==false && CH >0 && CH < 6 && AverageMax >0 && AverageMax <10000){
      // Add an ack packet for the next time around
      radio.writeAckPayload( CH, &AverageMax, sizeof(AverageMax) );
      
      Serial.print("Intervall on meter: ");
      Serial.print(CH);
      Serial.print(" will change to: ~");
      Serial.print(AverageMax);
      Serial.println("s on next transmission!");
    }
    else{
      while (Serial.available()) {
        skipp = Serial.read();
      }
      Serial.println("Wrong format! Type: 2:3 to change the intervall of meter 2 to ~3s");
    }
    
  }
  
}


// vim:cin:ai:sts=2 sw=2 ft=cpp