Search This Blog

Thursday, 26 June 2025

ESP32 TERIMA NOTIF SETING 10 NOTIF SETING IP STATIK CLEN PLUS PORT SETING

 #include <WiFi.h>

#include <WebServer.h>

#include <Preferences.h>

// #include <SoftwareSerial.h> // Uncomment if you are connecting SIM800L


// --- Basic Settings ---

#define MAX_CODES 10 // Maximum number of notification codes


// Global Variables

Preferences preferences;

WebServer server; // Initialize WebServer without a specific port here

int web_port = 80; // Default web server port


// WiFi Client Settings (Default)

String client_ssid = "Dara@home";

String client_pass = "rejeki88";


// New global variables for static IP configuration

String client_ip = "";

String client_gateway = "";

String client_subnet = "";

String client_dns1 = ""; // Optional: Primary DNS server

String client_dns2 = ""; // Optional: Secondary DNS server


// Access Point Settings (Fallback)

const char* ap_ssid = "PUTU@TECKNO-SIM800L";

const char* ap_pass = "rejeki88";


// Array to store allowed notification codes

String allowedCodes[MAX_CODES];


// New global variables for recipient phone numbers

String targetPhoneNumber1 = "";

String targetPhoneNumber2 = "";

String targetPhoneNumber3 = "";


// Variables to store current status

String lastNotification = "Belum ada";

String ipAddress = "N/A";


/*

// --- SETTINGS FOR SIM800L (EXAMPLE) ---

// Connect SIM800L TX pin to D2 (GPIO 2) and RX to D3 (GPIO 3)

// SoftwareSerial sim800l(2, 3); // RX, TX


// Function to send SMS to all configured phone numbers

void sendSMS(String message) {

  Serial.println("Mengirim SMS: " + message);

  // Array of target phone numbers for easier iteration

  String phoneNumbers[] = {targetPhoneNumber1, targetPhoneNumber2, targetPhoneNumber3};


  for (int i = 0; i < 3; i++) {

    if (phoneNumbers[i] != "") { // Only send if the number is not empty

      Serial.println("Mengirim ke: " + phoneNumbers[i]);

      // sim800l.println("AT+CMGF=1"); // Set text mode

      // delay(1000);

      // sim800l.println("AT+CMGS=\"" + phoneNumbers[i] + "\"");

      // delay(1000);

      // sim800l.print(message); // Message content

      // delay(100);

      // sim800l.write(26); // CTRL+Z character to send

      // delay(1000);

      // Serial.println("SMS terkirim ke " + phoneNumbers[i]);

    }

  }

}

*/


// --- Web Server Functions ---


// Display the main web page

