РЕШЕНО Esp32 web server проблема с html кодом

Тема в разделе "ESP8266, ESP32", создана пользователем Дмитрий9150518, 16 янв 2020.

  1. Доброго времени суток.

    Пытаюсь сваять web морду и сервер из ESP32 к MQTT сети на даче. Споткнулся уже на первых шагах на переключателе.
    Висит, зараза, статичной картинкой игнорируя скрипт. ПОМОГИТЕ, плиз
    Код (C++):
    #include <Arduino.h>
    #ifdef ESP32
    #include <WiFi.h>
    #include <AsyncTCP.h>
    #elif defined(ESP8266)
    #include <ESP8266WiFi.h>
    #include <ESPAsyncTCP.h>
    #endif
    #include <ESPAsyncWebServer.h>
    #include <PubSubClient.h>

    AsyncWebServer server(80);

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

    #define mqtt_server "192.168.1.1"             // mqtt брокер
    #define mqtt_login "mosquitto"                      
    #define mqtt_password ""                
    #define mqtt_port 1883                             // порт подключения к mqtt, у cloudmqtt порт отличный от 1883

    String temperaturestr;
    String pressurestr;
    String humiditystr;

    WiFiClient espClient;
    PubSubClient client(espClient);


    void notFound(AsyncWebServerRequest *request) {
        request->send(404, "text/plain", "Not found");
    }

    void MQTTcallback(char* topic, byte* payload, unsigned int length) {
      Serial.print("Message arrived in topic: ");
      Serial.println(topic);
      Serial.print("Message:");
    String strTopic = String(topic);
    String message;
      for (int i = 0; i < length; i++) {
        message = message + (char)payload[i];  //Conver *byte to String
      }
       Serial.print(message);

      Serial.println();
      Serial.println("-----------------------");
     
    if (strTopic == "bme280/temperature") {
        temperaturestr = message;
      }
      else if(strTopic == "bme280/humidity") {
        humiditystr = message;
      }
        else if(strTopic == "bme280/pressure") {
        pressurestr = message;
      }
    }

        const char index_html[] PROGMEM = R"rawliteral(
    <!DOCTYPE HTML><html>
    <head>
      <meta name="
    viewport" content="width=device-width, initial-scale=1">
      <link rel="
    stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
      <style>
        html {
         font-family: Arial;
         display: inline-block;
         margin: 0px auto;
         text-align: left;
        }
        h2 { font-size: 1.5rem; }
        p { font-size: 1.5rem; }
        .units { font-size: 1.0rem; }
        .dht-labels{
          font-size: 1.5rem;
          vertical-align:middle;
          padding-bottom: 15px;
        }
        .switch-btn {
        display: inline-block;
        width: 62px; /* ширина переключателя */
        height: 24px; /* высота переключателя */
        border-radius: 12px; /* радиус скругления */
        background: #bfbfbf; /* цвет фона */
        z-index: 0;
        margin: 0;
        padding: 0;
        border: none;
        cursor: pointer;
        position: relative;
        transition-duration: 300ms; /* анимация */
    }
    .switch-btn::after {
        content: "";
        height: 36px; /* высота кнопки */
        width: 36px; /* ширина кнопки */
        border-radius: 18px; /* радиус кнопки */
        background: #fff; /* цвет кнопки */
        top: -6px; /* положение кнопки по вертикали относительно основы */
        left: -6px; /* положение кнопки по горизонтали относительно основы */
        transition-duration: 300ms; /* анимация */
        box-shadow: 0 0 10px 0 #999999; /* тень */
        position: absolute;
        z-index: 1;
    }
    .switch-on {
        background: #fff;
        box-shadow: inset 0 0 10px 0 #999999; /* тень */
    }
    .switch-on::after {
        left: 30px;
        background: #118c4e;
    }
      </style>
    </head>
    <body>
      <h2>ESP32 Server</h2>
     
       <p>
        <i class="fas fa-cloud-sun-rain" style="color:#808080;"></i>
        <span class="dht-labels">Pressure</span>
        <span id="pressure">%PRESSURE%</span>
        <sup class="units">mm.rt.st.</sup>
      </p>
        <p>
        <i class="fas fa-thermometer-half" style="color:#059e8a;"></i>
        <span class="dht-labels">Temperature</span>
        <span id="temperature">%TEMPERATURE%</span>
        <sup class="units">&deg;C</sup>
      </p>
      <p>
        <i class="fas fa-tint" style="color:#00add6;"></i>
        <span class="dht-labels">Humidity</span>
        <span id="humidity">%HUMIDITY%</span>
        <sup class="units">%</sup>
      </p>
      <div class="switch-btn"></div>
      <div class="switch-btn switch-on"></div>
      <script>
    $('.switch-btn').click(function(){
        $(this).toggleClass('switch-on');
    });
    </script>
    </body>
    <script>
    setInterval(function ( ) {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("temperature").innerHTML = this.responseText;
        }
      };
      xhttp.open("GET", "/temperature", true);
      xhttp.send();
    }, 10000 ) ;

    setInterval(function ( ) {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("humidity").innerHTML = this.responseText;
        }
      };
      xhttp.open("GET", "/humidity", true);
      xhttp.send();
    }, 10000 ) ;
    setInterval(function ( ) {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
          document.getElementById("pressure").innerHTML = this.responseText;
        }
      };
      xhttp.open("GET", "/pressure", true);
      xhttp.send();
    }, 10000 ) ;
    </script>
    </html>)rawliteral";

    // Replaces placeholder with DHT values
    String processor(const String& var){
      //Serial.println(var);
      if(var == "
    TEMPERATURE"){
        return temperaturestr;
      }
      else if(var == "
    HUMIDITY"){
        return humiditystr;
      }
        else if(var == "
    PRESSURE"){
        return pressurestr;
      }
      return String();
    }


    void setup() {

        Serial.begin(115200);
        WiFi.mode(WIFI_STA);
        WiFi.begin(ssid, password);
        if (WiFi.waitForConnectResult() != WL_CONNECTED) {
            Serial.printf("
    WiFi Failed!\n");
            return;
        }

        Serial.print("
    IP Address: ");
        Serial.println(WiFi.localIP());


      client.setServer(mqtt_server, mqtt_port);
      client.setCallback(MQTTcallback);
      while (!client.connected()) {
        Serial.println("
    Connecting to MQTT...");
        if (client.connect("
    ESP8266", mqtt_login, mqtt_password )) {
          Serial.println("
    connected");
        } else {
          Serial.print("
    failed with state ");
          Serial.println(client.state());  //If you get state 5: mismatch in configuration
          delay(2000);
        }
      }
         // Route for root / web page
      server.on("
    /", HTTP_GET, [](AsyncWebServerRequest *request){
        request->send_P(200, "
    text/html", index_html, processor);
      });
      server.on("
    /temperature", HTTP_GET, [](AsyncWebServerRequest *request){
        request->send_P(200, "
    text/plain", temperaturestr.c_str());
      });
      server.on("
    /humidity", HTTP_GET, [](AsyncWebServerRequest *request){
        request->send_P(200, "
    text/plain", humiditystr.c_str());
      });
      server.on("
    /pressure", HTTP_GET, [](AsyncWebServerRequest *request){
        request->send_P(200, "
    text/plain", pressurestr.c_str());
      });
        server.begin();
       
       
        client.subscribe("
    bme280/humidity");
        client.subscribe("
    bme280/temperature");
        client.subscribe("
    bme280/pressure");
       

    }
     


    void loop() {
      client.loop();
    }
     

    Вложения:

    • printscreen.jpg
      printscreen.jpg
      Размер файла:
      25,2 КБ
      Просмотров:
      387
  2. Посмотрите в отладчике на браузере
    На строку
    Код (Text):
    $('.switch-btn').click(function(){
    он ругается
    используете джеквери, а сам класс видимо забыли загрузить.
    Добавил после
    пару строк
    Код (Text):
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
    и движок по клику переключается
    мета ютф-8 добавлял только чтоб браузер не ругался на не заданную кодировку

    Не забывайте, если из этой wifi сети в которой работаете, пропадет доступ в интернет, внешние классы грузить неоткуда будет.
     
    Дмитрий9150518, parovoZZ и ИгорьК нравится это.

  3. Заработало!! Спасибо, вернули мне веру в человечество))