/*
  This a simple example of the aREST Library for the ESP8266 WiFi chip.
  See the README file for more details.
  Written in 2015 by Marco Schwartz under a GPL license.
*/

// Import required libraries
#include <ESP8266WiFi.h>
#include <aREST.h>

#define bluePin  14 //D5
#define redPin  5   //D1
#define greenPin  4 //D2

// Create aREST instance
aREST rest = aREST();

// WiFi parameters
const char* ssid = "box";
const char* password = "*****";

// The port to listen for incoming TCP connections
#define LISTEN_PORT           80

// Create an instance of the server
WiFiServer server(LISTEN_PORT);

// Declare functions to be exposed to the API
int ledControlblue(String command);
int ledControlred(String command);
int ledControlgreen(String command);

void setup(void)
{
  // Start Serial
  Serial.begin(115200);
  
  // Function to be exposed
  rest.function("blue",ledControlblue);
  rest.function("red",ledControlred);
  rest.function("green",ledControlgreen);

  // Give name and ID to device
  rest.set_id("1");
  rest.set_name("esp8266");

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
  
  pinMode(bluePin, OUTPUT);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);

  analogWrite(bluePin, 255);
  analogWrite(redPin, 255);
  analogWrite(greenPin, 255);

}

void loop() {

  // Handle REST calls
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  while(!client.available()){
    delay(1);
  }
  rest.handle(client);

}

int ledControlblue(String command) {

  // Get state from command
  int state = command.toInt();

  Serial.print("blue: ");
  map(state, 7, 255, 0, 255);
  Serial.println(state);
  analogWrite(bluePin, state);
  
  return 1;
}

int ledControlred(String command) {

  // Get state from command
  int state = command.toInt();

  Serial.print("red: ");
  map(state, 7, 255, 0, 255);
  Serial.println(state);
  analogWrite(redPin, state);
  
  return 1;
}

int ledControlgreen(String command) {

  // Get state from command
  int state = command.toInt();

  Serial.print("green: ");
  map(state, 7, 255, 0, 255);
  Serial.println(state);
  analogWrite(greenPin, state);
  
  return 1;
}
