
#include <WiFi.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <OSCMessage.h> // for sending OSC messages
#include <ESPmDNS.h>



#ifndef STASSID
#define STASSID "NameOfTheWifiNetwork"
#define STAPSK  "Password"
#endif


const char* ssid = STASSID;
const char* password = STAPSK;

unsigned long previousMillis;


// ******** LED PIN CONFIGURATION ******************

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  LED_BUILTIN;      // the number of the LED pin

//******** init OSC ****************************** 

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status
int buttonVal = 0;
boolean buttonChanged = false;
int argumentOSC = 8;
String adresseOSC = "/LS/Go/PB/" //OSC Command for LightShark LS1 Controller. If you use another one, please refer to the user manual to find the OSC command available;
String phraseOSC;
const char* messageOSC;



//******** IP ADRESS AND PORTS CONFIGURATION **********


WiFiUDP Udp;                           // A UDP instance to let us send and receive packets over UDP
const IPAddress destIp(**,**,**,**);   // remote IP of the target device
const unsigned int destPort = 8***;    // remote port of the target device where the NodeMCU sends OSC to
const unsigned int localPort = 9***;   // local port to listen for UDP packets at the NodeMCU (another device must send OSC messages to this port)


//******** END OSC SETTINGS ****************************** 



void setup() {  
  
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT_PULLUP);
  Serial.begin(115200);


  // FOUR Flashs means the start of the program
  int i=0;
  while(i<4){
  digitalWrite(LED_BUILTIN, LOW);  // turn the LED on (HIGH is the voltage level)
  delay(100);                      // wait for a second
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED off by making the voltage LOW
  delay(100);  
    i++;
  }
  
  Serial.println("Booting");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();

  }

  initOTA();

  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

   Serial.println("Starting UDP");
   Udp.begin(localPort);
   Serial.printf("Local port: %s:%i/n", WiFi.localIP().toString().c_str(), localPort);




}

void loop() {
  ArduinoOTA.handle();

  if (millis() - previousMillis >= 500) {
    previousMillis = millis();
    Serial.println(F("Code has been update"));
  }



//****************** OSC Function ************************

    buttonState = digitalRead(buttonPin);

    
// appui ou relachement
  if (buttonState != buttonVal) {
        buttonChanged = true;
        buttonVal = digitalRead(buttonPin);
  }


  if(buttonChanged == true){
    
    phraseOSC = adresseOSC + String(argumentOSC); // en string + remise à zéro de la phraseOSC
    messageOSC = phraseOSC.c_str();  // en char
  
    OSCMessage msgOut(messageOSC);
    msgOut.add(0.0f); // add the FLOAT value to the OSC routing !!! Could be different for and INTEGER or BOOLEAN value
    Udp.beginPacket(destIp, destPort);//Format UDP message
    msgOut.send(Udp);

    Udp.endPacket();
    msgOut.empty();

    buttonChanged = false;
    
  }

 

  delay(10);





}

// ************** OSC Function End ********************


void initOTA() {
  // Port defaults to 8266
  // ArduinoOTA.setPort(8266);

  // Hostname defaults to esp8266-[ChipID]
  // ArduinoOTA.setHostname("myesp8266");

  // No authentication by default
  // ArduinoOTA.setPassword("admin");

  // Password can be set with it's md5 value as well
  // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");

  ArduinoOTA.onStart([]() {
    String type;
    if (ArduinoOTA.getCommand() == U_FLASH) {
      type = "sketch";
    } else { // U_FS
      type = "filesystem";
    }

    // NOTE: if updating FS this would be the place to unmount FS using FS.end()
    Serial.println("Start updating " + type);
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) {
      Serial.println("Auth Failed");
    } else if (error == OTA_BEGIN_ERROR) {
      Serial.println("Begin Failed");
    } else if (error == OTA_CONNECT_ERROR) {
      Serial.println("Connect Failed");
    } else if (error == OTA_RECEIVE_ERROR) {
      Serial.println("Receive Failed");
    } else if (error == OTA_END_ERROR) {
      Serial.println("End Failed");
    }
  });
  ArduinoOTA.begin();
}
