
#include "config_user.h"
#include "config.h"

volatile unsigned int anemometerRotations  = 0;
uint32_t     start_meas_wind_time = 0;
int          interruptNumber;

void ICACHE_RAM_ATTR _anemometerInterrupt()
{
  anemometerRotations++;
#ifdef DEBUG
  Serial.print("*");
  debug("*");
#endif
}

float wind_speed()
{
  start_measure_wind();
  do {
    delay(1000); // minimum delay of measurement time is 1 second
  } while (check_measure_wind_done() == false);
  return measure_wind_result();
}

void start_measure_wind()
{
  start_meas_wind_time = millis();
  anemometerRotations = 0;
  interruptNumber = digitalPinToInterrupt(ANEMOMETER_PIN);
  attachInterrupt(interruptNumber, _anemometerInterrupt, FALLING);
}

boolean check_measure_wind_done()
{
  if ((start_meas_wind_time + (WIND_SENSOR_MEAS_TIME_S * 1000)) <= millis())
  {
    detachInterrupt(interruptNumber);
    return true;
  }
  return false;
}

float measure_wind_result()
{
  start_meas_wind_time = 0;
#ifdef DEBUG
  debug("rotations = " + String((float)anemometerRotations));
#endif
  return (float)anemometerRotations * WINDSPEED_FACTOR;
}
