#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Mesure de la direction du vent

# Importation des bibliothèques utilisées par le script
from gpiozero import MCP3008
from time import sleep
import os

direction_precedente = 0.0

def compare(valeur, tension_lue):
	
    plage = 0.02

    if ( (tension_lue > (valeur * (1.0 - plage)))  and (tension_lue < (valeur *(1.0 + plage))) ):
        return True
        
    return False
 
def conversion_volt_degres(tension_lue, direction_precedente):
    if (compare(2.86, tension_lue)):
        return 0.0
        
    if (compare(1.87, tension_lue)):    
        return 22.5
        
    if (compare(2.05, tension_lue)): 
        return 45
        
    if (compare(0.50, tension_lue)):     
        return 67.5
        
    if (compare(0.55, tension_lue)):
        return 90.0

    if (compare(0.40, tension_lue)):
        return 112.5

    if (compare(1.00, tension_lue)):
        return 135.0

    if (compare(0.72, tension_lue)):
        return 157.5

    if (compare(1.44, tension_lue)):    
        return 180

    if (compare(1.27, tension_lue)):
        return 202.5

    if (compare(2.51, tension_lue)):
        return 225

    if (compare(2.43, tension_lue)):
        return 247.5

    if (compare(3.17, tension_lue)):
        return 270.0
	
    if (compare(2.94, tension_lue)):
        return 292.5

    if (compare(3.06, tension_lue)): 
        return 315.0
	
    if (compare(2.68, tension_lue)):
        return 337.5
	
    return direction_precedente  
    
def get_average(self, angles):
        """
        Consider the following three angles as an example: 10, 20, and 30
        degrees. Intuitively, calculating the mean would involve adding these
        three angles together and dividing by 3, in this case indeed resulting
        in a correct mean angle of 20 degrees. By rotating this system
        anticlockwise through 15 degrees the three angles become 355 degrees,
        5 degrees and 15 degrees. The naive mean is now 125 degrees, which is
        the wrong answer, as it should be 5 degrees.
        """

        # http://en.wikipedia.org/wiki/Directional_statistics

        sin_sum = 0.0
        cos_sum = 0.0

        for angle in angles:
            r = math.radians(angle)
            sin_sum += math.sin(r)
            cos_sum += math.cos(r)

        flen = float(len(angles))
        s = sin_sum / flen
        c = cos_sum / flen
        arc = math.degrees(math.atan(s / c))
        average = 0.0

        if s > 0 and c > 0:
            average = arc
        elif c < 0:
            average = arc + 180
        elif s < 0 and c > 0:
            average = arc + 360

        return 0.0 if average == 360 else average

def get_value(self, length=5):
        data = []
        print("Measuring wind direction for %d seconds..." % length)
        start_time = time.time()

        while time.time() - start_time <= length:
            adc_value = self.adc.read(self.adc_channel)
            direction = self.get_dir(adc_value)
            if direction is not None:  # keep only good measurements
                data.append(direction)
            else:
                print("Could not determine wind direction for ADC reading: %s" % adc_value)

        return self.get_average(data)



# Boucle infinie du programme
while True:
    # lire l'entrée A0
    adc = MCP3008(channel=0)
    
    
    print("Valeur : ", adc.value)
    print(f'Tension : {adc.value * 3.3:.3f}v ')
    tension_lue = adc.value * 3.3
    
    direction = conversion_volt_degres(tension_lue, direction_precedente)
    direction_precedente = direction
    print (direction)
    
    print(f'Direction : {direction:.2f} degrés')
    sleep(0.1)
    os.system("clear")