Files
arduino_api/ESP_api/ESP_api.ino
2025-03-10 17:27:22 +02:00

248 lines
8.5 KiB
C++

#include <WiFi.h>
#include <EEPROM.h>
#include <HTTPClient.h>
#include <WebServer.h>
#include "esp_mac.h"
//ver 1.03
// Constants for Access Point mode
const char* ap_ssid = "ESP32-AP";
const char* ap_password = "12345678";
// Pin definitions
const int userLedPin = 8;
const int buttonPin = 0;
const int relayPins[4] = {10, 11, 22, 23};
const int inputPins[4] = {1, 2, 3, 15};
// Create a WebServer on port 80
WebServer server(80);
// Variables to store WiFi settings
String ssid, password, static_ip, netmask, gateway, dns, hostname;
String logServerIP, logServerPort;
bool isAPMode = false;
// Variable to keep track of the last log time
unsigned long lastLogTime = 0;
// Function to send logs to the log server
void sendLog(String message) {
if (WiFi.status() == WL_CONNECTED && logServerIP.length() > 0 && logServerPort.length() > 0) {
HTTPClient http;
String url = "http://" + logServerIP + ":" + logServerPort + "/log";
http.begin(url);
http.addHeader("Content-Type", "application/json");
String payload = "{\"hostname\": \"" + hostname + "\", \"ip_address\": \"" + WiFi.localIP().toString() + "\", \"message\": \"" + message + "\"}";
int httpResponseCode = http.POST(payload);
http.end();
if (httpResponseCode > 0) {
Serial.println("Log sent successfully: " + message);
} else {
Serial.println("Error sending log: " + message);
}
}
}
// Handle the root URL ("/") and serve the configuration page
void handleRoot() {
String macAddress = getDefaultMacAddress();
String html = "<!DOCTYPE html><html><head><title>Configuration</title>";
html += "<style>body { font-family: Arial, sans-serif; background-color: #f4f4f9; margin: 0; padding: 0; }";
html += ".container { max-width: 600px; margin: 50px auto; padding: 20px; background-color: #fff; box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); }";
html += "h2 { text-align: center; color: #333; } form { display: flex; flex-direction: column; }";
html += "label { margin-bottom: 10px; color: #555; } input[type='text'], input[type='password'] { padding: 10px; margin-bottom: 20px; border: 1px solid #ccc; border-radius: 4px; }";
html += "input[type='submit'] { padding: 10px; background-color: #28a745; color: #fff; border: none; border-radius: 4px; cursor: pointer; }";
html += "input[type='submit']:hover { background-color: #218838; } button { padding: 10px; background-color: #007bff; color: #fff; border: none; border-radius: 4px; cursor: pointer; margin: 5px; }";
html += "button:hover { background-color: #0056b3; }</style></head><body>";
if (isAPMode) {
html += "<div class='container'><h2>Board Configuration</h2>";
html += "<form action='/save' method='POST'>";
html += "<label for='ssid'>SSID:</label><input type='text' id='ssid' name='ssid' value='" + ssid + "'><br>";
html += "<label for='password'>Password:</label><input type='password' id='password' name='password' value='" + password + "'><br>";
html += "<label for='static_ip'>Static IP:</label><input type='text' id='static_ip' name='static_ip' value='" + static_ip + "'><br>";
html += "<label for='netmask'>Netmask:</label><input type='text' id='netmask' name='netmask' value='" + netmask + "'><br>";
html += "<label for='gateway'>Gateway:</label><input type='text' id='gateway' name='gateway' value='" + gateway + "'><br>";
html += "<label for='dns'>DNS:</label><input type='text' id='dns' name='dns' value='" + dns + "'><br>";
html += "<label for='hostname'>Hostname:</label><input type='text' id='hostname' name='hostname' value='" + hostname + "'><br>";
html += "<label for='log_server_ip'>Log Server IP:</label><input type='text' id='log_server_ip' name='log_server_ip' value='" + logServerIP + "'><br>";
html += "<label for='log_server_port'>Log Server Port:</label><input type='text' id='log_server_port' name='log_server_port' value='" + logServerPort + "'><br>";
html += "<label for='mac_address'>MAC Address:</label><input type='text' id='mac_address' name='mac_address' value='" + macAddress + "' readonly><br>";
html += "<input type='submit' value='Save'></form></div>";
}
html += "</body></html>";
server.send(200, "text/html", html);
}
// Handle the save URL ("/save") and save the WiFi settings
void handleSave() {
ssid = server.arg("ssid");
password = server.arg("password");
static_ip = server.arg("static_ip");
netmask = server.arg("netmask");
gateway = server.arg("gateway");
dns = server.arg("dns");
hostname = server.arg("hostname");
logServerIP = server.arg("log_server_ip");
logServerPort = server.arg("log_server_port");
saveSettings();
server.send(200, "text/html", "Settings saved. Device will restart in client mode.");
delay(2000);
ESP.restart();
}
// Handle the relay control URL ("/relay") and control the relays
void handleRelay() {
int relay = server.arg("relay").toInt() - 1; // Adjust for zero-based index
String action = server.arg("action");
if (relay >= 0 && relay < 4) {
if (action == "on") {
digitalWrite(relayPins[relay], HIGH);
sendLog("Relay " + String(relay + 1) + " turned ON");
} else if (action == "off") {
digitalWrite(relayPins[relay], LOW);
sendLog("Relay " + String(relay + 1) + " turned OFF");
}
}
server.sendHeader("Location", "/");
server.send(303);
}
// Save the WiFi settings to EEPROM
void saveSettings() {
EEPROM.writeString(0, ssid);
EEPROM.writeString(32, password);
EEPROM.writeString(64, static_ip);
EEPROM.writeString(96, netmask);
EEPROM.writeString(128, gateway);
EEPROM.writeString(160, dns);
EEPROM.writeString(192, hostname);
EEPROM.writeString(224, logServerIP);
EEPROM.writeString(256, logServerPort);
EEPROM.commit();
}
// Load the WiFi settings from EEPROM
void loadSettings() {
ssid = EEPROM.readString(0);
password = EEPROM.readString(32);
static_ip = EEPROM.readString(64);
netmask = EEPROM.readString(96);
gateway = EEPROM.readString(128);
dns = EEPROM.readString(160);
hostname = EEPROM.readString(192);
logServerIP = EEPROM.readString(224);
logServerPort = EEPROM.readString(256);
}
// Get the default MAC address of the ESP32
String getDefaultMacAddress() {
String mac = "";
unsigned char mac_base[6] = {0};
if (esp_efuse_mac_get_default(mac_base) == ESP_OK) {
char buffer[18];
sprintf(buffer, "%02X:%02X:%02X:%02X:%02X:%02X", mac_base[0], mac_base[1], mac_base[2], mac_base[3], mac_base[4], mac_base[5]);
mac = buffer;
}
return mac;
}
void setup() {
Serial.begin(115200);
EEPROM.begin(512);
pinMode(userLedPin, OUTPUT);
digitalWrite(userLedPin, LOW);
pinMode(buttonPin, INPUT_PULLUP);
for (int i = 0; i < 4; i++) {
pinMode(relayPins[i], OUTPUT);
digitalWrite(relayPins[i], LOW);
pinMode(inputPins[i], INPUT_PULLUP);
}
loadSettings();
WiFi.softAPdisconnect(true);
if (digitalRead(buttonPin) == LOW || ssid.length() == 0) {
startAPMode();
} else {
connectToWiFi();
}
}
void loop() {
server.handleClient();
if (millis() - lastLogTime >= 30000) {
sendLog("Board is functioning");
lastLogTime = millis();
}
}
void startAPMode() {
WiFi.softAP(ap_ssid, ap_password);
Serial.println("Access Point Started");
Serial.print("IP Address: ");
Serial.println(WiFi.softAPIP());
server.on("/", handleRoot);
server.on("/save", handleSave);
server.on("/relay", handleRelay);
server.begin();
isAPMode = true;
}
void connectToWiFi() {
IPAddress ip, gw, nm, dnsServer;
if (!ip.fromString(static_ip) || !gw.fromString(gateway) || !nm.fromString(netmask) || !dnsServer.fromString(dns)) {
startAPMode();
return;
}
WiFi.config(ip, gw, nm, dnsServer);
WiFi.setHostname(hostname.c_str());
WiFi.begin(ssid.c_str(), password.c_str());
unsigned long startTime = millis();
while (WiFi.status() != WL_CONNECTED) {
if (millis() - startTime >= 10000) {
startAPMode();
return;
}
delay(500);
}
Serial.println("Connected to WiFi.");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
Serial.print("Hostname: ");
Serial.println(WiFi.getHostname());
digitalWrite(userLedPin, HIGH);
isAPMode = false;
startWebServer();
}
void startWebServer() {
server.on("/", handleRoot);
server.on("/save", handleSave);
server.on("/relay", handleRelay);
server.begin();
}
void blinkLed() {
static unsigned long lastBlinkTime = 0;
static bool ledState = LOW;
unsigned long interval = isAPMode ? 1000 : 3000;
if (millis() - lastBlinkTime >= interval) {
ledState = !ledState;
digitalWrite(userLedPin, ledState);
lastBlinkTime = millis();
}
}