// Sample RFM69 sender/node sketch, with ACK and optional encryption
// Sends periodic messages of increasing length to gateway (id=1)
// It also looks for an onboard FLASH chip, if present
// Library and code by Felix Rusu - felix@lowpowerlab.com
// Get the RFM69 and SPIFlash library at: https://github.com/LowPowerLab/
// with RC522 attached,it's important to keep SS of RC522 high, so that we can clear the SPI interface and make RF working.
// 2114/12/16 in Tr2 we will take out not used code, and transmit simple code, as well as receive
// In try 2 it keep on retry 2 times, (which is totally 3 tramsmitions for the same thing), after changing the gateway code with highpower 69HW, 
// it works normally.
/*2014/12/17
IN try3 I will first send out a RF message, then read RFID, then send out RFID
1st init RF, send a message through RF for testing,then stop RF, and init card reader, and read card ID, it works, but should we stop the interrupt
IN try4, sent RF, read card, and send RF again, by changing SS high to keep the device out....it works.

2015/01/02
Not sure what was the diference between try4 and try 5, but with moteino, some times initialization is very long, or fail
could it be an effect of SPI flash?

2015/01/03

to make a receive node from try 5
could easily hang, should be the time division between card reader and RF.when gate get ack, get get no card data,
and sometimes, card reader does not read. So, adding following for interlock on SPI:
digitalWrite(10, HIGH);
digitalWrite(SS_PIN,LOW);
not sure if need to re init card reader again
try to init 522 every time after switch, it can read the card, almost every time, still some time fail.
but don't understand what make note to sed out message
        
*/
#include <RFM69.h>
#include <SPI.h>


#define NODEID        2    //unique for each node on same network
#define NETWORKID     100  //the same on all nodes that talk to each other
#define GATEWAYID     1
//Match frequency to the hardware version of the radio on your Moteino (uncomment one):
#define FREQUENCY   RF69_433MHZ
#define ENCRYPTKEY    "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes!
#define IS_RFM69HW    //uncomment only for RFM69HW! Leave out if you have RFM69W!
#define ACK_TIME      30 // max # of ms to wait for an ack

//#define LED           9 // Moteinos have LEDs on D9
//#define FLASH_SS      8 // and FLASH SS on D8

#define SERIAL_BAUD   115200

int TRANSMITPERIOD = 500; //transmit a packet to gateway so often (in ms)
char payload[] = "Radio_out_testing";
char buff[20];
byte sendSize=17;
boolean requestACK = true;
//SPIFlash flash(FLASH_SS, 0xEF30); //EF30 for 4mbit  Windbond chip (W25X40CL)
RFM69 radio;

// define for RC522
//#include <SPI.h> //already included in 69HW
#include <MFRC522.h>
#define SS_PIN 7    //SS is marked as SDA
#define RST_PIN 6
MFRC522 mfrc522(SS_PIN, RST_PIN);        // Create MFRC522 instance.


//-------for data
byte UID_read[4];


void setup() {
  // init serial
  Serial.begin(SERIAL_BAUD);
  // To init 69HW, need fist to cut 522 off SPI
  pinMode(SS_PIN,OUTPUT);//SS_PIN is for RC522
  digitalWrite(SS_PIN,HIGH);// keep RC522 out of SPI
  digitalWrite(10, LOW);// enable RF
    radio.initialize(FREQUENCY,NODEID,NETWORKID);// spi init is in this function
#ifdef IS_RFM69HW
  radio.setHighPower(); //uncomment only for RFM69HW!
#endif
  radio.encrypt(ENCRYPTKEY);
  Serial.println("RFM69HW inited");
    if (radio.sendWithRetry(GATEWAYID, payload, sendSize))// try to send out a message for testing RF
     Serial.println(" sent out with ack ok!");
    else Serial.print(" nothing...");
  
  
  
  // To init 522 need to cut off 69HW from SPI, use the unselect() from RFM69
  //radio.unselect(); // can't work, since it's protected
  digitalWrite(10, HIGH);
  digitalWrite(SS_PIN,LOW);
  Serial.println("D10, high");
  mfrc522.PCD_Init();        // Init MFRC522 card
  Serial.println("RC522 inited");
  

  
}// end of setup


void loop() {
        digitalWrite(10, HIGH);
        digitalWrite(SS_PIN,LOW);
        delay(10);
        Serial.println("D10, high, RF OFF  522 ON");
          mfrc522.PCD_Init();        // Init MFRC522 card
          Serial.println("RC522 inited");
        delay(500);
        if ( mfrc522.PICC_IsNewCardPresent()){ 
         // Select one of the cards
            Serial.println("card detected");
        if ( ! mfrc522.PICC_ReadCardSerial())    return;
        
        Serial.print("                             Card UID:");    //Dump UID
        for (byte i = 0; i < mfrc522.uid.size; i++) {
          Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
          Serial.print(mfrc522.uid.uidByte[i], HEX);
        }// end of for 
        //==read UID into buffer========
        for(int i=0;i<4;i++){
        UID_read[i]=mfrc522.uid.uidByte[i];   
        }
        Serial.println();
        }// end of if
  // now change to radio
    digitalWrite(SS_PIN,HIGH);// keep RC522 out of SPI
    digitalWrite(10, LOW);// enable RF
    Serial.println("D7, high, RF ON  522 OFF");
    delay(500);
   if (radio.receiveDone())
  {
    Serial.print('[');Serial.print(radio.SENDERID, DEC);Serial.print("] ");
    //if (promiscuousMode)
    //{
    //  Serial.print("to [");Serial.print(radio.TARGETID, DEC);Serial.print("] ");
    //}
    for (byte i = 0; i < radio.DATALEN; i++)
      Serial.print((char)radio.DATA[i]);
    Serial.print("   [RX_RSSI:");Serial.print(radio.RSSI);Serial.print("]");
    
    if (radio.ACKRequested())
    {
      byte theNodeID = radio.SENDERID;
      radio.sendACK();
      Serial.print(" - ACK sent.");

      // When a node requests an ACK, respond to the ACK
      // and also send a packet requesting an ACK (every 3rd one only)
      // This way both TX/RX NODE functions are tested on 1 end at the GATEWAY
    /*  if (ackCount++%3==0)
      {
        Serial.print(" Pinging node ");
        Serial.print(theNodeID);
        Serial.print(" - ACK...");
        delay(3); //need this when sending right after reception .. ?
        if (radio.sendWithRetry(theNodeID, "ACK TEST", 8, 0))  // 0 = only 1 attempt, no retries
          Serial.print("ok!");
        else Serial.print("nothing");
      }
      */
    }// end of if (radio.ACKRequested())
    Serial.println();
 
  }// end of   if (radio.receiveDone())

   
}// end of loop


