簡體   English   中英

如何在由Arduino服務的ESP8266 HTML網頁上使用ajax和setInterval

[英]How to use ajax and setInterval on an ESP8266 HTML webpage served with Arduino

我最近一直在學習如何在Arduino上編程,以便在Adafruit HUZZAH ESP8266突破芯片上托管HTML / CSS / Javascript網頁,因此,如果我的方法完全不可用 ,請原諒我。

我目前正在嘗試獲取一個值,該值通過使用setInterval每五秒鍾運行一次的javascript函數通過ajax自動更新。 盡管它確實至少一次更新了該值,但它花費的時間遠遠超過了五秒鍾,然后再也不會更新該值。

請讓我知道您對我目前正在嘗試實現此方法的看法,如果我做不到這一點? 為了幫助您導航,關鍵功能是loadNum()sendNum() 並且遞增的變量是testNumPart2 (這里還有更多代碼,也使用按鈕打開/關閉LED)。

謝謝!

#include <ESP8266WiFi.h>

#define LED_PIN  15  // This example assumes you have a LED connected to pin 13

const char* ssid = "REDACTED";
const char* password = "REDACTED";

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

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

  // prepare GPIO2
  pinMode(LED_PIN, OUTPUT);
  //digitalWrite(2, 0);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  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());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
boolean currentLineIsBlank = true;
String currentLine = "";
String LEDstatus = "off";

String testNumPart1 = "document.getElementById('demo').innerHTML = ";
int testNumPart2 = 23; 

String testNum = testNumPart1 + testNumPart2; 

//Serial.print("TEST: ");
//Serial.println(testNum);

