Newer
Older
M5StickCPlus_FactoryTest2022 / SampleSrc / httpserver01.ino
@motoki miura motoki miura on 10 May 2022 2 KB SampleSource
#include <WiFi.h>

const char* ssid = "miura2g";
const char* password = "jikken2022";

WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) { // 接続中...
    delay(50);
    Serial.print(".");
  }
  String ip = WiFi.localIP().toString(); // m5デバイスのIPアドレス
  Serial.printf("\nopen http://%s\n\n", ip.c_str() );

  server.begin(); // Webサーバを開始
}

void loop() {
  WiFiClient client = server.available();
  if (client) {
    String req = "" ;
    String tmp = "" , meth = "" ;
    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
        req += c;
        if (c == '\n') {                    // if the byte is a newline character
          if (tmp.length() == 0) {  // end of request, break while loop
            break;
          } else { //まだ継続
            if (tmp.startsWith("GET ") || tmp.startsWith("POST ") ) {
              meth = tmp;
            }
            tmp = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          tmp += c;      // add it to the end of the currentLine
        }
      }
    } // end of while

    Serial.println(meth);
    if ( meth.startsWith("GET /") ) {
      client.println("HTTP/1.1 200 OK"); // header (with response code)
      client.println("Content-Type:text/plain");
      client.println(""); // HTTPでは、header と body の区切りは改行
      client.println(meth);
      client.println("-- request --");
      client.println(req);
    }

    if ( meth.startsWith("POST ") ) {
      String post = "";
      char buf[257];
      int n;
      while ((n = client.available()) > 0) {
        if (n < 256) {
          client.readBytes(buf, n) ;
          buf[n] = 0 ;
        } else {
          client.readBytes(buf, 256) ;
          buf[256] = 0 ;
        }
      }
      post += buf ;

      client.println("HTTP/1.1 200 OK");
      client.println("Content-Type:text/plain");
      client.println(""); // HTTPでは、header と body の区切りは改行
      client.println(meth);
      client.println("-- request --");
      client.println(req);
      client.println("-- post data --");
      client.println(post);
    }
    // close the connection:
    client.stop();
    Serial.println(" --- Client Disconnected.");
  }
  delay(100);
}