DEV Community

Komsan Nurak
Komsan Nurak

Posted on

1

ESP32 WiFiManager MQTT Spiffs config ArduinoJson 7

#include <WiFi.h>
#include <WiFiManager.h>
#include <ArduinoJson.h>
#include <PubSubClient.h>
#include <SPIFFS.h>

// ตั้งค่า WiFiManager
WiFiManager wm;

// ตั้งค่า MQTT
WiFiClient espClient;
PubSubClient client(espClient);

// ตั้งค่า JSON document
StaticJsonDocument<200> doc;

void setup() {
  Serial.begin(115200);

  // เริ่มต้น SPIFFS
  if (!SPIFFS.begin(true)) {
    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }

  // รีเซ็ตการตั้งค่า WiFi เมื่อกดปุ่มรีเซ็ตนาน 3 วินาที
  wm.resetSettings();

  // กำหนดค่าเริ่มต้นสำหรับการกำหนดค่าผ่าน WiFiManager
  WiFiManagerParameter custom_mqtt_server("server", "MQTT Server", "mqtt.example.com", 40);
  WiFiManagerParameter custom_mqtt_port("port", "MQTT Port", "1883", 6);
  wm.addParameter(&custom_mqtt_server);
  wm.addParameter(&custom_mqtt_port);

  bool res = wm.autoConnect("ESP32-AP");

  if (!res) {
    Serial.println("Failed to connect");
    // ไม่สามารถเชื่อมต่อ WiFi ให้เข้าสู่โหมด Deep Sleep
  } else {
    Serial.println("Connected to WiFi");

    // เก็บค่า MQTT Server และ Port ลงใน JSON document
    doc["mqtt_server"] = custom_mqtt_server.getValue();
    doc["mqtt_port"] = custom_mqtt_port.getValue();

    // เขียนข้อมูล JSON ลงไฟล์ /data.json ใน SPIFFS
    File file = SPIFFS.open("/data.json", "w");
    if (file) {
      serializeJson(doc, file);
      file.close();
    } else {
      Serial.println("Failed to open /data.json for writing");
    }

    // เชื่อมต่อ MQTT
    client.setServer(doc["mqtt_server"], doc["mqtt_port"].as<int>());
    client.connect("ESP32-Client");
  }
}

void loop() {
  // คงการเชื่อมต่อ MQTT
  client.loop();
}
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay