ESP8266 + RFID MRC-522 sends data to mysql note* wifi uses ESPAsycWebServer

[HTTP] GET... failed, error: connection failed

#include <Arduino.h>
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESPAsyncWebServer.h>
#include <ESPAsyncTCP.h>
#include "LittleFS.h"
#include <SPI.h>
#include <MFRC522.h>
#include <ESP8266HTTPClient.h>

// Definisi PIN
#define SS_PIN D8
#define RST_PIN D3
#define BUZZER_PIN D1
#define LED_GREEN_PIN D0
#define LED_RED_PIN D4
// SCK PIN D5
// MOSI PIN D6
// MISO PIN D7

const char* PARAM_INPUT_1 = "ssid";
const char* PARAM_INPUT_2 = "pass";
const char* PARAM_INPUT_3 = "ip";
const char* PARAM_INPUT_4 = "gateway";

String HOST_NAME = "http://ramacloud.000webhostapp.com";  // change to your PC's IP address
String PATH_NAME = "/insert_temp.php";
String jsonString;

// Objek untuk RFID
MFRC522 rfid(SS_PIN, RST_PIN);
MFRC522::MIFARE_Key key;
byte nuidPICC[4];

// Objek untuk server web
AsyncWebServer server(80);

// Variabel untuk menyimpan nilai dari formulir HTML
String ssid;
String pass;
String ip;
String gateway;

// Path file untuk menyimpan nilai input secara permanen
const char* ssidPath = "/ssid.txt";
const char* passPath = "/pass.txt";
const char* ipPath = "/ip.txt";
const char* gatewayPath = "/gateway.txt";

// IP dan gateway lokal
IPAddress localIP;
IPAddress localGateway;
IPAddress subnet(255, 255, 0, 0);

// Variabel timer
unsigned long previousMillis = 0;
const long interval = 10000;

// Variabel LED state
String ledState;

// Flag untuk restart
boolean restart = false;

// Inisialisasi LittleFS
void initFS() {
  if (!LittleFS.begin()) {
    Serial.println("Terjadi kesalahan saat menginisialisasi LittleFS");
  } else {
    Serial.println("LittleFS berhasil diinisialisasi");
  }
}

// Membaca file dari LittleFS
String readFile(fs::FS &fs, const char *path) {
  Serial.printf("Membaca file: %s\r\n", path);
  File file = fs.open(path, "r");
  if (!file || file.isDirectory()) {
    Serial.println("- Gagal membuka file untuk dibaca");
    return String();
  }
  String fileContent;
  while (file.available()) {
    fileContent = file.readStringUntil('\n');
    break;
  }
  file.close();
  return fileContent;
}

// Menulis file ke LittleFS
void writeFile(fs::FS &fs, const char *path, const char *message) {
  Serial.printf("Menulis file: %s\r\n", path);
  File file = fs.open(path, "w");
  if (!file) {
    Serial.println("- Gagal membuka file untuk ditulis");
    return;
  }
  if (file.print(message)) {
    Serial.println("- File berhasil ditulis");
  } else {
    Serial.println("- Gagal menulis file");
  }
  file.close();
}

// Inisialisasi WiFi
bool initWiFi() {
  if (ssid == "" || ip == "") {
    Serial.println("SSID atau alamat IP tidak terdefinisi.");
    return false;
  }

  WiFi.mode(WIFI_STA);
  localIP.fromString(ip.c_str());
  localGateway.fromString(gateway.c_str());

  if (!WiFi.config(localIP, localGateway, subnet)) {
    Serial.println("Gagal mengkonfigurasi STA");
    return false;
  }

  WiFi.begin(ssid.c_str(), pass.c_str());

  Serial.println("Menghubungkan ke WiFi...");
  delay(20000);  // Delay panjang agar WiFi dapat terhubung

  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Gagal terhubung.");
    return false;
  }

  Serial.println(WiFi.localIP());
  return true;
}

// Penanganan permintaan HTTP untuk membaca RFID
void handleOnRequest(AsyncWebServerRequest *request) {
  String uidHex = "";
  for (byte i = 0; i < rfid.uid.size; i++) {
    uidHex += String(rfid.uid.uidByte[i] < 0x10 ? "0" : "");
    uidHex += String(rfid.uid.uidByte[i], HEX);
  }
  //  request->send(200, "application/json", jsonString);
  AsyncWebServerResponse *response = request->beginResponse(200, "application/json", jsonString);
  response->addHeader("Content-Type", "application/json");
  response->addHeader("Authorization", "Bearer YourAccessToken");
  response->addHeader("Access-Control-Allow-Origin", "*");

  // Kirim respons kembali ke ESP8266
  request->send(response);

  // Buat URL lengkap dengan parameter UID
  String url = HOST_NAME + PATH_NAME + "?UID=" + uidHex;

  // Kirim permintaan HTTP GET ke server PHP
  WiFiClient client;
  HTTPClient http;
  http.begin(client, url);
  int httpCode = http.GET();

  if (httpCode > 0) {
    Serial.printf("[HTTP] GET... code: %d\n", httpCode);
    if (httpCode == HTTP_CODE_OK) {
      String payload = http.getString();
      Serial.println(payload);
    }
  } else {
    Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
  }

  http.end();
}

