//////////////////////////////////////////////////////////////////
//                                                              //
//                 LUMICUBE - IUT LYON  - GEII                  //
//                                                              //
//          TEAM : DIE ODD      BY RUBEN SARGSYAN (RUBYAN)      //
//                                                              // 
//                       Ver :  2.2                             // 
//                                                              //
//////////////////////////////////////////////////////////////////

#include <FastLED.h>
#include "BluetoothSerial.h"
#include <Arduino.h>
#include "DFRobotDFPlayerMini.h"

#include "LumiZic.h"

HardwareSerial mySoftwareSerial(1);
DFRobotDFPlayerMini myDFPlayer;

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;
int           Reception;                                              // La valeur de Reception
char          ValeurReceptionBT=0;                                    // La valeur de Reception en "char"

        char  changement;  
const   char  turnON ='a';
const   char  turnOFF ='b';
        int   Cellule = 9 ;                                           // Choix de la cellule
#define       LED_PIN     13                                          // Pin de commande LED
#define       NUM_LEDS    30                                          // Nombre de Led sur le ruban
CRGB          leds[NUM_LEDS];


  void setup() 
{  
 
  pinMode(23, OUTPUT);  
  digitalWrite(23, HIGH);
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  Serial.begin(115200);
  Serial.println("Boot ok\n");
  SerialBT.begin("ESP32_LumiCube\n");                                   // Bluetooth device name
  Serial.println("BT ok\n");
  LumiZic_Setup();
  Serial.println("Lib ok");
  mySoftwareSerial.begin(9600, SERIAL_8N1, 17, 16);                   // Bauds, type, RX, TX
  Serial.println("Tx/RX ok");

  
  
  Serial.println();
  Serial.println(F("DFRobot DFPlayer Mini"));
  Serial.println(F("Initialisation DFPlayer ... (Attendre 3~5 seconds)"));
  
  while(!myDFPlayer.begin(mySoftwareSerial)) 
  {
    Serial.println(F("Liaison impossible ou erreur"));
  }
  
  Serial.println(F("DFPlayer Mini online."));

}

  void loop (void)
{

  ValeurReceptionBT =(char)SerialBT.read();
  
  if (  Serial.available()  )    { SerialBT.write(Serial.read()); }             // bug avec music
  myDFPlayer.pause();
  if (SerialBT.available()) 
  {
        
        SerialBT.print("Reception :");                                // write on BT app
        SerialBT.println(ValeurReceptionBT);                          // write on BT app      
        Serial.print ("Reception :");                                 // print on serial monitor
        Serial.println(ValeurReceptionBT);                            // print on serial monitor    
        //SerialBT.println(ValeurReceptionBT);                        // print on the app    
        //SerialBT.write(ValeurReceptionBT);                          // print on serial monitor
        
        
        if(ValeurReceptionBT == turnON)                               // pour gestion BT
        
        {
              
              while (ValeurReceptionBT == turnON)                     // Si BT -> activation LumiCube
              {
                    changement='a';
                    
                    {                                                 // Start
                    
                        digitalWrite(23, LOW);                        // Etat Bas  = 5v (passage transistor)
                        delayMicroseconds(9);
                        digitalWrite(23, HIGH);                       // Etat Haut = 0v
                    
                    }
                    
                    {                                                 // Selection cellule    
                         SelectionCellule(Cellule);   
                    }
                    
                    {                                                 // Stop
                    
                        digitalWrite(23, LOW);                        // Etat Bas  = 5v (passage transistor)
                        delayMicroseconds(3);
                        digitalWrite(23, HIGH);                       // Etat Haut = 0v
                        delayMicroseconds(3);
                        digitalWrite(23, LOW);                        // Etat Bas  = 5v (passage transistor)
                        delayMicroseconds(3);
                        digitalWrite(23, HIGH);                       // Etat Haut = 0v
                    
                    }
                    
                    for (int i = 0; i <= 29; i++) 
                    {               
                        leds[i] = CRGB ( 0, 0, 255);                  // Selection Bleu 
                        FastLED.show();                               // Utilisation de l'algo FastLed
                        if(SerialBT.read()=='b'){ changement='b';  }  // Detection éventuel d'une action BT 
                         
                        delayMicroseconds(5);                         // delay de 5  us
                        delay(40);                                    // delay de 40 ms
                    }
                    
                    
                    for (int i = 29; i >= 0; i--) 
                    {
                        leds[i] = CRGB ( 255, 0, 0);                  // Selection Rouge
                        FastLED.show();                               // Utilisation de l'algo FastLed
                        if(SerialBT.read()=='b'){ changement='b';  }  // Detection éventuel d'une action BT 
                        
                        delayMicroseconds(5);                         // delay de 5  us
                        delay(40);                                    // delay de 40 ms
                    }
                    
                    Serial.write(SerialBT.read());                    // pour debugage
                    ValeurReceptionBT = changement;                   // pour gestion BT

              }
        }
        
        if(ValeurReceptionBT == turnOFF)                              // Si BT -> aLumiCube OFF
        
            {
              for (int i = 0; i <= 29; i++) 
                {
                 leds[i] = CRGB ( 0, 0, 0);                           // Selection "noir"
                 FastLED.show();                                      // Utilisation de l'algo FastLed
                 delay(40);                                           // delay de 40 ms
                }
            
            }

        if(ValeurReceptionBT == 'm')                              // Si BT -> aLumiCube OFF
        
            {
                         
       
                  SerialBT.print("\n\\__Lecteur Musique___//");
                  SerialBT.print("\n\\__s -> Start/Pause__//");
                  SerialBT.print("\n\\__S -> STOP_________//");
                  SerialBT.print("\n\\__+ -> Volume-Up____//");
                  SerialBT.print("\n\\__-_-> Volume-Down__//");
                  SerialBT.print("\n\\__z -> Back Menu____//");
              
                  changement=1;
                         
                      while (changement == 1)                     
                      {           
                          if (myDFPlayer.available()) 
                          {
                              uint8_t type = myDFPlayer.readType();
                                if(type == DFPlayerPlayFinished)
                                {
                                      if(musicMode == 1)
                                      {
                                        myDFPlayer.playFolder(1, 1);  
                                      } 
                                      else 
                                      {
                                        nextSong();
                                      }
                                }
                          }
                  
                        ValeurReceptionBT =(char)SerialBT.read();
                        
                        if (  Serial.available()  )    { SerialBT.write(Serial.read()); }   // bug avec music
                        
                        if (SerialBT.available()) 
                        {
                              
                              SerialBT.print("Reception :");                                // write on BT app
                              SerialBT.println(ValeurReceptionBT);                          // write on BT app      
                        }

                        Serial.write(SerialBT.read());                      // pour debugage
                        //ValeurReceptionBT = changement;                   // pour gestion BT

                        if(ValeurReceptionBT == '+')
                         {
                              SerialBT.print("\n\\________++++________//");
                              myDFPlayer.volumeUp();
                              myDFPlayer.volumeUp();
                              myDFPlayer.volumeUp();
                              myDFPlayer.volumeUp();
                         }
                          
                         if(ValeurReceptionBT == '-')
                         {
                              SerialBT.print("\n\\________----________//");
                              myDFPlayer.volumeDown();
                              myDFPlayer.volumeDown();
                              myDFPlayer.volumeDown();
                              myDFPlayer.volumeDown();
                         }
                          if(ValeurReceptionBT == 'S')
                         {
                              SerialBT.print("\n\\________STOP________//");
                              myDFPlayer.stop();
                              First_Start =1;    
                         }

                          if(ValeurReceptionBT == 'z')
                         {
                              SerialBT.print("\n\\________EXIT________//");
                              changement=0;
                              SerialBT.print("\n\n\\________MENU________//");
                         }
                          
                          if(ValeurReceptionBT == 's')
                         {
                              isPlaying = !isPlaying;
                              if(isPlaying == true)
                              {
                                  myDFPlayer.start();
                              } 
                              else 
                              {
                                  myDFPlayer.pause();
                                  SerialBT.print("\n\\____Start/Pause_____//"); 
                                  delay(500);
                                  if(First_Start == 1)
                                  {
                                      myDFPlayer.start();
                                      First_Start =0;
                                  }   
                              }
                         }
                         
                        if(ValeurReceptionBT == 'n')
                        {
                            SerialBT.print("\n\\____next song_____//");       //BUUUUG
                            myDFPlayer.playFolder(5, 1);
                            delay(500);
                         }     
                      }
            }      
              
      if(ValeurReceptionBT == 'h')                                            //help
            {
                        SerialBT.print("\n\\__Lecteur Musique___//");
                        SerialBT.print("\n\\__m -> Musique______//");
                        SerialBT.print("\n\\__a -> LEDS_ON______//");
                        SerialBT.print("\n\\__b -> LEDS_OFF_____//");
                        SerialBT.print("\n\\__XXXXXXXXXXXXXXXX__//");
                        SerialBT.print("\n\\__z -> BACK_________//");      
            
            }    
        delay(100);                                                   // delay de 100 ms

  }                                                                   // fin de if SerialBT.available
 
}                                                                     // fin de loop

void SelectionCellule(int Cellule)
{ 
    delayMicroseconds(2);                                             // Attente suplémentaire pour eviter un 
                                                                      // problème lors du dechargement (5->0) 
                                                                      // du transistor
    for (int i = 0; i <= (Cellule-1); i++) 
    {
        digitalWrite(13, HIGH);                                       // Etat Haut = 3v
        delayMicroseconds(1);
        digitalWrite(13, LOW);                                        // Etat Bas = 3v
        delayMicroseconds(1);
        
    }
}

  void nextSong()
{
  songNumber = ((songNumber)%(songsCount-1))+1; //Needs to be checked, might jump songs
  myDFPlayer.playFolder(2, songNumber);
}
