Задержка IDE WeMos D1 Mini Arduino отсутствует по запросу клиента / http? - PullRequest
0 голосов
/ 15 февраля 2019

может быть, очень очень глупый вопрос, но мои навыки в c ++ равны 0 ....

Моя ситуация:

Сначала значения Sensor и Relay отправляются на сервер через http.GET().Значения сохраняются через PHP в базе данных MySQL.Все в порядке.

Секунды, запрос через AJAX / JQUERY читает данные как время, записку из космоса.Вот проблема.Большая задержка (~ 30сек).

Я думаю, что это задержка (30000);(Первый)

Итак, что я могу сделать, чтобы разделить там 2 процесса, чтобы в запросе ajax не было большой задержки?Я не знаю, что Аякс плох - это задержка в наброске

Вот мой код:

//A lot of this code have been resued from the example on the ESP8266 Learning Webpage below. 
//http://www.esp8266learning.com/wemos-webserver-example.php

//CODE START 
//1
#include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <ArduinoJson.h>

#include <Time.h>
#include <TimeAlarms.h>
#include <ESP8266HTTPClient.h>
#include "DHT.h"

long Day2=0;
int Hour2 =0;
int Minute2=0;
int Second2=0;
int HighMillis2=0;
int Rollover2=0;

// Below you will need to use your own WIFI informaiton.
//2
const char* ssid = "xxxxxxxxxxxxxxxxxxx"; //WIFI Name, WeMo will only connect to a 2.4GHz network.
const char* password = "xxxxxxxxxxxxxxx"; //WIFI Password

//defining the pin and setting up the "server"
//3
#define DHTTYPE DHT21   // DHT 11
int relayPin = D1; // The Shield uses pin 1 for the relay
WiFiServer server(80);
IPAddress ip(192, 168, 1, 94); // where xx is the desired IP Address
IPAddress gateway(192, 168, 1, 1); // set gateway to match your network
IPAddress subnet(255, 255, 255, 0); // set subnet mask to match your network

// DHT Sensor
const int DHTPin = 4;
// Initialize DHT sensor.
DHT dht(DHTPin, DHTTYPE);

// Temporary variables
static char celsiusTemp[7];
static char fahrenheitTemp[7];
static char humidityTemp[7];
// void setup is where we initialize variables, pin modes, start using libraries, etc. 
//The setup function will only run once, after each powerup or reset of the wemos board.
//4

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "192.168.1.1:1233", 3600, 60000);


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

  dht.begin();




  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, LOW);

  Serial.print(F("Setting static ip to : "));
  Serial.println(ip);

  // Connect to WiFi network
  //5
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.config(ip, gateway, subnet); 
  WiFi.begin(ssid, password);
  //Trying to connect it will display dots
  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.print("Use this URL : ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

  timeClient.begin();
  timeClient.update();



setTime(timeClient.getHours(),timeClient.getMinutes(),timeClient.getSeconds(),1,1,11); // set time to Saturday 8:29:00am Jan 1 2011
//Serial.print(timeClient.getFormattedTime());
//Serial.print("^^^^");
// create the alarms 
Alarm.alarmRepeat(8,0,0, TurnLightOn);  // 8:30am every day
Alarm.alarmRepeat(20,0,0, TurnLightOff);  // 8:30am every day

}