void handleRoot() {

  // Construct the HTML page for configuration

  String html = "<!DOCTYPE html><html><head><meta charset='UTF-8' name='viewport' content='width=device-width, initial-scale=1.0'>"

                "<title>ESP32 Receiver Config</title>"

                "<style>"

                "body{font-family:Arial,sans-serif;background:#f2f2f2;margin:0;padding:15px;}"

                ".container{max-width:800px;margin:auto;background:white;padding:20px;border-radius:10px;box-shadow:0 2px 10px rgba(0,0,0,0.1);}"

                "h1,h2{color:#333;}"

                "form label{display:block;margin-top:10px;font-weight:bold;}"

                "form input[type='text'],form input[type='password']{width:calc(100% - 20px);padding:8px;margin-top:5px;border:1px solid #ccc;border-radius:5px;}"

                "form input[type='submit']{background-color:#007bff;color:white;border:none;padding:12px 20px;border-radius:5px;cursor:pointer;font-size:16px;margin-top:20px;}"

                ".status{background:#e9f5ff;border-left:5px solid #007bff;padding:10px;margin-top:20px;}"

                ".grid{display:grid;grid-template-columns:repeat(auto-fit, minmax(250px, 1fr));grid-gap:10px;}"

                "</style></head><body>"

                "<div class='container'>"

                "<h1>Konfigurasi Penerima Notifikasi</h1>"

                "<div class='status'>"

                "<h2>Status Saat Ini</h2>"

                "<strong>Status WiFi:</strong> " + (WiFi.status() == WL_CONNECTED ? "Terhubung ke " + client_ssid : "Mode Access Point Aktif") + "<br>"

                "<strong>Alamat IP:</strong> " + ipAddress + "<br>"

                "<strong>Port Web:</strong> " + String(web_port) + "<br>" // Display current web port

                "<strong>Notifikasi Terakhir:</strong> " + lastNotification +

                "</div>"

                "<form action='/save' method='post'>"

                "<h2>Pengaturan WiFi Client</h2>"

                "<label for='ssid'>Nama WiFi (SSID):</label>"

                "<input type='text' name='ssid' value='" + client_ssid + "'>"

                "<label for='password'>Password WiFi:</label>"

                "<input type='password' name='password' value='" + client_pass + "'>"


                "<h2>Pengaturan Port Web</h2>" // New section for web port

                "<label for='port'>Port Web (misalnya 80, 8080):</label>"

                "<input type='text' name='port' value='" + String(web_port) + "'>"


                "<h2>Pengaturan IP Statis (Kosongkan untuk DHCP)</h2>" // Section for static IP

                "<label for='ip'>Alamat IP:</label>"

                "<input type='text' name='ip' value='" + client_ip + "'>"

                "<label for='gateway'>Gateway:</label>"

                "<input type='text' name='gateway' value='" + client_gateway + "'>"

                "<label for='subnet'>Subnet Mask:</label>"

                "<input type='text' name='subnet' value='" + client_subnet + "'>"

                "<label for='dns1'>DNS Primer (Opsional):</label>"

                "<input type='text' name='dns1' value='" + client_dns1 + "'>"

                "<label for='dns2'>DNS Sekunder (Opsional):</label>"

                "<input type='text' name='dns2' value='" + client_dns2 + "'>"


                "<h2>Nomor Telepon Penerima Notifikasi</h2>" // Section for phone numbers

                "<label for='phone1'>Nomor HP 1:</label>"

                "<input type='text' name='phone1' value='" + targetPhoneNumber1 + "'>"

                "<label for='phone2'>Nomor HP 2:</label>"

                "<input type='text' name='phone2' value='" + targetPhoneNumber2 + "'>"

                "<label for='phone3'>Nomor HP 3:</label>"

                "<input type='text' name='phone3' value='" + targetPhoneNumber3 + "'>"

                "<h2>Kode Notifikasi yang Diizinkan (10 Kode)</h2>"

                "<div class='grid'>";


  // Add input fields for each allowed code

  for (int i = 0; i < MAX_CODES; i++) {

    html += "<div><label for='code" + String(i) + "'>Kode #" + String(i + 1) + "</label>"

            "<input type='text' name='code" + String(i) + "' value='" + allowedCodes[i] + "'></div>";

  }


  html += "</div>"

          "<input type='submit' value='Simpan Pengaturan & Restart'>"

          "</form></div></body></html>";


  // Send the HTML response to the client

  server.send(200, "text/html", html);

}


// Save configuration from the form

void handleSave() {

  // Begin preferences in read-write mode

  preferences.begin("config", false);


  // Save WiFi credentials

  client_ssid = server.arg("ssid");

  client_pass = server.arg("password");

  preferences.putString("ssid", client_ssid);

  preferences.putString("password", client_pass);


  // Save web port settings

  web_port = server.arg("port").toInt();

  if (web_port == 0) web_port = 80; // Ensure a valid port, default to 80 if 0 or invalid

  preferences.putInt("web_port", web_port);


  // Save static IP settings

  client_ip = server.arg("ip");

  client_gateway = server.arg("gateway");

  client_subnet = server.arg("subnet");

  client_dns1 = server.arg("dns1");

  client_dns2 = server.arg("dns2");

  preferences.putString("ip", client_ip);

  preferences.putString("gateway", client_gateway);

  preferences.putString("subnet", client_subnet);

  preferences.putString("dns1", client_dns1);

  preferences.putString("dns2", client_dns2);


  // Save recipient phone numbers

  targetPhoneNumber1 = server.arg("phone1");

  targetPhoneNumber2 = server.arg("phone2");

  targetPhoneNumber3 = server.arg("phone3");

  preferences.putString("phone1", targetPhoneNumber1);

  preferences.putString("phone2", targetPhoneNumber2);

  preferences.putString("phone3", targetPhoneNumber3);


  // Save 10 notification codes

  for (int i = 0; i < MAX_CODES; i++) {

    allowedCodes[i] = server.arg("code" + String(i));

    preferences.putString(("code" + String(i)).c_str(), allowedCodes[i]);

  }


  // End preferences, committing changes

  preferences.end();


  // HTML response after saving

  String html = "<!DOCTYPE html><html><head><title>Saved</title><style>"

                "body{font-family:Arial,sans-serif;text-align:center;padding-top:50px;}"

                "h1{color:#4CAF50;}"

                "</style></head><body>"

                "<h1>Pengaturan Disimpan!</h1>"

                "<p>Perangkat akan restart dalam 2 detik...</p>"

                "</body></html>";

  server.send(200, "text/html", html);

  delay(2000); // Wait 2 seconds before restarting

  ESP.restart(); // Restart the ESP32 to apply new settings

}


// Handle incoming notifications

void handleNotif() {

  // Check if the 'src' argument is present in the request

  if (server.hasArg("src")) {

    String receivedCode = server.arg("src");

    Serial.println("Notification received: " + receivedCode);

    lastNotification = receivedCode; // Update the last notification status


    bool isValid = false;

    // Check if the received code is in the allowed list

    for (int i = 0; i < MAX_CODES; i++) {

      // Ensure the allowed code is not empty before comparing

      if (allowedCodes[i] != "" && receivedCode == allowedCodes[i]) {

        isValid = true;

        break; // Code found, no need to check further

      }

    }


    if (isValid) {

      Serial.println("Valid code. Triggering action...");

      server.send(200, "text/plain", "OK. Notification received.");

       

      // --- PLACE YOUR ACTION HERE ---

      // Example: Send SMS using SIM800L

      // sendSMS(receivedCode); // This function will now send to all configured numbers

      // ------------------------------------


    } else {

      Serial.println("Invalid code.");

      server.send(401, "text/plain", "Unauthorized. Code not in allowed list.");

    }

  } else {

    // If 'src' parameter is missing

    server.send(400, "text/plain", "Bad Request. 'src' parameter missing.");

  }

}


// --- Setup and Loop Functions ---


// Load settings from NVS

void loadSettings() {

  preferences.begin("config", true); // Open NVS in read-only mode

  client_ssid = preferences.getString("ssid", "Dara@home"); // Load SSID, with default

  client_pass = preferences.getString("password", "rejeki88"); // Load password, with default


  web_port = preferences.getInt("web_port", 80); // Load web port, default to 80


  // Load static IP settings

  client_ip = preferences.getString("ip", "");

  client_gateway = preferences.getString("gateway", "");

  client_subnet = preferences.getString("subnet", "");

  client_dns1 = preferences.getString("dns1", "");

  client_dns2 = preferences.getString("dns2", "");



  // Load recipient phone numbers

  targetPhoneNumber1 = preferences.getString("phone1", "");

  targetPhoneNumber2 = preferences.getString("phone2", "");

  targetPhoneNumber3 = preferences.getString("phone3", "");


  // Load 10 notification codes, with default messages for the first few

  for (int i = 0; i < MAX_CODES; i++) {

    String default_msg = "";

    if (i == 0) default_msg = "UPS1 MATI";

    if (i == 1) default_msg = "UPS2 MATI";

    if (i == 2) default_msg = "PLN MATI";

    if (i == 3) default_msg = "GENSET MATI";


    allowedCodes[i] = preferences.getString(("code" + String(i)).c_str(), default_msg);

  }

  preferences.end(); // Close preferences

}


