如何从ESP8266 Webserver的Color picker(jscolor)SPIFFS中获取数值html页面。

问题描述 投票:0回答:1

我正在使用JScolor Picker从 http:/jscolor.comexamples

需要帮助提取这些R,G,B值,并将其作为整数输入到arduino代码中的变量。

请指导我的代码,我如何能得到更新的R,G& B值通过http传输回arduino草图。

我使用ESP8266 Webserver主持2个文件1) jscolor.js2) index.html。

enter image description here

Index.html代码

<!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代码(示例代码,以承载WebPage)。

#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");
    }
  }
}
colors rgb esp8266 picker spiffs
1个回答
0
投票

就个人而言,我使用ESPAsyncWebServer库的异步Web服务器,但我认为你应该能够保持你目前的服务器和代码仍将工作。

首先,在JavaScript中,你只需要做一个 "POST "与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!
 }


}

而对于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());


}

这段代码应该能用,如果不能用就告诉我。

但我发现ESPAsyncWebServer更容易使用(javascript不改变)。

  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);
  });
© www.soinside.com 2019 - 2024. All rights reserved.