# Importations des librairies et définition des fonctions

from PyFirmataDef import *
from ConnectToArduino import *
import time


# Déclaration des constantes et variables

PinLEDR = 11
PinLEDB = 10
PinLEDV = 9
PinPOTR = 2
PinPOTV = 1
PinPOTB = 0
PinButton = 12

BrightnessR = 0
BrightnessB = 0
BrightnessV = 0

ValButton = 0
OldValButton = 0
State = 0


# Connexion à l'Arduino

PortComArduino = SelectPortCOM()
board = OpenPortCom(PortComArduino)


# Connexion à l'Arduino réussie - Déclaration des entrées et sorties
    
ArduinoIterator = Iterateur(board)

PinDigitalInput = DigitalInput(board, PinButton)

PinAnalogInputR = AnalogInput(board, PinPOTR)
PinAnalogInputV = AnalogInput(board, PinPOTV)
PinAnalogInputB = AnalogInput(board, PinPOTB)

PinAnalogOutputR = AnalogOutput(board, PinLEDR)
PinAnalogOutputV = AnalogOutput(board, PinLEDV)
PinAnalogOutputB = AnalogOutput(board, PinLEDB)

time.sleep (0.5)

print("Connexion à l'arduino établie - Appuyez sur Ctrl-C pour quitter")


# Boucle principale du programme

while True:
    try:
        ValButton = PinDigitalInput.read()
        time.sleep(.01)
            
        if ValButton == 1 and OldValButton == 0:
            State = 1 - State        

        OldValButton = ValButton

        if State==1:
            BrightnessR = PinAnalogInputR.read()
            BrightnessV = PinAnalogInputV.read()
            BrightnessB = PinAnalogInputB.read()

            PinAnalogOutputR.write(1 - BrightnessR)
            PinAnalogOutputV.write(1 - BrightnessV)
            PinAnalogOutputB.write(1 - BrightnessB)
        else:
            PinAnalogOutputR.write(0)
            PinAnalogOutputV.write(0)
            PinAnalogOutputB.write(0)

    except KeyboardInterrupt:
        PinAnalogOutputR.write(0)
        PinAnalogOutputV.write(0)
        PinAnalogOutputB.write(0)
        board.exit()
        sys.exit(0)
    
    
