/*
 * Project 6: ESP32 RGB LED Web Server
 * Control an RGB LED from a browser color picker using PWM.
 *
 * Pin map:
 *   GPIO 13 -> Red anode (through 220 ohm)
 *   GPIO 12 -> Green anode (through 220 ohm)
 *   GPIO 14 -> Blue anode (through 220 ohm)
 *   Common cathode -> GND
 *
 * Libraries: WiFi (built-in)
 * Serial: 115200 baud
 */

// Load Wi-Fi library
#include <WiFi.h>

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// Set web server port number to 80
WiFiServer server(80);

// Decode HTTP GET value
String redString = "0";
String greenString = "0";
String blueString = "0";
int pos1 = 0;
int pos2 = 0;
int pos3 = 0;
int pos4 = 0;

// Variable to store the HTTP request
String header;

// Red, green, and blue pins for PWM control
const int redPin = 13;     // 13 corresponds to GPIO13
const int greenPin = 12;   // 12 corresponds to GPIO12
const int bluePin = 14;    // 14 corresponds to GPIO14

// Setting PWM frequency and bit resolution (ESP32 Core v3.x+ API)
// Same two settings as Project 3, applied to three pins instead of one.
// The core allocates an internal PWM channel per pin for you.
const int freq = 5000;
// Bit resolution 2^8 = 256
const int resolution = 8;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

void setup() {
  Serial.begin(115200);
  delay(500);

  Serial.println();
  Serial.println("==============================================");
  Serial.println(" Project 6: ESP32 RGB LED Web Server");
  Serial.println("==============================================");
  Serial.printf ("RGB LED -> R:GPIO%d  G:GPIO%d  B:GPIO%d\n", redPin, greenPin, bluePin);

  // Enable PWM on each color pin: one call per pin sets up the timer,
  // picks a free channel, and routes it to the GPIO.
  ledcAttach(redPin,   freq, resolution);
  ledcAttach(greenPin, freq, resolution);
  ledcAttach(bluePin,  freq, resolution);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to Wi-Fi: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println();
  Serial.println("Wi-Fi connected!");
  Serial.print("Open this address in your browser:  http://");
  Serial.println(WiFi.localIP());
  Serial.println("----------------------------------------------");
  server.begin();
}

void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    currentTime = millis();
    previousTime = currentTime;
    String currentLine = "";                // holds incoming data from the client
    while (client.connected() && currentTime - previousTime <= timeoutTime) {
      currentTime = millis();
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          if (currentLine.length() == 0) {
            // Send the HTTP response header
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            // Display the HTML web page (color picker)
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            client.println("<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\">");
            client.println("<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.min.js\"></script>");
            client.println("</head><body><div class=\"container\"><div class=\"row\"><h1>ESP Color Picker</h1></div>");
            client.println("<a class=\"btn btn-primary btn-lg\" href=\"#\" id=\"change_color\" role=\"button\">Change Color</a> ");
            client.println("<input class=\"jscolor {onFineChange:'update(this)'}\" id=\"rgb\"></div>");
            client.println("<script>function update(picker) {document.getElementById('rgb').innerHTML = Math.round(picker.rgb[0]) + ', ' +  Math.round(picker.rgb[1]) + ', ' + Math.round(picker.rgb[2]);");
            client.println("document.getElementById(\"change_color\").href=\"?r\" + Math.round(picker.rgb[0]) + \"g\" +  Math.round(picker.rgb[1]) + \"b\" + Math.round(picker.rgb[2]) + \"&\";}</script></body></html>");
            client.println();

            // Request sample: /?r201g32b255&   ->  Red=201 Green=32 Blue=255
            if(header.indexOf("GET /?r") >= 0) {
              pos1 = header.indexOf('r');
              pos2 = header.indexOf('g');
              pos3 = header.indexOf('b');
              pos4 = header.indexOf('&');
              redString   = header.substring(pos1+1, pos2);
              greenString = header.substring(pos2+1, pos3);
              blueString  = header.substring(pos3+1, pos4);
              // Clear, readable log of the chosen color
              Serial.printf("[WEB] Color set -> R:%s  G:%s  B:%s\n",
                            redString.c_str(), greenString.c_str(), blueString.c_str());
              // In Core v3.x+ the first argument is the GPIO pin, not a channel
              ledcWrite(redPin,   redString.toInt());
              ledcWrite(greenPin, greenString.toInt());
              ledcWrite(bluePin,  blueString.toInt());
            }
            break;
          } else {
            currentLine = "";
          }
        } else if (c != '\r') {
          currentLine += c;
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
  }
}