// Setup WiFi connection (Client or Access Point)

void setupWiFi() {

  WiFi.mode(WIFI_STA); // Set WiFi to Station (client) mode


  // Check if static IP settings are provided

  if (client_ip != "" && client_gateway != "" && client_subnet != "") {

    IPAddress ip, gateway, subnet, dns1, dns2;

    if (ip.fromString(client_ip) && gateway.fromString(client_gateway) && subnet.fromString(client_subnet)) {

      if (client_dns1 != "" && dns1.fromString(client_dns1)) {

        if (client_dns2 != "" && dns2.fromString(client_dns2)) {

          WiFi.config(ip, gateway, subnet, dns1, dns2); // Use primary and secondary DNS

        } else {

          WiFi.config(ip, gateway, subnet, dns1); // Use only primary DNS

        }

      } else {

        WiFi.config(ip, gateway, subnet); // Use only IP, Gateway, Subnet

      }

      Serial.println("Menggunakan IP Statis.");

    } else {

      Serial.println("IP Statis tidak valid, menggunakan DHCP.");

      // Clear invalid static IP settings to fall back to DHCP

      client_ip = "";

      client_gateway = "";

      client_subnet = "";

      client_dns1 = "";

      client_dns2 = "";

    }

  } else {

    Serial.println("IP Statis tidak dikonfigurasi, menggunakan DHCP.");

  }


  WiFi.begin(client_ssid.c_str(), client_pass.c_str()); // Attempt to connect to saved WiFi


  Serial.print("Connecting to " + client_ssid);

  int attempts = 0;

  // Wait for connection or timeout (10 seconds)

  while (WiFi.status() != WL_CONNECTED && attempts < 20) {

    delay(500); // Wait 0.5 seconds

    Serial.print(".");

    attempts++;

  }


  if (WiFi.status() == WL_CONNECTED) {

    Serial.println("\nConnected!");

    ipAddress = WiFi.localIP().toString(); // Get assigned IP address

    Serial.println("IP Address: " + ipAddress);

  } else {

    Serial.println("\nConnection Failed. Activating Access Point Mode.");

    WiFi.mode(WIFI_AP); // Switch to Access Point mode

    WiFi.softAP(ap_ssid, ap_pass); // Start Access Point

    ipAddress = WiFi.softAPIP().toString(); // Get AP IP address

    Serial.println("AP SSID: " + String(ap_ssid));

    Serial.println("AP IP Address: " + ipAddress);

  }

}


// Arduino setup function (runs once)

void setup() {

  Serial.begin(115200); // Initialize serial communication

  Serial.println("\nStarting ESP32 Receiver...");


  // Initialize SIM800L (uncomment if used)

  // sim800l.begin(9600);

  

  loadSettings(); // Load saved settings from NVS

  setupWiFi();    // Setup WiFi connection


  // Register web server handlers for different URLs

  server.on("/", HTTP_GET, handleRoot);    // Root path for configuration page

  server.on("/save", HTTP_POST, handleSave); // Save configuration

  server.on("/notif", HTTP_GET, handleNotif); // Notification endpoint


  server.begin(web_port); // Start the web server on the configured port

  Serial.println("Web Server started on port: " + String(web_port));

}


// Arduino loop function (runs repeatedly)

void loop() {

  server.handleClient(); // Must be called to handle incoming web requests

}


No comments:

Post a Comment

Tandon Air Otomatis (ESP32 Master & Display) + Kode Lengkap

  Panduan Lengkap Tandon Air Otomatis (ESP32 Master & Display) + Kode Lengkap Diperbarui: 09 August 2025 Artikel ini memandu Anda memban...