Code backup
This commit is contained in:
2026-05-10 16:59:01 +02:00
commit 368d6fafea
796 changed files with 315310 additions and 0 deletions
+321
View File
@@ -0,0 +1,321 @@
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include <Update.h>
#include <ArduinoJson.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>
#include <LiquidCrystal_I2C.h>
#pragma region GLOBAL VARIABLES
int mustReset = 0;
static long wdt_survey_timeout = 10000; // Time in s to trigger the watchdog for solenoid zones
static bool wdt_survey_triggered = false; // Trigger for a single solenoid zone timer
const char* description = "ESP32 Temperature server"; // Description
static const char* ssid = "XXX"; // SSID
static const char* password = "XXX"; // Password Wifi
static const IPAddress gateway(172, 16, 83, 254); // IP del gateway
static const IPAddress subnet(255, 255, 255, 0); // Subnet Mask
static const IPAddress primaryDNS(172, 16, 94, 95); // DNS
hw_timer_t *wdt_survey = NULL; // Timer for single solenoid zone
portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED;
WebServer server(80);
WebServer otaServer(8080);
IPAddress localIp(172, 16, 83, 12); // IP dell' ESP32
String hostname = "XXX"; // Hostname
String macAddress = "";
HTTPClient http;
LiquidCrystal_I2C lcd(0x27, 16, 2);
Adafruit_BME280 bme; // BME variable
float Temperature;
float Humidity;
float Pressure;
#pragma endregion
#pragma region WIFI
void handle_WiFi(){
if ( WiFi.status() != WL_CONNECTED )
{
WiFi.begin(ssid, password);
int WLcount = 0;
while (WiFi.status() != WL_CONNECTED && WLcount < 200 )
{
delay(100);
++WLcount;
}
mustReset++;
if(WiFi.status() != WL_CONNECTED && mustReset > 4)
{
ESP.restart();
}
}
else
{
mustReset = 0;
server.handleClient();
otaServer.handleClient();
}
}
#pragma endregion
#pragma region WEB SERVER OTA
void handleOtaRoot() {
otaServer.sendHeader("Connection", "close");
otaServer.send(200, "text/html", "<form name='loginForm'>"
"<table width='20%' bgcolor='A09F9F' align='center'>"
"<tr>"
"<td colspan=2>"
"<center><font size=4><b>ESP32 Login Page</b></font></center>"
"<br>"
"</td>"
"<br>"
"<br>"
"</tr>"
"<td>Username:</td>"
"<td><input type='text' size=25 name='userid'><br></td>"
"</tr>"
"<br>"
"<br>"
"<tr>"
"<td>Password:</td>"
"<td><input type='Password' size=25 name='pwd'><br></td>"
"<br>"
"<br>"
"</tr>"
"<tr>"
"<td><input type='submit' onclick='check(this.form)' value='Login'></td>"
"</tr>"
"</table>"
"</form>"
"<script>"
"function check(form)"
"{"
"if(form.userid.value=='paladmin' && form.pwd.value==''passwordDaImpostarePerSicurezza)"
"{"
"window.open('/serverIndex')"
"}"
"else"
"{"
" alert('Error Password or Username')/*displays error message*/"
"}"
"}"
"</script>");
}
void handleOtaServerIndex() {
otaServer.sendHeader("Connection", "close");
otaServer.send(200, "text/html", "<script src='https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'></script>"
"<form method='POST' action='#' enctype='multipart/form-data' id='upload_form'>"
"<input type='file' name='update'>"
"<input type='submit' value='Update'>"
"</form>"
"<div id='prg'>progress: 0%</div>"
"<script>"
"$('form').submit(function(e){"
"e.preventDefault();"
"var form = $('#upload_form')[0];"
"var data = new FormData(form);"
" $.ajax({"
"url: '/update',"
"type: 'POST',"
"data: data,"
"contentType: false,"
"processData:false,"
"xhr: function() {"
"var xhr = new window.XMLHttpRequest();"
"xhr.upload.addEventListener('progress', function(evt) {"
"if (evt.lengthComputable) {"
"var per = evt.loaded / evt.total;"
"$('#prg').html('progress: ' + Math.round(per*100) + '%');"
"}"
"}, false);"
"return xhr;"
"},"
"success:function(d, s) {"
"console.log('success!')"
"},"
"error: function (a, b, c) {"
"}"
"});"
"});"
"</script>");
}
void handleOtaUpdate() {
otaServer.sendHeader("Connection", "close");
otaServer.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
ESP.restart();
}
void otaDoUpdate() {
HTTPUpload& upload = otaServer.upload();
if (upload.status == UPLOAD_FILE_START) {
Serial.printf("Update: %s\n", upload.filename.c_str());
if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_WRITE) {
/* flashing firmware to ESP*/
if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
Update.printError(Serial);
}
} else if (upload.status == UPLOAD_FILE_END) {
if (Update.end(true)) { //true to set the size to the current progress
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
} else {
Update.printError(Serial);
}
}
}
#pragma endregion
void handle_SurveyLoop(){
// Handling temperature zone timer trigger
if(wdt_survey_triggered == true)
{
portENTER_CRITICAL(&timerMux);
wdt_survey_triggered = false;
portEXIT_CRITICAL(&timerMux);
//Serial.println("Zio mestre!"); // EasterEgg
Temperature = bme.readTemperature();
Humidity = bme.readHumidity();
Pressure = bme.readPressure();
}
}
void handleRoot() {
server.send(200, "text/plain", hostname + " - Climavey");
}
void handle_GetValue() {
DynamicJsonDocument doc(400);
JsonObject obj = doc.createNestedObject("Values");
obj["Temperature"] = Temperature; // Temperature
obj["Humidity"] = Humidity; // Humidity
obj["Pressure"] = Pressure; // Pressure
obj["macAddress"] = macAddress; // macAddress
String jsonData = "";
serializeJson(doc, jsonData);
server.send(200, "text/plain", jsonData);
//server.send(200, "text/plain", "{ \"Values\": { \"Temperature\": " + Temperature + ", \"Humidity\": " + Humidity + ", \"Pressure\": " + Pressure + " } }" );
/*server.send(200, "text/plain",
String(Temperature) + ";"
+ String(Humidity) + ";"
+ String(Pressure) + ";"
+ macAddress
);*/
}
void handleNotFound(){
server.send(404, "text/plain", "404: Not found");
}
#pragma region Timer Functions
void IRAM_ATTR onWdTimerElapsed() {
portENTER_CRITICAL_ISR(&timerMux);
wdt_survey_triggered = true;
portEXIT_CRITICAL_ISR(&timerMux);
}
#pragma endregion
#pragma region Setup
void bmeSetup() {
bool status = bme.begin(0x76);
if (!status) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
}
}
void webServer() {
if (!WiFi.config(localIp, gateway, subnet, primaryDNS)) {
Serial.println("STA Failed to configure");
}
WiFi.mode(WIFI_STA);
WiFi.setHostname(hostname.c_str());
WiFi.begin(ssid, password);
Serial.println("");
wdt_survey = timerBegin(0, 80, true); //timer 0, div 80
timerAttachInterrupt(wdt_survey, &onWdTimerElapsed, true);
timerAlarmWrite(wdt_survey, wdt_survey_timeout * 1000, true);
timerAlarmEnable(wdt_survey);
Serial.println("");
Serial.print("ESP Board MAC Address: ");
macAddress = WiFi.macAddress();
Serial.println(macAddress);
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
server.on("/", HTTP_GET, handleRoot);
server.on("/getValue", HTTP_GET, handle_GetValue);
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP 80 server started");
otaServer.on("/", HTTP_GET, handleOtaRoot);
otaServer.on("/serverIndex", HTTP_GET, handleOtaServerIndex);
otaServer.on("/update", HTTP_POST, handleOtaUpdate, otaDoUpdate);
otaServer.begin();
Serial.println("HTTP 8080 server started");
}
void lcdInitilizer(){
lcd.init();
lcd.backlight();
}
#pragma endregion
void setup(void) {
Serial.begin(9600);
bmeSetup();
lcdInitilizer();
webServer();
}
void loop(void) {
handle_WiFi();
handle_SurveyLoop();
lcd.setCursor(0, 0);
lcd.print("Hello, World!");
}