Simple code Esp8266 for Deviot App

 #include <ESP8266WiFi.h>

#include <ArduinoJson.h>

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

// Set web server port number to 80
WiFiServer server(80);
String header;
// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

void http_response(String pathWiFiClient *wclient);
JsonObject strtojson(String input);
StaticJsonDocument<1024paratojson(String _sString i1String i2String i3String i4String i5String i6);
String argUrlParsing(String nameargString LineURL);
int var1 = 30;
int var2 = 31;
String _s1 = "OFF";
String _s2 = "OFF";
String _s3 = "OFF";
String _s4 = "OFF";
String _d1 = "d1_mini_pro";
void setup()
{
  Serial.begin(115200);
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssidpassword);
  //WiFi.beginSmartConfig();
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
    //if(WiFi.smartConfigDone()){
      //Serial.println("WiFi Smart Config Done.");
    //}
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}
// the loop function runs over and over again forever
void loop()
{
  WiFiClient client = server.available();
  if (client)
  {
    Serial.println("New Client."); // print a message out in the serial port
    String currentLine = "";       // make a String to hold incoming data from the client
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime)
    {
      currentTime = millis();
      if (client.available())
      {
        char c = client.read(); // read a byte, then
        Serial.write(c);        // print it out the serial monitor
        header += c;
        if (c == '\n')
        {
          if (currentLine.length() == 0)
          {

            if (header.indexOf("GET /5/on") >= 0)
            {
              client.println("HTTP/1.1 200 OK");
              client.println("Content-type:text/html");
              client.println("Connection: close");
              client.println();
              Serial.println("GPIO 5 on");
            }
            else if (header.indexOf("GET /jsoncmd") >= 0)
            {
              http_response("/jsoncmd", &client);
            }
            else if (header.indexOf("GET /tclose") >= 0)
            {
              http_response("/tclose", &client);
              String tclose = argUrlParsing("tclose"header);
              String doit = argUrlParsing("doit"header);
              //Serial.println("cccc=" + tclose);
              if (doit == "plus")
              {
                var1 = var1 + 1;
              }
              else
              {
                var1 = var1 - 1;
              }
            }
            else if (header.indexOf("GET /topen") >= 0)
            {
              http_response("/topen", &client);
              String tclose = argUrlParsing("topen"header);
              String doit = argUrlParsing("doit"header);
              //Serial.println("cccc=" + tclose);
              if (doit == "plus")
              {
                var2 = var2 + 1;
              }
              else
              {
                var2 = var2 - 1;
              }
            }
            else if (header.indexOf("GET /onoff") >= 0)
            {
              String page = argUrlParsing("page"header);
              if (page == "server_status")
              {
                http_response("/jsoncmd", &client);
                String s = argUrlParsing("s"header);
                String status = argUrlParsing("status"header);
                String doit = argUrlParsing("doit"header);
                if (s == "1")
                {
                  if (doit == "plus")
                  {
                    _s1 = "ON";
                  }
                  else
                  {
                    _s1 = "OFF";
                  }
                }
                else if (s == "2")
                {
                  if (doit == "plus")
                  {
                    _s2 = "ON";
                  }
                  else
                  {
                    _s2 = "OFF";
                  }
                }
                else if (s == "3")
                {
                  if (doit == "plus")
                  {
                    _s3 = "ON";
                  }
                  else
                  {
                    _s3 = "OFF";
                  }
                }else if (s == "4")
                {
                  if (doit == "plus")
                  {
                    _s4 = "ON";
                  }
                  else
                  {
                    _s4 = "OFF";
                  }
                }
              }
              else if (page == "servercontrol")
              {
                http_response("/", &client);
              }
              else
              {
                http_response("/", &client);
              }
            }
            else
            {
              http_response("/", &client);
            }
            break;
            //client.println("https://randomnerdtutorials.com/esp8266-web-server/");
          }
          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("");
  }
}

void http_response(String pathWiFiClient *wclient)
{
  //Serial.println(path);
  if (path == "/jsoncmd")
  {
    Serial.println("jsoncmd");
    wclient->println("HTTP/1.1 200 OK");
    wclient->println("Content-Type: application/json; charset=utf-8");
    wclient->println("Server: Arduino");
    StaticJsonDocument<1500doc;
    JsonArray data = doc.createNestedArray("data");
    doc["server"] = "iot1";
    data.add(paratojson("s1""set""time close""button"String(var1), "/tclose?tclose=""80"));
    data.add(paratojson("s1""set""time open""button"String(var2), "/topen?topen=""80"));
    data.add(paratojson("s1""read""s1""switch"_s1"/onoff?s=1&status=""80"));
    data.add(paratojson("s1""read""s2""switch"_s2"/onoff?s=2&status=""80"));
    data.add(paratojson("s1""read""s3""switch"_s3"/onoff?s=3&status=""80"));
    data.add(paratojson("s1""read""s4""switch"_s4"/onoff?s=4&status=""80"));
    data.add(paratojson("s1""read""var""dispaly"_d1"/var?t=""80"));
    //station1 = true ? "OFF" : "ON";
    String output = "";
    serializeJson(docoutput);
    Serial.println(output);
    //wclient->println("Content-Length: "+output.length());
    wclient->println("Connection: close");
    wclient->println();
    wclient->println(output);
  }
  else if (path == "/tclose" || path == "/topen")
  {
    //Serial.println("/tclose====");

    wclient->println("HTTP/1.1 200 OK");
    wclient->println("Content-Type: text/html");
    wclient->println("Connection: close"); // the connection will be closed after completion of the response

    wclient->println();
    wclient->println("<!DOCTYPE HTML>");
    wclient->println("<html>");
    wclient->println(path);
    wclient->println("</html>");
  }
  else if (path == "/")
  {
    wclient->println("HTTP/1.1 200 OK");
    wclient->println("Content-Type: text/html");
    wclient->println("Connection: close"); // the connection will be closed after completion of the response
    //wclient.println("Refresh: 5");  // refresh the page automatically every 5 sec
    wclient->println();
    wclient->println("<!DOCTYPE HTML>");
    wclient->println("<html>");
    //wclient.println("http://192.168.1.123");
    wclient->println("ok wait for write command");
    wclient->println("</html>");
  }
}

StaticJsonDocument<1024paratojson(String _sString i1String i2String i3String i4String i5String i6)
{
  StaticJsonDocument<1024list;
  //list["v1"]["\"" + _s + "\""] = "\"" + input + "\"";
  //list["v1"]["\"f\""] = "\"" + input2 + "\"";
  list["v1"][_s] = i1;
  list["v1"]["f"] = i2;
  list["v1"]["t"] = i3;
  list["v1"]["s"] = i4;
  list["v1"]["h"] = i5;
  list["v1"]["p"] = i6;
  return list;
}

JsonObject strtojson(String input)
{
  DynamicJsonDocument doc(512);
  // You can use a String as your JSON input.
  // WARNING: the string in the input  will be duplicated in the JsonDocument.
  //String input = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
  DeserializationError error = deserializeJson(docinput);
  if (error)
  {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.f_str());
  }
  else
  {
    Serial.println("good json");
  }
  JsonObject obj = doc.as<JsonObject>();
  return obj;
}

String argUrlParsing(String nameargString LineURL)
{
  Serial.println(LineURL);
  if (LineURL.indexOf("?") > 0)
  {
    String argurl = LineURL.substring((LineURL.indexOf("?") + 1), (LineURL.indexOf(" HTTP") - 0));
    //Serial.println(argurl);
    StaticJsonDocument<300argdoc;

    while (argurl.indexOf("&") > 0)
    {
      int posindex = 0;
      //Serial.println(argurl.substring(posindex,argurl.indexOf("&")));
      String tmp = argurl.substring(posindexargurl.indexOf("&"));
      argdoc[tmp.substring(posindexargurl.indexOf("="))] = tmp.substring((argurl.indexOf("=") + 1), tmp.length());
      posindex = argurl.indexOf("&") + 1;
      argurl = argurl.substring(posindexargurl.indexOf(" "));
    }
    //Serial.println(argurl);
    String tmp = argurl.substring(0argurl.length());
    argdoc[tmp.substring(0argurl.indexOf("="))] = tmp.substring((argurl.indexOf("=") + 1), tmp.length());
    const char *sensor = argdoc[namearg];
    if (argdoc[namearg] != "")
    {
      //Serial.println(namearg+" >> "+ String(sensor));
    }
    String output;
    serializeJson(argdocoutput);
    Serial.println(output);
    return String(sensor);
  }
  else
  {
    return "";
  }
}

Popular posts from this blog

Deviotauto app privacy-policy