
////////////////////////////////////////////////////////////////////////////////////////////////////
//ANDRUINO LIBRARY
//A.Scavuzzo
//www.andruino.it
////////////////////////////////////////////////////////////////////////////////////////////////////


bool status_pass_ping_client = false;

void main_Loop() {


#if OTA_ESP8266 == 1 && MCU_ESP8266 == 1
ArduinoOTA.handle();
#endif

  watchdog_cnt = 0;


  if (restart_board) {
    restart_board = false;
    Restart(false, true);         //true, increment in flash the fault counter, true SILENT
  }

  //examples

  //example of variable. You can generate variable starting from ADC values
  //Arduino_User_var[5].value = (ArduinoAnalog[0].value/0.0655)*((ArduinoAnalog[2].value-2.51)/0.0227);
  //Arduino_User_var[6].value = (ArduinoAnalog[1].value/0.0655)*((ArduinoAnalog[3].value-2.51)/0.0227);


  //HOW READ A PIN STATE  (reading directly the Arduino PIN)
  //int read_pin = read(ArduinoIO[3]).state;            //DIGITAL
  //float adc = analogRead(ArduinoAnalog[0].pin) * ADC_STEP;      //ANALOG

  //HOW READ A PIN STATE (reading the global array, it is refreshed by sketch preriodically)
  //int read_state = ArduinoIO[3].state;                          //DIGITAL
  //float read_analog = ArduinoAnalog[0].value;                    //ANALOG



  //reset ehternet card if doesn't connect
#if (WIFI_ESP8266_SHIELD == 1 || MCU_ESP8266 == 1 || ARDUINO_MK1010_WIFI == 1)
  if ((client_fail_connected_cnt > 20 && wifi_signal_bars >=2) ||
      (client_fail_connected_cnt > 30 && wifi_signal_bars == 1)  ||
      (client_fail_connected_cnt > 100 && wifi_signal_bars == 0)  ||
      server_fail_repeated_cnt > 5 || restart_eth) {
#else
  if (client_fail_connected_cnt > 20 || server_fail_repeated_cnt > 5 || restart_eth) {
#endif
    restart_eth = false;
    client_fail_connected_cnt = 0;
    client_consecutive_fails_cnt = 0;
    server_fail_repeated_cnt = 0;
    server_fail_cnt = 0;
    push_fail_cnt = 0;
    eth_restart_cnt++;

    //disable timer interrupts
    deattach_interrupt_timer();
    deattach_interrupt_pin_reading_timer();

    //enable LED BLINKING
    attach_interrupt_startup_led_timer(500);

#if ETHERNET_SHIELD == 1  || ETHERNET_SHIELD_V2 == 1
    if (eth_restart_cnt == 10)
      Restart(true, true);         //true, increment in flash the fault counter, true SILENT
#endif

    ethsetup_network_disconnect();
    /*  WiFi.reconnect();
      while (WiFi.status() != WL_CONNECTED)
      {
        delay(500);
        Serial.print(".");
      }
    */


    //try to reconnect again
    ethsetup_network_setup(false);                                        //restart ethernet network card

    if (station_connection_ok) {
      //check if the issue persist, then increment eth_err_restart_persist used to reduce the connection frequency
      if (ethsetup_SetupPush(false))                                  //check connection (ping to server)
        eth_err_restart_persist = 0;
      else
        eth_err_restart_persist++;
#if SERVER_MODE == 1
      delay(2000);
      ethsetup_server_begin(server_port_number);
#endif
    }

    deattach_interrupt_startup_led_timer();
    attach_interrupt_timer();
    attach_interrupt_pin_reading_timer();
    //   Serial1.println("AT+CIPBUFRESET");
  }


  //SENSORS BASE READING
  sensors_ReadAnalogSensors();                                             //read various types of sensors

  //CHECL LIMITS AND SEND PUSH NOTIFICATIONS
  lim_CheckLimitsSensors(push_user, board_name_array);




  //NETWORK CONNECTION AS SERVER
#if SERVER_MODE == 1
  //DA FARE  if(station_connection_ok)
  server_check_connection();
#endif




  //send the pairing message
  if (msg_to_be_paired_push) {
    msg_to_be_paired_push = false;
    push_SendPush(andruino_it_ip_address, push_user, board_name_array, "pair2", "", "", 0, 0, SKETCH_VERSION, false);    //(char *type, char *mode,byte port, byte lim,float value);
  }
  //send the pairing message
  if (msg_paired_push) {
    msg_paired_push = false;
    push_SendPush(andruino_it_ip_address, push_user, board_name_array, "pair", "", "", 0, 0, SKETCH_VERSION, false);    //(char *type, char *mode,byte port, byte lim,float value);
  }

  if (store_sensor_eeprom) {                //store sensor setting to eeprom
    store_sensor_eeprom = false;
    eep_StoreDataToFlash();
  }
  else if (check_timers) {                  //check the timers every 5 minutes
    check_timers = false;
    timer_CheckTimers(push_user, board_name_array);
  }
  //store only digital when a pin is changed
  else if (store_digital_out_eeprom && (seconds_counter % 20 == 0)) {                      //if a pin is changed after 20sec store data on flash
    store_digital_out_eeprom = false;
    eep_StoreDigitalToFlash();
  }
  else if (store_var_on_eeprom && (seconds_counter % 20 == 0)) {                           //if a pin is changed after 20sec store data on flash
    store_var_on_eeprom = false;
    eep_StoreVarToFlash();
  }


  //every 10 SECONDS send a request to server if the App is not connected
  //every 60 seconds if the connection is on error (after 2 restart)
  //PING SEND
  if (station_connection_ok && send_ping_req && pin_push_flash > 0  && connection_isfar >= CONNECTION_FAR_IS) {
    send_ping_req = false;
    Serial.print(F("PING@")); Serial.print(((float)millis() / 1000), 2); Serial.print(F("s - ")); Serial.print(station_connection_ok); Serial.print(F(" - "));
    status_pass_ping_client =  SendClient_Data_KeepALive(andruino_it_ip_address, push_user, board_name_array, ARDUINO_PASS, 4, NO_KEEP_ALIVE);    //send PING
    //reset eth error persist if the connection is PASSED
    if (status_pass_ping_client)
      eth_err_restart_persist = 0;
  }
  //ACTIVE SEND
  else if (station_connection_ok && status_pass_ping_client && send_http_active_client_req && pin_push_flash > 0 && connection_isfar > CONNECTION_FAR_IS) {              //every 2 SECONDS send JSON DATA TO to server if the App is connected
    SendClient_3Packets_keepAlive(push_user, board_name_array, ARDUINO_PASS);
    
     #if SLEEP_MODE == 1
      if(pairing_id >0) {
        Serial.println(F("Going in sleep mode")); 
        delay(500);
        ESP.deepSleep(SLEEP_WAKEUP_MIN*60e6); 
      }
    #endif
  }
  //NOT ACTIVE SEND
  else if (station_connection_ok && status_pass_ping_client && send_http_notactive_client_req && pin_push_flash > 0 && connection_isfar > CONNECTION_FAR_IS) {              //every 2 SECONDS send JSON DATA TO to server if the App is connected
    Serial.print(F("SEND DATA@")); Serial.print(((float)millis() / 1000), 2); Serial.print(F("s - "));
    SendClient_3Packets_keepAlive(push_user, board_name_array, ARDUINO_PASS);
    
    #if SLEEP_MODE == 1
      if(pairing_id >0) {
        Serial.println(F("Going in sleep mode")); 
        delay(500);
        ESP.deepSleep(SLEEP_WAKEUP_MIN*60e6); 
      }
    #endif
  }




#if NRF24L_ENABLE == 1
  nrf_loop();
#endif


//WATCHDOG 
#if ARDUINO_2560MEGA == 1
 //reset watchdog
  wdt_reset();
#endif

}
