Я работаю над проектом теплицы (ESP32). Следующий код должен записывать данные на веб-сервер (датчики) и считывать состояние переключателя для ручного управления устройствами. Мне удалось заставить его работать, но консоль продолжает выдавать ERR: CONNECTION RESET при вызове setLED запроса. Коммутаторы сами по себе работают нормально, но так как я никогда не работал с XMLHttp, я думаю, что где-то допустил ошибку.
VM385:1 GET http://192.168.0.104/setLED?lamp=false&pump=false&fan=false net::ERR_CONNECTION_RESET
const char MAIN_page[] PROGMEM = R"=====(
<!DOCTYPE html>
<html>
<style>
.card{
max-width: 400px;
min-height: 250px;
background: #02b875;
padding: 30px;
box-sizing: border-box;
color: #FFF;
margin:20px;
box-shadow: 0px 2px 18px -4px rgba(0,0,0,0.75);
}
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
</style>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<meta charset='urf-8'>
</head>
<body>
<div class="card">
<h4>The ESP32 Update web page without refresh</h4><br>
<h1>Temperature: <span id="temp">0</span> C</h1><br>
<h1>Humidity: <span id="humidity">0</span> %</h1><br>
<h1>Water moisture: <span id="watermoisture">0</span> %</h1><br>
LAMP
<br>
<label class="switch">
<input class="controls" id="lamp"type="checkbox">
<span class="slider round"></span>
</label><br>
<br>
PUMP
<br>
<label class="switch">
<input class="controls" id="pump"type="checkbox">
<span class="slider round"></span>
</label><br>
<br>
FAN
<br>
<label class="switch">
<input class="controls" id="fan"type="checkbox">
<span class="slider round"></span>
</label><br>
</div>
<script>
setInterval(function() {
// Call a function repetatively with 2 Second interval
getData();
}, 2000); //2000mSeconds update rate
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = this.responseText.split("\t");
document.getElementById("temp").innerHTML = data[0];
document.getElementById("humidity").innerHTML = data[1];
document.getElementById("watermoisture").innerHTML = data[2];
}
};
xhttp.open("GET", "readADC", true);
xhttp.send();
var states = [false,false,false];
var xhr = new XMLHttpRequest();
var controls = document.getElementsByClassName("controls");
for(var i=0;i<controls.length;i++){
if(controls[i].checked) states[i]=true;
if(!controls[i].checked) states[i]=false;
}
console.log(states);
var arguments = "lamp=" + states[0] + "&pump=" + states[1] + "&fan=" + states[2];
xhr.open("GET", "/setLED?" + arguments, true);
xhr.send();
}
</script>
</body>
</html>
)=====";
/*
* ESP32 AJAX Demo
* Updates and Gets data from webpage without page refresh
* https://circuits4you.com
*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <DHT.h>
#include "index.h" //Web page header file
WebServer server(80);
#define DHTPIN 25
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
//Enter your SSID and PASSWORD
const char* ssid = "";
const char* password = "";
//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void handleRoot() {
server.send(200, "text/html", MAIN_page); //Send web page
}
void handleADC() {
String adcValue;
float a = dht.readHumidity();
float b = dht.readTemperature();
String humidity = String(a);
String temperature = String(b);
adcValue += "10";
adcValue += "\t";
adcValue += "25";
adcValue += "\t";
adcValue += "30";
server.send(200, "text/plain", adcValue); //Send ADC value only to client ajax request
}
void handleLED() {
String lampstate = server.arg("lamp");
String pumpstate = server.arg("pump");
String fanstate = server.arg("fan");
Serial.println(lampstate);
Serial.println(pumpstate);
Serial.println(fanstate);
}
//===============================================================
// Setup
//===============================================================
void setup(void){
Serial.begin(115200);
Serial.println();
Serial.println("Booting Sketch...");
WiFi.mode(WIFI_STA); //Connectto your wifi
WiFi.begin(ssid, password);
Serial.println("Connecting to ");
Serial.print(ssid);
//Wait for WiFi to connect
while(WiFi.waitForConnectResult() != WL_CONNECTED){
Serial.print(".");
}
//If connection successful show IP address in serial monitor
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
//----------------------------------------------------------------
server.on("/", handleRoot);
server.on("/readADC", handleADC);
server.on("/setLED", handleLED);
server.begin(); //Start server
Serial.println("HTTP server started");
dht.begin();
}
//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void loop(void){
server.handleClient();
delay(1);
}