while (client.connected()) {
  if (client.available()) {
    char c = client.read();
    Serial.write(c);

    testNumPart2++;

    testNum = testNumPart1 + testNumPart2; 

    // if you've gotten to the end of the line (received a newline
    // character) and the line is blank, the http request has ended,
    // so you can send a reply
    if (c == '\n' && currentLineIsBlank) {
      // send a standard http response header
      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type: text/html");
      client.println("Connection: close");  // the connection will be closed after completion of the response
      //client.println("Refresh: 5");  // refresh the page automatically every 5 sec
      client.println();
      client.println("<!DOCTYPE HTML>");
      client.println("<html>");
        client.println("<head>");
            client.println("<title>Adafruit HUZZAH ESP8266</title>");
            client.println("<style type='text/css'>");

                //Styles for on/off switch
                client.println(".onoffswitch { position: relative; width: 90px; -webkit-user-select:none; -moz-user-select:none; -ms-user-select: none; }");
                client.println(".onoffswitch-checkbox { display: none; }");
                client.println(".onoffswitch-label { display: block; overflow: hidden; cursor: pointer; border: 2px solid #999999; border-radius: 20px; }");
                client.println(".onoffswitch-inner { display: block; width: 200%; margin-left: -100%; transition: margin 0.3s ease-in 0s;}");
                client.println(".onoffswitch-inner:before, .onoffswitch-inner:after { display: block; float: left; width: 50%; height: 30px; padding: 0; line-height: 30px; font-size: 14px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold; box-sizing: border-box; }");
                client.println(".onoffswitch-inner:before { content: 'ON'; padding-left: 10px; background-color: #34A7C1; color: #FFFFFF; }");
                client.println(".onoffswitch-inner:after { content: 'OFF'; padding-right: 10px; background-color: #EEEEEE; color: #999999; text-align: right; }");
                client.println(".onoffswitch-switch { display: block; width: 18px; margin: 6px; background: #FFFFFF; position: absolute; top: 0; bottom: 0; right: 56px; border: 2px solid #999999; border-radius: 20px; transition: all 0.3s ease-in 0s; }");
                client.println(".onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner { margin-left: 0; }");
                client.println(".onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch { right: 0px; }");
            client.println("</style>");

            //Javascript Function
            client.println("<script>");
                client.println("function LEDswitch(){");
                    client.println("var LEDswitchCheck = document.getElementById('myonoffswitch').checked;");

                    client.println("if(LEDswitchCheck){");
                        client.println("window.location.href = '/H';");
                    client.println("}");
                    client.println("else {");
                        client.println("window.location.href = '/L';");
                    client.println("}");
                client.println("}");
                client.println("function loadNum() {");
                    client.println("setInterval(sendNum, 5000);");
                client.println("}");
                client.println("function sendNum() {");
                    client.println("var request = new XMLHttpRequest();");
                    client.println("request.onreadystatechange = function() {");
                        client.println("if (this.readyState == 4) {");
                            client.println("if (this.status == 200) {");
                                client.println(testNum);
                            client.println("}");
                        client.println("}");
                    client.println("};");
                    client.println("request.open('GET', '', true);");
                    client.println("request.send();");
                client.println("}");
            client.println("</script>");

        client.println("</head>");
        client.println("<body style='background-color:#558C89;' onload=\"loadNum()\">");
            client.println("<div style='background-color:#74AFAD;'>");
                client.println("<h1 style='text-decoration: underline;'>Adafruit HUZZAH ESP8266</h1>");
            client.println("</div>");

    }
    if (c == '\n') {
      // you're starting a new line
      currentLineIsBlank = true;

      // if the current line is blank, you got two newline characters in a row.
      // that's the end of the client HTTP request, so send a response:
      if (currentLine.length() == 0) {
        client.println("<div style='background-color:#74AFAD;'>");
            client.println("<h2 style='color: red;'>LED Controls</h2>");

        // The HTTP response ends with another blank line:
        client.println();

                        client.println("<div class='onoffswitch'>");

                            if (LEDstatus == "on") 
                            {
                                client.println("<input type='checkbox' name='onoffswitch' class='onoffswitch-checkbox' id='myonoffswitch' checked='checked' onclick='LEDswitch()'>");


                            } //end if
                            else if(LEDstatus == "off")
                            {
                                client.println("<input type='checkbox' name='onoffswitch' class='onoffswitch-checkbox' id='myonoffswitch' onclick='LEDswitch()'>");
                            } //end else

                            client.println("<label class='onoffswitch-label' for='myonoffswitch'>");
                                client.println("<span class='onoffswitch-inner'></span>");
                                client.println("<span class='onoffswitch-switch'></span>");
                            client.println("</label>");
                        client.println("</div>");
                    client.println("</div>"); 
                    client.println("<div style='background-color:#74AFAD;'>");
                        client.println("<h2 style='color: green;'>Num Refresh Test</h2>");
                        client.println("<div id='demo'><h2>Let AJAX change this text</h2></div>");
                        //client.println("<button type='button' onclick='loadNum()'>Change Content</button>");
                    client.println("</div>");
                client.println("</div>");
            client.println("</body>");
        client.println("</html>");
        break;
      } //end if

      else
      {
          currentLine = ""; 
      } //end else
    }
    else if (c != '\r') {
      // you've gotten a character on the current line
      currentLineIsBlank = false;

      currentLine += c;
    }

    // Check to see if the client request was "GET /H" or "GET /L":
    if (currentLine.endsWith("GET /H")) {
      digitalWrite(LED_PIN, HIGH);               // GET /H turns the LED on
      LEDstatus = "on";
    } //end if (/H)

    if (currentLine.endsWith("GET /L")) {
      digitalWrite(LED_PIN, LOW);                // GET /L turns the LED off
      LEDstatus = "off";
    } //end if (/L)

  } //end if (client available)
} //end while
// give the web browser time to receive the data
delay(1);

// close the connection:
client.stop();
Serial.println("client disconnected");
} //end if (client)
} //end void loop

好吧,我最終以此為基礎,並得出了結論: http : //www.esp8266.com/viewtopic.php? f=29&t=7059

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM