'''
 __        _____ _   _ ____  
 \ \      / /_ _| \ | |  _ \ 
  \ \ /\ / / | ||  \| | | | |
   \ V  V /  | || |\  | |_| |
    \_/\_/  |___|_| \_|____/ 
                             

Script to read wind speed from a Davis Anémomètre-girouette Vantage Pro (6410)
https://www.shapemaker.io/blog/wind-speed-measurements-with-anemometer-and-a-raspberry-pi

Connexion:
black (wind speed )     -> gpio21
green (wind direction)  -> ADS1115 (module I2C) 
Yellow                  -> 5v
RED                     -> GND

Attention:  The Raspberry Pi doesn't have analog inputs, so we need an analog-to-digital converter (ADC) to read the wind direction.

sudo /usr/bin/python3 /var/www/nebuleair_pro_4g/windMeter/read_wind_speed.py

'''


import time
from gpiozero import Button
from signal import pause

# Setup wind speed sensor on GPIO pin 21 (instead of 5)
wind_speed_sensor = Button(21)
wind_count = 0

def spin():
    global wind_count
    wind_count = wind_count + 1

def calc_speed(spins, interval):
    # Davis anemometer formula: V = P*(2.25/T) in MPH
    # P = pulses per sample period, T = sample period in seconds
    wind_speed_mph = spins * (2.25 / interval)
    return wind_speed_mph

def reset_wind():
    global wind_count
    wind_count = 0

# Register the event handler for the sensor
wind_speed_sensor.when_pressed = spin

try:
    print("Wind speed measurement started. Press Ctrl+C to exit.")
    
    while True:
        # Reset the counter
        reset_wind()
        
        # Wait for 3 seconds and count rotations
        print("Measuring for 3 seconds...")
        time.sleep(3)
        
        # Calculate and display wind speed
        wind_speed = calc_speed(wind_count, 3)
        print(f"Wind count: {wind_count} spins")
        print(f"Wind speed: {wind_speed:.2f} mph ({wind_speed * 1.60934:.2f} km/h)")
        
except KeyboardInterrupt:
    print("\nMeasurement stopped by user")