void setup() {
  Serial.begin(115200);
  SPI.begin();
  rfid.PCD_Init();

  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(LED_GREEN_PIN, OUTPUT);
  pinMode(LED_RED_PIN, OUTPUT);

  initFS();

  ssid = readFile(LittleFS, ssidPath);
  pass = readFile(LittleFS, passPath);
  ip = readFile(LittleFS, ipPath);
  gateway = readFile(LittleFS, gatewayPath);
  Serial.println(ssid);
  Serial.println(pass);
  Serial.println(ip);
  Serial.println(gateway);

  if (initWiFi()) {
    server.on("/", HTTP_GET, handleOnRequest);
    server.serveStatic("/", LittleFS, "/");
    server.begin();
  } else {
    Serial.println("Mengatur AP (Access Point)");
    WiFi.softAP("ESP-WIFI-MANAGER", NULL);
    IPAddress IP = WiFi.softAPIP();
    Serial.print("IP AP: ");
    Serial.println(IP);
    server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
      request->send(LittleFS, "/wifimanager.html", "text/html");
    });
    server.serveStatic("/", LittleFS, "/");
    server.on("/", HTTP_POST, [](AsyncWebServerRequest * request) {
      int params = request->params();
      for (int i = 0; i < params; i++) {
        AsyncWebParameter *p = request->getParam(i);
        if (p->isPost()) {
          if (p->name() == PARAM_INPUT_1) {
            ssid = p->value().c_str();
            Serial.print("SSID diatur menjadi: ");
            Serial.println(ssid);
            writeFile(LittleFS, ssidPath, ssid.c_str());
          }
          if (p->name() == PARAM_INPUT_2) {
            pass = p->value().c_str();
            Serial.print("Password diatur menjadi: ");
            Serial.println(pass);
            writeFile(LittleFS, passPath, pass.c_str());
          }
          if (p->name() == PARAM_INPUT_3) {
            ip = p->value().c_str();
            Serial.print("Alamat IP diatur menjadi: ");
            Serial.println(ip);
            writeFile(LittleFS, ipPath, ip.c_str());
          }
          if (p->name() == PARAM_INPUT_4) {
            gateway = p->value().c_str();
            Serial.print("Gateway diatur menjadi: ");
            Serial.println(gateway);
            writeFile(LittleFS, gatewayPath, gateway.c_str());
          }
        }
      }
      restart = true;
      request->send(200, "text/plain", "Selesai. ESP akan restart, hubungkan ke router Anda dan buka alamat IP: " + ip);
    });

    server.begin();
  }
}

void loop() {
  if (restart) {
    delay(5000);
    ESP.restart();
  }

  if (rfid.PICC_IsNewCardPresent()) {
    if (rfid.PICC_ReadCardSerial()) {
      String uidHex = "";
      for (byte i = 0; i < rfid.uid.size; i++) {
        uidHex += String(rfid.uid.uidByte[i] < 0x10 ? "0" : "");
        uidHex += String(rfid.uid.uidByte[i], HEX);
      }

      DynamicJsonDocument doc(1024);
      doc["UID"] = uidHex;
      doc["refresh"] = 100;

      String jsonString;
      serializeJson(doc, jsonString);

      digitalWrite(BUZZER_PIN, HIGH);
      digitalWrite(LED_GREEN_PIN, HIGH);
      digitalWrite(LED_RED_PIN, LOW);
      delay(1000);

      rfid.PICC_HaltA();
      rfid.PCD_StopCrypto1();
    }
  } else {
    digitalWrite(LED_GREEN_PIN, LOW);
    digitalWrite(LED_RED_PIN, HIGH);
    digitalWrite(BUZZER_PIN, LOW);
  }
}

Are you giving the correct SSID and password?

Yes, I have provided the correct SSID and password, oh yes, maybe it can help you understand that the WiFi I use can be changed according to the input so you can be sure that the SSID and password will not be wrong

You newdid you create a file to input the ssid and pass? or could it be the php file that inputs to mysql?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.