//void loop is where you put all your code. it is a funtion that returns nothing and will repeat over and over again
//6
void loop() {
// Check if a client has connected
  WiFiClient client = server.available();
  //Serial.print(client);
  if (!client) {


 Serial.println("-------------KEIN CLIENT AUTOMATISCH ----------------------");
             float h = dht.readHumidity();
            // Read temperature as Celsius (the default)
            float t = dht.readTemperature();
            // Read temperature as Fahrenheit (isFahrenheit = true)
            float f = dht.readTemperature(true);

            // Check if any reads failed and exit early (to try again).
            if (isnan(h) || isnan(t) || isnan(f)) {
              Serial.println("Failed to read from DHT sensor!");
              strcpy(celsiusTemp,"Failed");
              strcpy(fahrenheitTemp, "Failed");
              strcpy(humidityTemp, "Failed");         
            } else{
              // Computes temperature values in Celsius + Fahrenheit and Humidity




              //send sensor data to server
              HTTPClient http;    //Declare object of class HTTPClient
              //GET Data
              String Link;
              String GetURL;
              int RelayLightStatus = digitalRead (5);
              GetURL += F("http://192.168.1.1:8082/controlcenter/api.php?name=wemosd1mini%&do=updateepsvalue");
              GetURL += F("&temp=");
              GetURL += String(t, 2);
              GetURL += F("&rlf=");
              GetURL += String(h, 2);
              GetURL += F("&relaylightstatus=");
              GetURL += String(RelayLightStatus);
              Serial.println(GetURL);



              http.begin(GetURL);     //Specify request destination
              http.addHeader("Content-Type", "text/plain");  //Specify content-type header

              int httpCode = http.GET();            //Send the request
              String payload = http.getString();    //Get the response payload
              Serial.println(httpCode);   //Print HTTP return code
              //Serial.println(payload);    //Print request response payload
              http.end();  //Close connection


            //ZSU FUnktion
            String  currenttime;
            currenttime = timeClient.getFormattedTime();


            Serial.println(currenttime);


             uptime(); //Runs the uptime script located below the main loop and reenters the main loop
            //print_Uptime();

             delay(30000);  //GET Data at every 5 seconds
             Alarm.delay(1000); // wait one second between clock display




            }







 Serial.println("-------------KEIN CLIENT AUTOMATISCH ENDE----------------------");




  } else {

    Serial.println("------------- CLIENT AUTOMATISCH ----------------------");


    // Wait until the client sends some data
    Serial.println("new client");
    while(!client.available()){
      delay(1);
    }

    // Read the first line of the request
    String request = client.readStringUntil('\r');
    Serial.println(request);
    client.flush();


    client.println("HTTP/1.1 200 OK");
    client.println("Content-Type: application/json");
    client.println("Access-Control-Allow-Origin: *");
    client.println("");

   // Return the response, build the html page


  if (request.indexOf("/sysinfo") != -1) {
    String freemem;
    String output;
    freemem = ESP.getFreeHeap(); 


    StaticJsonBuffer<300> JSONbuffer;
    JsonObject& JSONencoder = JSONbuffer.createObject();

    JSONencoder["freemem"] = freemem;
    //JsonArray& values = JSONencoder.createNestedArray("values");

    //values.add(freemem);
    JSONencoder["uptimed"] = Day2;
    JSONencoder["uptimeh"] = Hour2;
    JSONencoder["uptimem"] = Minute2;
    JSONencoder["uptimes"] = Second2;
    JSONencoder["systime"] = timeClient.getFormattedTime();
    JSONencoder["hostname"] = String(WiFi.hostname());
    JSONencoder["dsdd"] = String(WiFi.localIP());
    JSONencoder["ssid"] = String(ssid);
    JSONencoder["wifistatus"] = String(WiFi.status());
    Serial.println(ESP.getResetInfo());

    JSONencoder.printTo(client);
    client.println();  

  }

  if (request.indexOf("/switchRelay") != -1 or request.indexOf("/switchRelayrelayrelayLight=OFF") != -1 or request.indexOf("/switchRelayrelayrelayLight=OFF") != -1) {


      //Match the request, checking to see what the currect state is
      int value = LOW;

      if (request.indexOf("/switchRelayrelayrelayLight=ON") != -1) {
          digitalWrite(D1, HIGH);
          client.print("{\"status\": {\"state\": \"ok\"}}");
          value = HIGH;
      } 


      if (request.indexOf("/switchRelayrelayrelayLight=OFF") != -1){
          digitalWrite(D1, LOW);
          client.print("{\"status\": {\"state\": \"ok\"}}");
          value = LOW;
      }




  }

      delay(1);
      Serial.println("Client disconnected");
      Serial.println("");
      client.setNoDelay(true);

   Serial.println("------------- CLIENT END ----------------------");

}

//CLOCK


}//END


void TurnLightOn(){
  Serial.println("Turn light on"); 
  digitalWrite(D1, HIGH);   

  HTTPClient http1; 

  String GetURL1;
  GetURL1 += F("http://192.168.1.1:8082/controlcenter/api.php?do=addRun&task=2&value=on&trigger=auto");
  http1.begin(GetURL1);     //Specify request destination
  http1.addHeader("Content-Type", "text/plain");  //Specify content-type header

  int httpCode1 = http1.GET();            //Send the request
  String payload1 = http1.getString();    //Get the response payload
  //Serial.println(httpCode);   //Print HTTP return code
  //Serial.println(payload);    //Print request response payload
  http1.end();  //Close connection


}

void TurnLightOff(){
  Serial.println("Turn light off"); 
  digitalWrite(D1, LOW);   

  HTTPClient http1; 

  String GetURL1;
  GetURL1 += F("http://192.168.1.1:8082/controlcenter/api.php?do=addRun&task=2&value=off&trigger=auto");
  http1.begin(GetURL1);     //Specify request destination
  http1.addHeader("Content-Type", "text/plain");  //Specify content-type header

  int httpCode1 = http1.GET();            //Send the request
  String payload1 = http1.getString();    //Get the response payload
  //Serial.println(httpCode);   //Print HTTP return code
  //Serial.println(payload);    //Print request response payload
  http1.end();  //Close connection  
}

 void uptime(){
//** Making Note of an expected rollover *****//   
if(millis()>=3000000000){ 
HighMillis2=1;

}
//** Making note of actual rollover **//
if(millis()<=100000&&HighMillis2==1){
Rollover2++;
HighMillis2=0;
}

long secsUp = millis()/1000;

Second2 = secsUp%60;

Minute2 = (secsUp/60)%60;

Hour2 = (secsUp/(60*60))%24;

Day2 = (Rollover2*50)+(secsUp/(60*60*24));  //First portion takes care of a rollover [around 50 days]

};
...