Search This Blog

Sunday, 22 June 2025

ESP32 TERIMA NOTIF SETING 10 NOTIF SETING IP NOTIF

 #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(80);

// WiFi Client Settings (Default)
String client_ssid = "Dara@home";
String client_pass = "rejeki88";

// 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>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>Nomor Telepon Penerima Notifikasi</h2>" // New 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 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

  // 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
  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(); // Start the web server
  Serial.println("Web Server started.");
}

// 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...