'''
 __        _____ _   _ ____  
 \ \      / /_ _| \ | |  _ \ 
  \ \ /\ / / | ||  \| | | | |
   \ 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_direction.py

'''
import time
import board
import busio
import adafruit_ads1x15.ads1115 as ADS
from adafruit_ads1x15.analog_in import AnalogIn

# Create the I2C bus and ADC object
i2c = busio.I2C(board.SCL, board.SDA)
ads = ADS.ADS1115(i2c)

# Connect to the channel with your Davis wind vane
wind_dir_sensor = AnalogIn(ads, ADS.P0)

# Check the current voltage range
min_voltage = 9999
max_voltage = -9999

def get_wind_direction():
    """Get wind direction angle from Davis Vantage Pro2 wind vane"""
    global min_voltage, max_voltage
    
    # Read voltage from ADS1115
    voltage = wind_dir_sensor.voltage
    
    # Update min/max for calibration
    if voltage < min_voltage:
        min_voltage = voltage
    if voltage > max_voltage:
        max_voltage = voltage
    
    # We'll use a safer mapping approach
    # Assuming the Davis sensor is linear from 0° to 360°
    estimated_max = 3.859 # Initial estimate, will refine
    
    # Calculate angle with bounds checking
    angle = (voltage / estimated_max) * 360.0
    
    # Ensure angle is in 0-360 range
    angle = angle % 360
    
    return voltage, angle

# Main loop
try:
    print("Reading wind direction. Press Ctrl+C to exit.")
    print("Voltage, Angle, Min Voltage, Max Voltage")
    while True:
        voltage, angle = get_wind_direction()
        print(f"{voltage:.3f}V, {angle:.1f}°, {min_voltage:.3f}V, {max_voltage:.3f}V")
        time.sleep(1)
except KeyboardInterrupt:
    print("\nProgram stopped")
    print(f"Observed voltage range: {min_voltage:.3f}V to {max_voltage:.3f}V")
    
    # Suggest calibration if we have enough data
    if max_voltage > min_voltage:
        print("\nSuggested calibration for your setup:")
        print(f"max_voltage = {max_voltage:.3f}")
        print(f"def get_wind_direction():")
        print(f"    voltage = wind_dir_sensor.voltage")
        print(f"    angle = (voltage / {max_voltage:.3f}) * 360.0")
        print(f"    return angle % 360")