/*|-------------------------------------------------|*/
/*| RC CAR VOICE CONTROL VIA WEB INTERFACE          |*/
/*| Webkit (GOOGLE) technology for voice-to-text    |*/
/*| Author: Martin Chlebovec (martinius96)          |*/
/*| LANGUAGE English - region US --> en-US          |*/
/*|-------------------------------------------------|*/
#include <WiFi.h>

const char* ssid     =    "ssid";
const char* pass     =    "password";
const char* host     =    "www.arduino.php5.sk";

WiFiClient client;
void setup() {
  Serial.begin(115200);
  delay(10);
  Serial.print("Connecting to ssid: ");
  Serial.println(ssid);
  WiFi.disconnect(true);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, pass);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
  Serial.println("IP address set: ");
  Serial.println(WiFi.localIP());
}

void translation() {
  if (client.connect(host, 80)) {
    String url = "/php_car/translation.txt";
    client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "User-Agent: NodeMCU\r\n" + "Connection: close\r\n\r\n");
    while (client.connected()) {
      String hlavicka = client.readStringUntil('\n');
      if (hlavicka == "\r") {
        break;
      }
    }
    String line = client.readStringUntil('\n');
    Serial.println(line);
    if (line == "UP") { //if command == go UP


      Serial.println("Moving forward...");
      // PUT CODE FOR MOVE FORWARD THERE


    } else if (line == "DOWN") { //if command == go DOWN


      Serial.println("Moving backward...");
      // PUT CODE FOR MOVE BACKWARD THERE


    } else if (line == "LEFT") { //if command == TURN LEFT


      Serial.println("Turning left...");
      // PUT CODE FOR TURN LEFT THERE


    } else if (line == "RIGHT") { //if command == TURN RIGHT


      Serial.println("Turning right...");
      // PUT CODE FOR TURN RIGHT THERE


    } else if (line == "Last command executed by ESP8266. Waiting for new command.") { //if command == NO_MORE_COMMAND


      Serial.println("No voice command set yet");


    }
  } else {
    Serial.println("Problem connecting to GET voice command");
  }
  client.stop();
}

void executed_command() {
  if (client.connect(host, 80)) { //ak je pripojenie uspesne
    Serial.println("RESET VOICE COMMAND SUCESSFUL");
    String url = "/php_car/command_executed.php";
    client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "User-Agent: NodeMCU\r\n" + "Connection: close\r\n\r\n");
  } else {
    Serial.println("CONNECTION FAILED");
  }
  client.stop();
}

void loop() {
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");

  }
  translation();
  executed_command();
  delay(2000); // WAIT () miliseconds before next reading of variable
}