[ Day16] Esp32s用AP mode + Relay - (程序码讲解)

1.前言

今天依旧接续之前没讲完程序码,这次主要是讲loop里面的程序码,那此次主要介绍较为主要的部份,但由於这部分稍长,所以会挑一些讲,另外补充些额外的内容,剩下就会丢给後天那篇文章。

2.HTTP状态码

状态码是在说明当手机或各种装置(可上网页),当连接至网页服务器时所回覆状态,包含连接正常,或服务器离线等等,我这样讲大家可能听不太懂,那我说个大家容易听见的404,许多人都会在连接网路时,如果连接不到或者网路不好时都会发生404 Not Found,那通常404 Not Found是服务器不想给使用者知道为何连线被拒绝,那下面就稍微介绍一些常见状态码。

2-1.状态码:2xx 连接成功

代表服务器接受使用者的请求,但通常各位看不见,因为接受就直接进网页拉,不会像常见的4xx状态码一样会显示在网页上。

2-2.状态码:4xx 客户端错误

这类的状态码代表了客户端看起来可能发生了错误,妨碍了服务器的处理。典型的就像403、404等等。

那这边就不多介绍拉,因为主要就是要说Esp32s开启网页时,也是会有状态码,那如果要看详细的可以到 HTTP状态码 wiki 查看。

3.程序码

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

  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // 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) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
            
            // turns the GPIOs on and off
            if (header.indexOf("GET /23/on") >= 0) {
              Serial.println("GPIO 23 on");
              output0State = "on";
              digitalWrite(output0, HIGH);
            } else if (header.indexOf("GET /23/off") >= 0) {
              Serial.println("GPIO 23 off");
              output0State = "off";
              digitalWrite(output0, LOW);
            } else if (header.indexOf("GET /22/on") >= 0) {
              Serial.println("GPIO 22 on");
              output2State = "on";
              digitalWrite(output2, HIGH);
            } else if (header.indexOf("GET /22/off") >= 0) {
              Serial.println("GPIO 22 off");
              output2State = "off";
              digitalWrite(output2, LOW);
            }
            
            // Display the HTML web page
            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:,\">");
            // CSS to style the on/off buttons 
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}");
            client.println(".button { background-color: #4CAF50; border: none; color: white; padding: 16px 40px;");
            client.println("text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}");
            client.println(".button2 {background-color: #555555;}</style></head>");
            
            // Web Page Heading
            client.println("<body><h1>ESP32 Web Server</h1>");
            
            // Display current state, and ON/OFF buttons for GPIO 23  
            client.println("<p>GPIO 23 - State " + output0State + "</p>");
            // If the output0State is off, it displays the ON button       
            if (output0State=="off") {
              client.println("<p><a href=\"/23/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/23/off\"><button class=\"button button2\">OFF</button></a></p>");
            } 
               
            // Display current state, and ON/OFF buttons for GPIO 22  
            client.println("<p>GPIO 22 - State " + output2State + "</p>");
            // If the output2State is off, it displays the ON button       
            if (output2State=="off") {
              client.println("<p><a href=\"/22/on\"><button class=\"button\">ON</button></a></p>");
            } else {
              client.println("<p><a href=\"/22/off\"><button class=\"button button2\">OFF</button></a></p>");
            }
            client.println("</body></html>");
            
            // The HTTP response ends with another blank line
            client.println();
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
    Serial.println("Client disconnected.");
    Serial.println("");
  }
}

从程序码部分开始看,从43行开始会侦测是否有使用者连接,并抓取使用者资讯,而45行会判断是否有使用者连接,如果有则往46行走,没有结束(直接到loop结尾)

  • 48行,如果使用者连接时後持续跑while的程序
  • 49行,这边会读取使用者的资讯(像是点击按钮等动作),後续会做字串切割
  • 53行,侦测刚分析完後,判断c结尾是否有换行符号(\n)或c结尾是除了删除键('\r')
  • 56行,判断字串长度是否为0
  • 59-62行,都是在与使用者的装置做沟通,像是我等等要到哪里,通关密码、里面资料内容的资料传输
  • 64-81行,是侦测网页上按钮的ON与OFF,如果网页上按钮的切换,都会被这边接收後并让对应脚位输出讯号
  • 84-114行,主要都是网路语法,主要是控制页面按钮的ON与OFF,与网页的文字叙述,因为这边会扯到网页的写法(html),所以丢下次讲解程序码时会稍微讲解
  • 129行,将变数清空
  • 131行,与服务器中断连线

欢迎交流

好了,这次讲解内容还希望大家听得懂,因为loop的部分有许多牵扯到网页状态及网页写法...等,所以可能无法一次就理解全部,下次讲解程序码时会稍微讲述html的写法,那麽明天再见罗~


<<:  [Day3]什麽是比特币?

>>:  【第十七天 - 动态规划 题目分析】

Day 1 - 什麽是 HomeLab 及网路

网路,是我们生活圈不可缺少的一部分。 每天一早,不少人都会打开手机查看新的讯息、新闻或影片。 由此可...

【Day8】 用 MelGan 把 Mel 转成 Waveform

MelGan 诚如昨天所说的,使用 Wavenet_Vocoder 生成声音的速度实在是太慢了,所以...

心得

今天是铁人赛的最後一天啦!回想起刚开赛时,抱持着怎麽样都不要去碰到vue-cli的心态,但是到了铁人...

{Day29}Espresso

Espresso Espresso是一种UI Test自动化测试框架,可以在短时间跑完测试并且可以跟...

Day 29:K-近邻演算法(k-nearest neighbors)

K-近邻演算法是一个以已知的资料作为输入,为资料进行分类的演算法,在日常生活中有非常多应用。 举例来...