Hello everyone, does anybody can help me? The board is DOIT ESP32 DEVKIT V1. Trying to create wifi manger with the ability to enter wifi and telegram credentials through LittleFS. Sketch is work, wifi and telegram data are saved trough web server and read after ESP32 restart. ESP connects to wifi with credentials from spiffs but telgram is not started (I try to check them through flash led example), although bottoken is successfully read from memory (I see it in COM port). I would appreciate any help or links to relevant examples. Текст «как есть» (без применения форматирования).
#include <Arduino.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h> //3.7.2
#include <AsyncTCP.h> //3.3.6
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h> //1.3.0
#include "LittleFS.h"
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
// Search for parameter in HTTP POST request
const char* PARAM_INPUT_1 = "ssid";
const char* PARAM_INPUT_2 = "pass";
const char* PARAM_INPUT_3 = "bottoken";
const char* PARAM_INPUT_4 = "chatid";
char BOTtoken[48];// = "1841511384:AAGWI6tCq437jobvKEnFtlLV1EloMtxQmZ8"; // your Bot Token (Get from Botfather)
char CHAT_ID[11];// = "1622910223";
String bottoken = String(BOTtoken);
String chatid = String(CHAT_ID);
//Variables to save values from HTML form
String ssid;
String pass;
//String bottoken;
//String chatid;
// File paths to save input values permanently
const char* ssidPath = "/ssid.txt";
const char* passPath = "/pass.txt";
const char* bottokenPath = "/bottoken.txt";
const char* chatidPath = "/chatid.txt";
IPAddress localIP;
//IPAddress localIP(192, 168, 1, 200); // hardcoded
// Set your Gateway IP address
IPAddress localGateway;
//IPAddress localGateway(192, 168, 1, 1); //hardcoded
IPAddress subnet(255, 255, 0, 0);
WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOTtoken, secured_client);
//UniversalTelegramBot bot(bottoken.c_str(), secured_client);
unsigned long bot_lasttime; // last time messages' scan has been done
// Timer variables
unsigned long previousMillis = 0;
const long interval = 10000; // interval to wait for Wi-Fi connection (milliseconds)
const unsigned long BOT_MTBS = 1000; // mean time between scan messages
const int ledPin = LED_BUILTIN;
int ledStatus = 0;
// Initialize LittleFS
void initLittleFS() {
if (!LittleFS.begin(true)) {
Serial.println("An error has occurred while mounting LittleFS");
}
Serial.println("LittleFS mounted successfully");
}
// Read File from LittleFS
String readFile(fs::FS &fs, const char * path){
Serial.printf("Reading file: %s\r\n", path);
File file = fs.open(path);
if(!file || file.isDirectory()){
Serial.println("- failed to open file for reading");
return String();
}
String fileContent;
while(file.available()){
fileContent = file.readStringUntil('\n');
break;
}
return fileContent;
}
// Write file to LittleFS
void writeFile(fs::FS &fs, const char * path, const char * message){
Serial.printf("Writing file: %s\r\n", path);
File file = fs.open(path, FILE_WRITE);
if(!file){
Serial.println("- failed to open file for writing");
return;
}
if(file.print(message)){
Serial.println("- file written");
} else {
Serial.println("- write failed");
}
}
void handleNewMessages(int numNewMessages)
{
Serial.print("handleNewMessages ");
Serial.println(numNewMessages);
for (int i = 0; i < numNewMessages; i++)
{
String chat_id = bot.messages[i].chat_id;
String text = bot.messages[i].text;
String from_name = bot.messages[i].from_name;
if (from_name == "")
from_name = "Guest";
if (text == "/ledon")
{
digitalWrite(ledPin, LOW); // turn the LED on (HIGH is the voltage level)
ledStatus = 1;
bot.sendMessage(chat_id, "Led is ON", "");
}
if (text == "/ledoff")
{
ledStatus = 0;
digitalWrite(ledPin, HIGH); // turn the LED off (LOW is the voltage level)
bot.sendMessage(chat_id, "Led is OFF", "");
}
if (text == "/status")
{
if (ledStatus)
{
bot.sendMessage(chat_id, "Led is ON", "");
}
else
{
bot.sendMessage(chat_id, "Led is OFF", "");
}
}
if (text == "/start")
{
String welcome = "Welcome to Universal Arduino Telegram Bot library, " + from_name + ".\n";
welcome += "This is Flash Led Bot example.\n\n";
welcome += "/ledon : to switch the Led ON\n";
welcome += "/ledoff : to switch the Led OFF\n";
welcome += "/status : Returns current status of LED\n";
bot.sendMessage(chat_id, welcome, "Markdown");
}
}
}
// Initialize WiFi
bool initWiFi() {
if(ssid=="" || pass==""){
Serial.println("Undefined SSID or Password.");
return false;
}
WiFi.mode(WIFI_STA);
delay(100);
WiFi.begin(ssid.c_str(), pass.c_str()); //WiFi.begin(ssid.c_str(), pass.c_str());
Serial.println("Connecting to WiFi...");
unsigned long currentMillis = millis();
previousMillis = currentMillis;
while(WiFi.status() != WL_CONNECTED) {
currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
Serial.println("Failed to connect.");
return false;
}
}
Serial.print("WiFi connected to ");
Serial.print(ssid.c_str());
Serial.print(" RSSI: ");
Serial.println(WiFi.RSSI());
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
return true;
}
void setup() {
// Serial port for debugging purposes
Serial.begin(115200);
pinMode(ledPin, OUTPUT); // initialize digital ledPin as an output.
delay(10);
digitalWrite(ledPin, LOW); // initialize pin as off (active LOW)
initLittleFS();
// Load values saved in LittleFS
ssid = readFile(LittleFS, ssidPath);
pass = readFile(LittleFS, passPath);
bottoken = readFile(LittleFS, bottokenPath);
chatid = readFile (LittleFS, chatidPath);
Serial.print("SSID: ");
Serial.println(ssid);
Serial.print("Password: ");
Serial.println(pass);
Serial.print("Bot Token: ");
Serial.println(bottoken);
Serial.print("Chat ID: ");
Serial.println(chatid);
//initWiFi();
if(initWiFi()) {
Serial.print("Connecting to Wifi SSID; ");
Serial.println(ssid.c_str());
secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(500);
}
Serial.print("\nWiFi connected. IP address: ");
Serial.print("Retrieving time: ");
Serial.print("Bot token; ");
Serial.println(bottoken.c_str());
configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
time_t now = time(nullptr);
while (now < 24 * 3600)
{
Serial.print(".");
delay(100);
now = time(nullptr);
}
Serial.println(now);
}
else {
// Connect to Wi-Fi network with SSID and password
Serial.println("Setting AP (Access Point)");
// NULL sets an open Access Point
WiFi.softAP("ESP-WIFI-MANAGER", NULL);
IPAddress IP = WiFi.softAPIP();
Serial.print("AP IP address: ");
Serial.println(IP);
// Web Server Root URL
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++){
const AsyncWebParameter* p = request->getParam(i);
if(p->isPost()){
// HTTP POST ssid value
if (p->name() == PARAM_INPUT_1) {
ssid = p->value().c_str();
Serial.print("SSID set to: ");
Serial.println(ssid);
// Write file to save value
writeFile(LittleFS, ssidPath, ssid.c_str());
}
// HTTP POST pass value
if (p->name() == PARAM_INPUT_2) {
pass = p->value().c_str();
Serial.print("Password set to: ");
Serial.println(pass);
// Write file to save value
writeFile(LittleFS, passPath, pass.c_str());
}
// HTTP POST ip value
if (p->name() == PARAM_INPUT_3) {
bottoken = p->value().c_str();
Serial.print("Bot Token set to: ");
Serial.println(bottoken);
// Write file to save value
writeFile(LittleFS, bottokenPath, bottoken.c_str());
}
// HTTP POST gateway value
if (p->name() == PARAM_INPUT_4) {
chatid = p->value().c_str();
Serial.print("Chat ID set to: ");
Serial.println(chatid);
// Write file to save value
writeFile(LittleFS, chatidPath, chatid.c_str());
}
}
}
request->send(200, "text/plain", "Done. Restart Now");
delay(3000);
ESP.restart();
});
server.begin();
WiFi.setTxPower(WIFI_POWER_8_5dBm);
int txPower = WiFi.getTxPower();
}
}
void loop() {
if (millis() - bot_lasttime > BOT_MTBS)
{
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while (numNewMessages)
{
Serial.println("got response");
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
bot_lasttime = millis();
}
}