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


#if ARDUINO_2560MEGA == 1
int freeRam () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
#elif MCU_ESP8266 == 1
int freeRam () {

  return (ESP.getFreeHeap());
}
#elif MCU_STM32 == 1
int freeRam () {

  return (0);
}
#elif ARDUINO_MK1010_WIFI == 1
int freeRam () {

  return (0);
}
#endif

#if ARDUINO_2560MEGA == 1
void(* resetFunc) (void) = 0;  // declare reset fuction at address 0

#elif MCU_ESP8266 == 1
void(* resetFunc) (void) = 0;  // declare reset fuction at address 0

#elif MCU_STM32 == 1
void resetFunc () {
  NVIC_SystemReset();
}
#endif

//fault_counter_en=true: store in flash the fault counter
//silent_restart=true: restart but without push notification
void Restart (bool fault_counter_en, bool silent_restart) {


  if (fault_counter_en) {
    fault_restart++;
    eeprom_write_byteNEW ((FLA_FAULT_RESTART_ADDRESS), fault_restart);
  }
  if (silent_restart)
    eeprom_write_byteNEW ((FLA_SILENT_RESTART_ADDRESS), 1);

  deattach_interrupt_timer();
  deattach_interrupt_pin_reading_timer();



#if ARDUINO_2560MEGA == 1 || MCU_STM32 == 1
  delay(3000);
  resetFunc();
  delay(5000);
#elif MCU_ESP8266 == 1
  delay(5000);
  ESP.reset();
  delay(2000);
#endif


}


void ftoa_andrea(float val, char *val_char)
{
  int decPart;
  bool neg = false;
  byte width = 3;

  if (val < 0)
    neg = true;
  int intPart = int(val);

  if (neg)
    decPart = (10000 * ((float)intPart - (float)val) + 1) / 10;
  else
    decPart = (10000 * ((float)val - (float)intPart) + 1) / 10;

  if (decPart < 0)
    decPart = ((-1) * decPart);           //if negative, multiply by -1


  // Serial.print("float:");Serial.print(val,3);Serial.print(", intPart:");Serial.print(intPart);Serial.print(", decPart:");Serial.println(decPart);
  if (decPart == 0) {
    sprintf(val_char, "%d", intPart);
    return;
  }

  if (decPart % 10 == 0) {
    width = 2;
    decPart = decPart / 10;
    if (decPart % 10 == 0) {
      width = 1;
      decPart = decPart / 10;
    }
  }
  if (neg) {
    if (width == 3)
      sprintf(val_char, "-%d.%03d", abs(intPart), decPart);
    else if (width == 2)
      sprintf(val_char, "-%d.%02d", abs(intPart), decPart);
    else if (width == 1)
      sprintf(val_char, "-%d.%01d", abs(intPart), decPart);
  }
  else {
    if (width == 3)
      sprintf(val_char, "%d.%03d", abs(intPart), decPart);
    else if (width == 2)
      sprintf(val_char, "%d.%02d", abs(intPart), decPart);
    else if (width == 1)
      sprintf(val_char, "%d.%01d", abs(intPart), decPart);
  }
}
