
#include <RFM69.h>
#define FREQUENCY     RF69_433MHZ
#define IS_RFM69HW    //uncomment only for RFM69HW! Leave out if you have RFM69W!
#define ENCRYPT_KEY "sampleEncryptKey"
#define ADDRESS 1
#define NETWORK_ID 99
#define BURST_REPLY_TIMEOUT_MS 350
int TARGETID = 2;//the node number of the first listenmode node
int Total_Nodes = 2; //  this is the number of nodes the gateway will poll
RFM69 radio;
int retryCounter;
int targetNODE;
int nodeAttempts = 9; // if no contact on 1st poll - this is the number of retries

typedef struct {
  int sensorReading;
  int sensorReadingL;  
  
} Node;
Node theData;



void setup() {
Serial.begin(115200);
Serial.println("AT SETUP");
delay (5); 

radio.initialize(FREQUENCY, ADDRESS, NETWORK_ID);
radio.encrypt(ENCRYPT_KEY);
#ifdef IS_RFM69HW
  radio.setHighPower(); //uncomment only for RFM69HW!
#endif
radio.writeReg(0x03,0x68);      //RegBitrateMsb 1200 bitrate
radio.writeReg(0x04,0x2B);      //RegBitrateLsb 1200 bitrate
radio.writeReg(0x05,0x00);      //RegFdevMsb     2000 
radio.writeReg(0x06,0x52);      //RegFdevLsb     2000
radio.writeReg(0x19,0x40|0x10|0x05);      //RegRxBw  DccFreq:010, RxBw_Mant:24, RxBw_Exp:5 
radio.writeReg(0x18,0x00|0x00|0x01);      //RegLna  LnaZin:50ohm, LowPower:Off, CurrentGain:MAX 

}

char payload[] = "1000"; //IMPORTANT THIS PAYLOAD IS FOR A DYNAMIC REQUEST 
char conTrlON []  = "747"; //NOT USED IN THIS ITERATION 
char turnOFF []  = "618"; //NOT USED IN THIS ITERATION 


void loop() {
  delay(5000);
Serial.println("MAIN LOOP");
  delay (50);
retryCounter = 0;

if (TARGETID >= (Total_Nodes + 2)){ /* Node 1 is the gateway, Node 2 and 3 (and any others as defined by Total_Nodes prior to setup() )
            are pinged.  if the target = (Total_Nodes + 2 - you have incremented past total of target nodes, 
            return to the first node  (which is 2 - see next line) */
        TARGETID = 2; //1st node in series
  }

 if (TARGETID <= 1){ // if the target node is 0 or 1
        TARGETID = 2;   // skip and start at 2  
      }
           
       while  (TARGETID <= Total_Nodes + 1){ // set the number of nodes to ping to Total_Nodes (the +1 covers the gateway node 1)
          radio.listenModeSendBurst(TARGETID, payload, sizeof(payload)); // send payload "1000"
          bool replied = false;
          long start = millis();
          while (millis() - start < BURST_REPLY_TIMEOUT_MS) {
            if (radio.receiveDone()) { 
              replied = true; 
              
               Serial.println("pinging this node");
               delay (10); 
                Serial.println (TARGETID);
                delay (10); 
                     
                 theData = *(Node*)radio.DATA;
                 if((theData.sensorReading) >= TARGETID*1000){ // make sure data is from actual node
                  Serial.println("received data");
                  
                      Serial.println(theData.sensorReading);
                      delay (10);  
                      Serial.println(theData.sensorReadingL);
                      delay (10); 
                      Serial.flush();
                     
                      TARGETID ++;
                     break;
                 }
                 
                }
               }
              
              if (!replied) {
                retryCounter = 0;
                
                
                 Serial.println("THIS NODE DID NOT RESPOND");
                 Serial.println (TARGETID); 
                 delay (10); 
                                
                Serial.flush();
                 failRetry();
                  
                                  
                }
              }
            }
   
    void failRetry(){ // if the initial attemp did not success retry X times, where x = nodeAttempts (as defined prior to setup)
        Serial.println("at failRetry - node:");
             Serial.println (TARGETID);       
   while (retryCounter <nodeAttempts){
        radio.listenModeSendBurst(TARGETID, payload, sizeof(payload));
        bool replied = false;
        long start = millis();
          while (millis() - start < BURST_REPLY_TIMEOUT_MS) {
             if (radio.receiveDone()) { 
             replied = true;    
             retryCounter = nodeAttempts;
             Serial.println("success with:");
             Serial.println (TARGETID);
             
             delay (10); 
             theData.sensorReading = 0; 
               theData.sensorReadingL = 0;
               delay (10); 
                      theData = *(Node*)radio.DATA;
                      Serial.println(theData.sensorReading);
                      delay (10);  
                      Serial.println(theData.sensorReadingL);
                      delay (10); 
                 
               theData.sensorReading = 0; 
               theData.sensorReadingL = 0;
               delay (10); 
               TARGETID ++;
               delay (BURST_REPLY_TIMEOUT_MS);
               Serial.flush();
               return;
            
                    }
                  }
                
               if (!replied) {
                   theData.sensorReading = 0; 
                   theData.sensorReadingL = 0;
                   
                   Serial.flush(); 
                      retryCounter++;
                      Serial.println ("RETRYCOUNTER IS - ");
                      Serial.println(retryCounter);
                      delay (10); 
                     
             
                        if (retryCounter >= nodeAttempts) { // if all attempts are completed without result
                          theData.sensorReading = 0; 
                          theData.sensorReadingL = 0;
                      TARGETID ++; // increment target node 
                      
                }    
              }
           }
         Serial.flush(); 
    }
 
   
