#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();
}
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.
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)