0

I am using JScolor Picker from http://jscolor.com/examples/

Need Help to extract those R, G, B Values and use them as Integer input to variable in arduino code.

Please Guide me with code how can i get updated values of R, G & B Transferred via http back to arduino sketch.

I am using ESP8266 Webserver to host 2 Files 1) jscolor.js 2) index.html

enter image description here

Index.html code

<!DOCTYPE html>
<html>
<head>
    <title>Getting colors</title>
</head>
<body>


<script src="jscolor.js"></script>

<div style="position:absolute; left:280px; top:10px;">
    toHEXString = <span id="hex-str"></span><br />
    toRGBString = <span id="rgb-str"></span><br />
    R, G, B = <span id="rgb"></span><br />
    H, S, V = <span id="hsv"></span>
</div>

<input class="jscolor {onFineChange:'update(this)'}" value="ffcc00">

<script>
function update(picker) {
    document.getElementById('hex-str').innerHTML = picker.toHEXString();
    document.getElementById('rgb-str').innerHTML = picker.toRGBString();

    document.getElementById('rgb').innerHTML =
        Math.round(picker.rgb[0]) + ', ' +
        Math.round(picker.rgb[1]) + ', ' +
        Math.round(picker.rgb[2]);

    document.getElementById('hsv').innerHTML =
        Math.round(picker.hsv[0]) + '&deg;, ' +
        Math.round(picker.hsv[1]) + '%, ' +
        Math.round(picker.hsv[2]) + '%';
}
document.getElementById("picker_id").addEventListener('change', sendRGB); 
// Added this to extract R, G, B Values but don't know how to handle it in arduino listner.
</script>
</body>
</html>

Arduino code (Sample code to host WebPage from ):

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServer.h>
#include <FS.h>   // Include the SPIFFS library

ESP8266WiFiMulti wifiMulti;     // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti'

ESP8266WebServer server(80);    // Create a webserver object that listens for HTTP request on port 80

File fsUploadFile;              // a File object to temporarily store the received file

String getContentType(String filename); // convert the file extension to the MIME type
bool handleFileRead(String path);       // send the right file to the client (if it exists)
void handleFileUpload();                // upload a new file to the SPIFFS

void setup() {
  Serial.begin(115200);         // Start the Serial communication to send messages to the computer
  delay(10);
  Serial.println('\n');

  wifiMulti.addAP("itsveryeasy", "samepassword");   // add Wi-Fi networks you want to connect to
  wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
  wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");

  Serial.println("Connecting ...");
  int i = 0;
  while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
    delay(1000);
    Serial.print(++i); Serial.print(' ');
  }
  Serial.println('\n');
  Serial.print("Connected to ");
  Serial.println(WiFi.SSID());              // Tell us what network we're connected to
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP());           // Send the IP address of the ESP8266 to the computer

  if (!MDNS.begin("esp8266")) {             // Start the mDNS responder for esp8266.local
    Serial.println("Error setting up MDNS responder!");
  }
  Serial.println("mDNS responder started");

  SPIFFS.begin();                           // Start the SPI Flash Files System

  server.on("/upload", HTTP_GET, []() {                 // if the client requests the upload page
    if (!handleFileRead("/upload.html"))                // send it if it exists
      server.send(404, "text/plain", "404: Not Found"); // otherwise, respond with a 404 (Not Found) error
  });

  server.on("/upload", HTTP_POST,                       // if the client posts to the upload page
    [](){ server.send(200); },                          // Send status 200 (OK) to tell the client we are ready to receive
    handleFileUpload                                    // Receive and save the file
  );

  server.onNotFound([]() {                              // If the client requests any URI
    if (!handleFileRead(server.uri()))                  // send it if it exists
      server.send(404, "text/plain", "404: Not Found"); // otherwise, respond with a 404 (Not Found) error
  });

  server.begin();                           // Actually start the server
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}

String getContentType(String filename) { // convert the file extension to the MIME type
  if (filename.endsWith(".html")) return "text/html";
  else if (filename.endsWith(".css")) return "text/css";
  else if (filename.endsWith(".js")) return "application/javascript";
  else if (filename.endsWith(".ico")) return "image/x-icon";
  else if (filename.endsWith(".gz")) return "application/x-gzip";
  return "text/plain";
}

bool handleFileRead(String path) { // send the right file to the client (if it exists)
  Serial.println("handleFileRead: " + path);
  if (path.endsWith("/")) path += "index.html";          // If a folder is requested, send the index file
  String contentType = getContentType(path);             // Get the MIME type
  String pathWithGz = path + ".gz";
  if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path)) { // If the file exists, either as a compressed archive, or normal
    if (SPIFFS.exists(pathWithGz))                         // If there's a compressed version available
      path += ".gz";                                         // Use the compressed verion
    File file = SPIFFS.open(path, "r");                    // Open the file
    size_t sent = server.streamFile(file, contentType);    // Send it to the client
    file.close();                                          // Close the file again
    Serial.println(String("\tSent file: ") + path);
    return true;
  }
  Serial.println(String("\tFile Not Found: ") + path);   // If the file doesn't exist, return false
  return false;
}

void handleFileUpload(){ // upload a new file to the SPIFFS
  HTTPUpload& upload = server.upload();
  if(upload.status == UPLOAD_FILE_START){
    String filename = upload.filename;
    if(!filename.startsWith("/")) filename = "/"+filename;
    Serial.print("handleFileUpload Name: "); Serial.println(filename);
    fsUploadFile = SPIFFS.open(filename, "w");            // Open the file for writing in SPIFFS (create if it doesn't exist)
    filename = String();
  } else if(upload.status == UPLOAD_FILE_WRITE){
    if(fsUploadFile)
      fsUploadFile.write(upload.buf, upload.currentSize); // Write the received bytes to the file
  } else if(upload.status == UPLOAD_FILE_END){
    if(fsUploadFile) {                                    // If the file was successfully created
      fsUploadFile.close();                               // Close the file again
      Serial.print("handleFileUpload Size: "); Serial.println(upload.totalSize);
      server.sendHeader("Location","/success.html");      // Redirect the client to the success page
      server.send(303);
    } else {
      server.send(500, "text/plain", "500: couldn't create file");
    }
  }
}
user1543571
  • 57
  • 2
  • 9
  • You need to add [AJAX](https://www.w3schools.com/XML/ajax_xmlhttprequest_send.asp) at your index.html/javascript code to send the data back to your server, and on server side, you also need to create the route to handle the data receiving and parse the received data. – hcheung Apr 20 '20 at 05:02
  • you mean to say use websockets ? – user1543571 Apr 21 '20 at 07:33
  • AJAX has nothing to do with websocket. It is for web client like browser to send data back to server using HTTP POST, or request data from server using HTTP GET. Pls read the link that I provided. – hcheung Apr 21 '20 at 10:19
  • Take a look at my [answer](https://stackoverflow.com/a/61181465/4902099) to a similar question for the implementation of ajax – hcheung Apr 21 '20 at 11:36

1 Answers1

0

Personally, I use an Asynchronous Web server with the ESPAsyncWebServer library but I think you should be able to keep your current server and the code will still work :

First, in JavaScript, you just need to do a "POST" with jQuery :

function sendRGB() {
 // Use values from the picker (it's just an exemple here)
 var valueR; 
 var valueG;
 var valueB;

 $.post("receiveRGB", {
   R: valueR,
   G: valueG,
   B: valueB
   // You can add other variables if you want of course!
 }


}

And for the Arduino :

void getRGB() {
    String R = server.arg("R");
    String G = server.arg("G");
    String B = server.arg("B");

    // Do what you want

    server.send(204);
}

void setup() {

    // init serial etc...

    server.on("/receiveRGB", getRGB());


}

That code should work, tell me if it doesn't.

But I find that ESPAsyncWebServer is easier to use (javascript does not change) :

  server.on("/receiveRGB", HTTP_POST, [](AsyncWebServerRequest *request) {
    String R;
    String G;
    String B;
    if(request->hasParam("R", true) && request->hasParam("G", true) && request->hasParam("B", true)) {
      R = request->getParam("R", true)->value();
      G = request->getParam("G", true)->value();
      B = request->getParam("B", true)->value();

      Serial.println(R + " " + G + " " + B);

    }
    request->send(204);
  });
Vincent
  • 1
  • 1
  • 2