It was a pleasure to communicate with you about the espcam 32 book. Someone was able to implement wifimanager and telegram bot, this is because of the ease it would be to enter both the SSID data, wifi password and the telegrambot IDchat and token credentials. I did a lot of research and there are many version errors dearduinojson etc please I await your reply
Hi.
I think you can easily modify the “Wi-Fi Maanger” project on our “Build Web Servers with ESP32 and ESP8266” eBook so that you can enter the telegram credentials.
Check that out.
Regards,
Sara
I almost never ask for help and I know how to solve it by searching the web, but in this case I ask you for help, I tried everything, I got errors of variables, versions, etc., etc., I got stuck
invalid operands of types ‘const char [76]’ and ‘char [40]’ to binary ‘operator+’
please help me for this thank you very much
please
I found this I am not a programmer but I am excited to develop iot if you can contact me please I am very grateful
strcpy(chatId, custom_chatId.getValue());
strcpy(BOTtoken, custom_BOTtoken.getValue());
cannot convert ‘String’ to ‘char*’ for argument ‘1’ to ‘char* strcpy(char*, const char*)’
Hi.
You need to be more specific about your issues.
Try to solve one issue at a time.
You need to give more details about your errors, otherwise I can’t help.
How are you defining your variables, what type of variables are you using? What values do those variables have?
Regards,
Sara
good afternoon I was trying and doing everything if you can help me please here I send you the code does not work for me
#include
#include
#include
#ifdef ESP32
#include “SPIFFS.h”
#endif
#include “soc/soc.h”
#include “soc/rtc_cntl_reg.h”
#include “esp_camera.h”
#include
#include
#include //https://github.com/alanswx/ESPAsyncWiFiManager
#include
//const char* ssid = “FLIA ABENDANO”;
//const char* password = “49513772”;
// Initialize Telegram BOT
//String BOTtoken = “”; // your Bot Token (Get from Botfather)
char chat_id[100];
char bot_token[100];
String chatId;
String BOTtoken;
// Use @myidbot to find out the chat ID of an individual or a group
// Also note that you need to click “start” on a bot before it can
// message you
//String chatID = “”;
bool sendPhoto = false;
WiFiClientSecure clientTCP;
UniversalTelegramBot bot(BOTtoken, clientTCP);
#define FLASH_LED_PIN 4
bool flashState = LOW;
//flag for saving data
bool shouldSaveConfig = false;
//callback notifying us of the need to save config
void saveConfigCallback () {
Serial.println(“Should save config”);
shouldSaveConfig = true;
}
AsyncWebServer server(80);
DNSServer dns;
//Checks for new messages every 1 second.
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;
//CAMERA_MODEL_AI_THINKER
#define PWDN_GPIO_NUM 32
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 0
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 21
#define Y4_GPIO_NUM 19
#define Y3_GPIO_NUM 18
#define Y2_GPIO_NUM 5
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
void configInitCamera(){
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = Y2_GPIO_NUM;
config.pin_d1 = Y3_GPIO_NUM;
config.pin_d2 = Y4_GPIO_NUM;
config.pin_d3 = Y5_GPIO_NUM;
config.pin_d4 = Y6_GPIO_NUM;
config.pin_d5 = Y7_GPIO_NUM;
config.pin_d6 = Y8_GPIO_NUM;
config.pin_d7 = Y9_GPIO_NUM;
config.pin_xclk = XCLK_GPIO_NUM;
config.pin_pclk = PCLK_GPIO_NUM;
config.pin_vsync = VSYNC_GPIO_NUM;
config.pin_href = HREF_GPIO_NUM;
config.pin_sscb_sda = SIOD_GPIO_NUM;
config.pin_sscb_scl = SIOC_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = 20000000;
config.pixel_format = PIXFORMAT_JPEG;
//init with high specs to pre-allocate larger buffers
if(psramFound()){
config.frame_size = FRAMESIZE_UXGA;
config.jpeg_quality = 10; //0-63 lower number means higher quality
config.fb_count = 2;
} else {
config.frame_size = FRAMESIZE_SVGA;
config.jpeg_quality = 12; //0-63 lower number means higher quality
config.fb_count = 1;
}
// camera init
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
Serial.printf(“Camera init failed with error 0x%x”, err);
delay(1000);
ESP.restart();
}
// Drop down frame size for higher initial frame rate
sensor_t * s = esp_camera_sensor_get();
s->set_framesize(s, FRAMESIZE_CIF); // UXGA|SXGA|XGA|SVGA|VGA|CIF|QVGA|HQVGA|QQVGA
}
void handleNewMessages(int numNewMessages) {
Serial.print(“Handle New Messages: “);
Serial.println(numNewMessages);
for (int i = 0; i len;
uint16_t extraLen = head.length() + tail.length();
uint16_t totalLen = imageLen + extraLen;
clientTCP.println(“POST /bot”+BOTtoken+”/sendPhoto HTTP/1.1”);
clientTCP.println(“Host: ” + String(myDomain));
clientTCP.println(“Content-Length: ” + String(totalLen));
clientTCP.println(“Content-Type: multipart/form-data; boundary=RandomNerdTutorials”);
clientTCP.println();
clientTCP.print(head);
uint8_t *fbBuf = fb->buf;
size_t fbLen = fb->len;
for (size_t n=0;n<fbLen;n=n+1024) {
if (n+10240) {
size_t remainder = fbLen%1024;
clientTCP.write(fbBuf, remainder);
}
}
clientTCP.print(tail);
esp_camera_fb_return(fb);
int waitTime = 10000; // timeout 10 seconds
long startTimer = millis();
boolean state = false;
while ((startTimer + waitTime) > millis())
{
Serial.print(“.”);
delay(100);
while (clientTCP.available())
{
char c = clientTCP.read();
if (c == ‘\n’)
{
if (getAll.length()==0) state=true;
getAll = “”;
}
else if (c != ‘\r’)
getAll += String(c);
if (state==true) getBody += String(c);
startTimer = millis();
}
if (getBody.length()>0) break;
}
clientTCP.stop();
Serial.println(getBody);
}
else {
getBody=”Connected to api.telegram.org failed.”;
Serial.println(“Connected to api.telegram.org failed.”);
}
return getBody;
}
void setup(){
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);
// Init Serial Monitor
Serial.begin(115200);
// Set LED Flash as output
pinMode(FLASH_LED_PIN, OUTPUT);
digitalWrite(FLASH_LED_PIN, flashState);
//SPIFFS.format();
//read configuration from FS json
Serial.println(“mounting FS…”);
if (SPIFFS.begin()) {
Serial.println(“mounted file system”);
if (SPIFFS.exists(“/config.json”)) {
//file exists, reading and loading
Serial.println(“reading config file”);
File configFile = SPIFFS.open(“/config.json”, “r”);
if (configFile) {
Serial.println(“opened config file”);
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr buf(new char[size]);
configFile.readBytes(buf.get(), size);
#if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6
DynamicJsonDocument json(1024);
auto deserializeError = deserializeJson(json, buf.get());
serializeJson(json, Serial);
if ( ! deserializeError ){
#else
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
json.printTo(Serial);
// if (json.success()) {
#endif
Serial.println(“\nparsed json”);
strcpy(chat_id, json[“chat_id”]);
strcpy(bot_token, json[“bot_token”]);
} else {
Serial.println(“failed to load json config”);
}
configFile.close();
}
}
} else {
Serial.println(“failed to mount FS”);
}
//end read
//Telegram parameters
AsyncWiFiManagerParameter custom_chat_id(“chat_id”, “chat id”, chat_id, 100);
AsyncWiFiManagerParameter custom_bot_token(“bot_token”, “bot token”, bot_token, 100);
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
AsyncWiFiManager wifiManager(&server, &dns);
//set config save notify callback
wifiManager.setSaveConfigCallback(saveConfigCallback);
wifiManager.addParameter(&custom_chat_id);
wifiManager.addParameter(&custom_bot_token);
//scheduled reset
//WiFiManager
AsyncWiFiManagerParameter custom_text(“Seleccione la red WiFi para conectarse.”);
wifiManager.addParameter(&custom_text);
//reset saved settings OJOJO DESCOMENTAR PARA OLVIDARLAS CREDENCIALES
//wifiManager.resetSettings();
//set custom ip for portal
//wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
//fetches ssid and pass from eeprom and tries to connect
//if it does not connect it starts an access point with the specified name
//here “AutoConnectAP”
//and goes into a blocking loop awaiting configuration
wifiManager.autoConnect(“Iberotecno AP”);
//or use this for auto generated name ESP + ChipID
//wifiManager.autoConnect();
//if you get here you have connected to the WiFi
Serial.println(“connected…yeey :)”);
//read updated parameters
strcpy(chat_id, custom_chat_id.getValue());
strcpy(bot_token, custom_bot_token.getValue());
//save the custom parameters to FS
if (shouldSaveConfig) {
Serial.println(“saving config”);
#if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6
DynamicJsonDocument json(1024);
#else
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
#endif
json[“chat_id”] = chat_id;
json[“bot_token”] = bot_token;
File configFile = SPIFFS.open(“/config.json”, “w”);
if (!configFile) {
Serial.println(“failed to open config file for writing”);
}
#if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6
serializeJson(json, Serial);
serializeJson(json, configFile);
#else
json.printTo(Serial);
json.printTo(configFile);
#endif
configFile.close();
//end save
}
clientTCP.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
Serial.println(“local ip”);
Serial.println(WiFi.localIP());
// Config and init the camera
configInitCamera();
// Connect to Wi-Fi
//WiFi.mode(WIFI_STA);
//Serial.println();
//Serial.print(“Connecting to “);
//Serial.println(ssid);
//WiFi.begin(ssid, password);
//clientTCP.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
//while (WiFi.status() != WL_CONNECTED) {
//Serial.print(“.”);
//delay(500);
//}
//Serial.println();
//Serial.print(“ESP32-CAM IP Address: “);
//Serial.println(WiFi.localIP());
}
void loop() {
if (sendPhoto) {
Serial.println(“Preparing photo”);
sendPhotoTelegram();
sendPhoto = false;
}
if (millis() > lastTimeBotRan + botRequestDelay) {
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);
}
lastTimeBotRan = millis();
}
}
Hi.
I’ll be out of the office during the next week. I can’t test your code.
If you’re more specific about the errors you get and in which parts of the code you have errors, maybe I can help.
Regards,
Sara
thanks for your answer i was trying everything but i have the same problem detailed here
https://forum.arduino.cc/t/cannot-get-wifi-manager-telegram-library-working-together/694455
check if someone was able to insert wifimanager to the esp32 cam camera the data of the Id chat and token enter correctly in the wifimanager once inside the void loop it does not receive the commands sent from the phone (telegram) my code is the following, please help me in making it work thanks
#include <FS.h> //library to access the filesystem
#include <WiFiClientSecure.h>
#ifdef ESP32
#include “SPIFFS.h”
#endif
#define ESP_DRD_USE_SPIFFS true
#include <ESPAsyncWebServer.h> //https://github.com/alanswx/ESPAsyncWiFiManager
#include <ESPAsyncWiFiManager.h>
/* ======================================== Including the libraries. */
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include “soc/soc.h”
#include “soc/rtc_cntl_reg.h”
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
#define JSON_CONFIG_FILE “/test_config.json”
/* ======================================== */
//define custom fields
char chatid[20];
char bot_token[100];
#define ONBOARD_LED 2
//flag for saving data
bool shouldSaveConfig = false;
//callback notifying us of the need to save config
void saveConfigCallback () {
Serial.println(“Should save config”);
shouldSaveConfig = true;
}
AsyncWebServer server(80);
DNSServer dns;
//SimpleTimer timer;
/* ======================================== Variables for network. */
// REPLACE WITH YOUR NETWORK CREDENTIALS
//const char* ssid = “”; //–> Enter your SSID / your WiFi network name.
//const char* password = “”; //–> Enter your WiFi password.
/* ======================================== */
/* ======================================== Variables for telegram bot tokens. */
String BOTtoken;// = bot_token; //–> your Bot Token (Get from Botfather).
/* ======================================== */
/* ======================================== @myidbot ID */
// Use @myidbot to find out the chat ID of an individual or a group.
// Also note that you need to click “start” on a bot before it can message you.
String CHAT_ID;// = chatid;
/* ======================================== */
/* ======================================== Initialize WiFiClientSecure. */
WiFiClientSecure clientTCP;
/* ======================================== */
/* ======================================== Initialize UniversalTelegramBot. */
UniversalTelegramBot bot(BOTtoken, clientTCP);
/* ======================================== */
/* ======================================== Variables for millis. */
// Checks for new messages every 1 second (1000 ms).
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;
/* ======================================== */
/* ======================================== Defines HIGH and LOW with ON and OFF (for LED FLash). */
#define ON HIGH
#define OFF LOW
/* ======================================== */
#define FLASH_LED_PIN 4 //–> LED Flash PIN (GPIO 4)
/* ________________________________________________________________________________ Subroutine to turn on or off the LED Flash. */
void LEDFlash_State (bool ledState) {
digitalWrite(FLASH_LED_PIN, ledState);
}
/* ________________________________________________________________________________ */
void handleNewMessages(int numNewMessages) {
Serial.print(“Handle New Messages: “);
Serial.println(numNewMessages);
/* —————————————- “For Loop” to check the contents of the newly received message. */
for (int i = 0; i < numNewMessages; i++) {
/* ::::::::::::::::: Check ID (ID obtained from IDBot/@myidbot). */
/*
* If the chat_id is different from your chat ID (CHAT_ID), it means that someone (that is not you) has sent a message to your bot.
* If that’s the case, ignore the message and wait for the next message.
*/
String chat_id = String(bot.messages[i].chat_id);
if (chat_id != CHAT_ID){
bot.sendMessage(chat_id, “Unauthorized user”, “”);
Serial.println(“Unauthorized user”);
Serial.println(“————“);
continue;
}
/* ::::::::::::::::: */
/* ::::::::::::::::: Print the received message. */
String text = bot.messages[i].text;
Serial.print(“Incoming command/message : “);
Serial.println(text);
/* ::::::::::::::::: */
/* ::::::::::::::::: Check conditions based on commands sent from your telegram BOT. */
// If it receives the “/start” message, we’ll send the valid commands to control the ESP. This is useful if you happen to forget what are the commands to control your board.
String send_feedback_message = “”;
String from_name = bot.messages[i].from_name;
// The condition if the command received is “/start”.
if (text == “/start”) {
Serial.println(“Reply to the start command.”);
send_feedback_message += “From the ESP32-CAM :\n\n”;
send_feedback_message += “Welcome , ” + from_name + “\n”;
send_feedback_message += “Use the following commands to interact with the ESP32-CAM \n”;
send_feedback_message += “/ping_esp32cam : Send ping to test connection\n”;
send_feedback_message += “/led_flash_on : Turn on the LED Flash\n”;
send_feedback_message += “/led_flash_off : Turn off the LED Flash”;
bot.sendMessage(CHAT_ID, send_feedback_message, “”);
Serial.println(“————“);
}
// The condition if the command received is “/ping_esp32cam”.
if (text == “/ping_esp32cam”) {
Serial.println(“Reply to the ping command.”);
send_feedback_message += “From the ESP32-CAM :\n\n”;
send_feedback_message += “The ESP32 CAM replies to the ping command.\n”;
send_feedback_message += “Connection OK.\n\n”;
send_feedback_message += “/start : to see all commands.”;
bot.sendMessage(CHAT_ID, send_feedback_message, “”);
Serial.println(“————“);
}
// The condition if the command received is “/led_flash_on”.
if (text == “/led_flash_on”) {
LEDFlash_State(ON);
Serial.println(“LED Flash ON.”);
Serial.println(“Reply to the led_flash_on command.”);
send_feedback_message += “From the ESP32-CAM :\n\n”;
send_feedback_message += “The ESP32 CAM replies to the led_flash_on command.\n”;
send_feedback_message += “LED Flash ON.\n\n”;
send_feedback_message += “/start : to see all commands.”;
bot.sendMessage(CHAT_ID, send_feedback_message, “”);
Serial.println(“————“);
}
// The condition if the command received is “/led_flash_off”.
if (text == “/led_flash_off”) {
LEDFlash_State(OFF);
Serial.println(“LED Flash OFF.”);
Serial.println(“Reply to the led_flash_off command.”);
send_feedback_message += “From the ESP32-CAM :\n\n”;
send_feedback_message += “The ESP32 CAM replies to the led_flash_off command.\n”;
send_feedback_message += “LED Flash OFF.\n\n”;
send_feedback_message += “/start : to see all commands.”;
bot.sendMessage(CHAT_ID, send_feedback_message, “”);
Serial.println(“————“);
}
/* ::::::::::::::::: */
}
/* —————————————- */
}
/* ________________________________________________________________________________ Subroutines to handle what to do after a new message arrives. */
/* ________________________________________________________________________________ */
/* ________________________________________________________________________________ VOID SETTUP() */
void setup(){
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //–> Disable brownout detector.
/* —————————————- Init serial communication speed (baud rate). */
Serial.begin(115200);
delay(1000);
Serial.println(“\n”);
/* —————————————- */
SPIFFS.format();
//read configuration from FS json
Serial.println(“mounting FS…”);
if (SPIFFS.begin()) {
Serial.println(“mounted file system”);
if (SPIFFS.exists(“/config.json”)) {
//file exists, reading and loading
Serial.println(“reading config file”);
File configFile = SPIFFS.open(“/config.json”, “r”);
if (configFile) {
Serial.println(“opened config file”);
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
#if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6
DynamicJsonDocument json(1024);
auto deserializeError = deserializeJson(json, buf.get());
serializeJson(json, Serial);
if ( ! deserializeError ){
#else
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.parseObject(buf.get());
json.printTo(Serial);
//if (json.success()) {
#endif
Serial.println(“\nparsed json”);
strcpy(chatid, json[“chatid”]);
strcpy(bot_token, json[“bot_token”]);
} else {
Serial.println(“failed to load json config”);
}
configFile.close();
}
}
} else {
Serial.println(“failed to mount FS”);
}
//end read
//Telegram parameters
AsyncWiFiManagerParameter custom_chat_id(“chatid”, “chatid”, chatid, 100);
AsyncWiFiManagerParameter custom_bot_token(“bot_token”, “bot token”, bot_token, 100);
//WiFiManager
//Local intialization. Once its business is done, there is no need to keep it around
AsyncWiFiManager wifiManager(&server, &dns);
//set config save notify callback
wifiManager.setSaveConfigCallback(saveConfigCallback);
wifiManager.addParameter(&custom_chat_id);
wifiManager.addParameter(&custom_bot_token);
//scheduled reset
// int horas = 1; // hours for scheduled reset
// timer.setInterval(horas * 3600000, reinicio);
//WiFiManager
AsyncWiFiManagerParameter custom_text(“<p>Seleccione la red WiFi para conectarse.</p>”);
wifiManager.addParameter(&custom_text);
//reset saved settings
wifiManager.resetSettings();
//set custom ip for portal
//wifiManager.setAPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));
//fetches ssid and pass from eeprom and tries to connect
//if it does not connect it starts an access point with the specified name
//here “AutoConnectAP”
//and goes into a blocking loop awaiting configuration
wifiManager.autoConnect(“Iberotecno AP”);
//or use this for auto generated name ESP + ChipID
//wifiManager.autoConnect();
//if you get here you have connected to the WiFi
Serial.println(“connected…yeey :)”);
clientTCP.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
//read updated parameters
strcpy(chatid, custom_chat_id.getValue());
strcpy(bot_token, custom_bot_token.getValue());
//save the custom parameters to FS
if (shouldSaveConfig) {
Serial.println(“saving config”);
#if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6
DynamicJsonDocument json(1024);
#else
DynamicJsonBuffer jsonBuffer;
JsonObject& json = jsonBuffer.createObject();
#endif
json[“chatid”] = chatid;
json[“bot_token”] = bot_token;
File configFile = SPIFFS.open(“/config.json”, “w”);
if (!configFile) {
Serial.println(“failed to open config file for writing”);
}
#if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6
serializeJson(json, Serial);
serializeJson(json, configFile);
#else
json.printTo(Serial);
json.printTo(configFile);
#endif
configFile.close();
//end save
}
Serial.println(“local ip”);
Serial.println(WiFi.localIP());
/* —————————————- Set LED Flash as output and make the initial state of the LED Flash is off. */
pinMode(FLASH_LED_PIN, OUTPUT);
LEDFlash_State(OFF);
/* —————————————- */
String CHAT_ID = String (chatid);
String BOTtoken = String (bot_token);
/* —————————————- Connect to Wi-Fi. */
//WiFi.mode(WIFI_STA);
//Serial.println(“————“);
//Serial.print(“Connecting to “);
//Serial.println(ssid);
//WiFi.begin(ssid, password);
//clientTCP.setCACert(TELEGRAM_CERTIFICATE_ROOT); //–> Add root certificate for api.telegram.org
/* ::::::::::::::::: The process of connecting ESP32 CAM with WiFi Hotspot / WiFi Router. */
/*
* The process timeout of connecting ESP32 CAM with WiFi Hotspot / WiFi Router is 20 seconds.
* If within 20 seconds the ESP32 CAM has not been successfully connected to WiFi, the ESP32 CAM will restart.
* I made this condition because on my ESP32-CAM, there are times when it seems like it can’t connect to WiFi, so it needs to be restarted to be able to connect to WiFi.
*/
int connecting_process_timed_out = 20; //–> 20 = 20 seconds.
connecting_process_timed_out = connecting_process_timed_out * 2;
while (WiFi.status() != WL_CONNECTED) {
Serial.print(“.”);
LEDFlash_State(ON);
delay(250);
LEDFlash_State(OFF);
delay(250);
if(connecting_process_timed_out > 0) connecting_process_timed_out–;
if(connecting_process_timed_out == 0) {
delay(1000);
ESP.restart();
}
}
/* ::::::::::::::::: */
LEDFlash_State(OFF);
Serial.println();
Serial.print(“Successfully connected to “);
//Serial.println(ssid);
Serial.print(“ESP32-CAM IP Address: “);
//clientTCP.setCACert(TELEGRAM_CERTIFICATE_ROOT); //–> Add root certificate for api.telegram.org
Serial.println(WiFi.localIP());
Serial.println(“————“);
Serial.println();
Serial.println(CHAT_ID);
Serial.println(BOTtoken);
/* —————————————- */
pinMode(ONBOARD_LED,OUTPUT);
}
/* ________________________________________________________________________________ */
/* ________________________________________________________________________________ VOID LOOP() */
void loop() {
/* —————————————- Condition to check if any new messages come in. */
// Checks for new messages every 1 second (see “botRequestDelay” value).
if (millis() > lastTimeBotRan + botRequestDelay) {
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while (numNewMessages) {
Serial.println();
Serial.println(“————“);
Serial.println(“Got response”);
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
lastTimeBotRan = millis();
}
delay(1000);
digitalWrite(ONBOARD_LED,HIGH);
Serial.println(“led is on”);
delay(1000);
digitalWrite(ONBOARD_LED,LOW);
Serial.println(“led is off”);
}
Hi again.
You’re using a library that I’m not familiar with.
Many people have reported issues when trying to integrate WiFiManager libraries with other projects.
I think you may try to get some help from the developer of that library.
Or you can build your own wi-fi manager based on the example project we have on our “Build Web Servers” eBook.
Regards,
Sara
thank you very much for your answer but I can’t get help, I also tried with your library and I get the same result I really feel disappointed by your very kind answer here I send my code your answer is appreciated in advance
/*********
Rui Santos
Complete instructions at https://RandomNerdTutorials.com/esp32-wi-fi-manager-asyncwebserver/
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*********/
#include <Arduino.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <ESPAsyncWiFiManager.h>
#include <AsyncTCP.h>
#include “SPIFFS.h”
#include <WiFiClientSecure.h>
#include “soc/soc.h”
#include “soc/rtc_cntl_reg.h”
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
WiFiClientSecure clientTCP;
// Checks for new messages every 1 second (1000 ms).
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;
#define ON HIGH
#define OFF LOW
#define FLASH_LED_PIN 4 //–> LED Flash PIN (GPIO
void LEDFlash_State (bool ledState) {
digitalWrite(FLASH_LED_PIN, ledState);
}
// Search for parameter in HTTP POST request
const char* PARAM_INPUT_1 = “ssid”;
const char* PARAM_INPUT_2 = “pass”;
const char* PARAM_INPUT_3 = “ip”;
const char* PARAM_INPUT_4 = “gateway”;
const char* PARAM_INPUT_5 = “chatId”;
const char* PARAM_INPUT_6 = “BOTtoken”;
//Variables to save values from HTML form
String ssid;
String pass;
String ip;
String gateway;
String chatId= “”;
String BOTtoken= “”;
UniversalTelegramBot bot(BOTtoken, clientTCP);
// File paths to save input values permanently
const char* ssidPath = “/ssid.txt”;
const char* passPath = “/pass.txt”;
const char* ipPath = “/ip.txt”;
const char* gatewayPath = “/gateway.txt”;
const char* chatIdPath = “/chatId.txt”;
const char* BOTtokenPath = “/BOTtoken.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);
// Timer variables
unsigned long previousMillis = 0;
const long interval = 10000; // interval to wait for Wi-Fi connection (milliseconds)
// Set LED GPIO
const int ledPin = 2;
// Stores LED state
#define ONBOARD_LED 2
String ledState;
// Initialize SPIFFS
void initSPIFFS() {
if (!SPIFFS.begin(true)) {
Serial.println(“An error has occurred while mounting SPIFFS”);
}
Serial.println(“SPIFFS mounted successfully”);
}
// Read File from SPIFFS
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 SPIFFS
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(“- frite failed”);
}
}
// Initialize WiFi
bool initWiFi() {
if(ssid==”” || ip==””){
Serial.println(“Undefined SSID or IP address.”);
return false;
}
WiFi.mode(WIFI_STA);
localIP.fromString(ip.c_str());
localGateway.fromString(gateway.c_str());
if (!WiFi.config(localIP, localGateway, subnet)){
Serial.println(“STA Failed to configure”);
return false;
}
WiFi.begin(ssid.c_str(), pass.c_str());
Serial.println(“Connecting to WiFi…”);
clientTCP.setCACert(TELEGRAM_CERTIFICATE_ROOT); //–> Add root certificate for api.telegram.org
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.println(WiFi.localIP());
return true;
}
// Replaces placeholder with LED state value
String processor(const String& var) {
if(var == “STATE”) {
if(digitalRead(ledPin)) {
ledState = “ON”;
}
else {
ledState = “OFF”;
}
return ledState;
}
return String();
}
void handleNewMessages(int numNewMessages) {
Serial.print(“Handle New Messages: “);
Serial.println(numNewMessages);
/* —————————————- “For Loop” to check the contents of the newly received message. */
for (int i = 0; i < numNewMessages; i++) {
/* ::::::::::::::::: Check ID (ID obtained from IDBot/@myidbot). */
/*
* If the chat_id is different from your chat ID (CHAT_ID), it means that someone (that is not you) has sent a message to your bot.
* If that’s the case, ignore the message and wait for the next message.
*/
String chat_id = String(bot.messages[i].chat_id);
if (chat_id != chatId){
bot.sendMessage(chat_id, “Unauthorized user”, “”);
Serial.println(“Unauthorized user”);
Serial.println(“————“);
continue;
}
/* ::::::::::::::::: */
/* ::::::::::::::::: Print the received message. */
String text = bot.messages[i].text;
Serial.print(“Incoming command/message : “);
Serial.println(text);
/* ::::::::::::::::: */
/* ::::::::::::::::: Check conditions based on commands sent from your telegram BOT. */
// If it receives the “/start” message, we’ll send the valid commands to control the ESP. This is useful if you happen to forget what are the commands to control your board.
String send_feedback_message = “”;
String from_name = bot.messages[i].from_name;
// The condition if the command received is “/start”.
if (text == “/start”) {
Serial.println(“Reply to the start command.”);
send_feedback_message += “From the ESP32-CAM :\n\n”;
send_feedback_message += “Welcome , ” + from_name + “\n”;
send_feedback_message += “Use the following commands to interact with the ESP32-CAM \n”;
send_feedback_message += “/ping_esp32cam : Send ping to test connection\n”;
send_feedback_message += “/led_flash_on : Turn on the LED Flash\n”;
send_feedback_message += “/led_flash_off : Turn off the LED Flash”;
bot.sendMessage(chatId, send_feedback_message, “”);
Serial.println(“————“);
}
// The condition if the command received is “/ping_esp32cam”.
if (text == “/ping_esp32cam”) {
Serial.println(“Reply to the ping command.”);
send_feedback_message += “From the ESP32-CAM :\n\n”;
send_feedback_message += “The ESP32 CAM replies to the ping command.\n”;
send_feedback_message += “Connection OK.\n\n”;
send_feedback_message += “/start : to see all commands.”;
bot.sendMessage(chatId, send_feedback_message, “”);
Serial.println(“————“);
}
// The condition if the command received is “/led_flash_on”.
if (text == “/led_flash_on”) {
LEDFlash_State(ON);
Serial.println(“LED Flash ON.”);
Serial.println(“Reply to the led_flash_on command.”);
send_feedback_message += “From the ESP32-CAM :\n\n”;
send_feedback_message += “The ESP32 CAM replies to the led_flash_on command.\n”;
send_feedback_message += “LED Flash ON.\n\n”;
send_feedback_message += “/start : to see all commands.”;
bot.sendMessage(chatId, send_feedback_message, “”);
Serial.println(“————“);
}
// The condition if the command received is “/led_flash_off”.
if (text == “/led_flash_off”) {
LEDFlash_State(OFF);
Serial.println(“LED Flash OFF.”);
Serial.println(“Reply to the led_flash_off command.”);
send_feedback_message += “From the ESP32-CAM :\n\n”;
send_feedback_message += “The ESP32 CAM replies to the led_flash_off command.\n”;
send_feedback_message += “LED Flash OFF.\n\n”;
send_feedback_message += “/start : to see all commands.”;
bot.sendMessage(chatId, send_feedback_message, “”);
Serial.println(“————“);
}
/* ::::::::::::::::: */
}
/* —————————————- */
}
void setup() {
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);
// Serial port for debugging purposes
Serial.begin(115200);
initSPIFFS();
// Set GPIO 2 as an OUTPUT
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin, LOW);
// Load values saved in SPIFFS
ssid = readFile(SPIFFS, ssidPath);
pass = readFile(SPIFFS, passPath);
ip = readFile(SPIFFS, ipPath);
gateway = readFile (SPIFFS, gatewayPath);
chatId = readFile(SPIFFS, chatIdPath);
BOTtoken = readFile(SPIFFS, BOTtokenPath);
Serial.println(ssid);
Serial.println(pass);
Serial.println(ip);
Serial.println(gateway);
Serial.println(chatId);
Serial.println(BOTtoken);
if(initWiFi()) {
// Route for root / web page
server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(SPIFFS, “/index.html”, “text/html”, false, processor);
});
server.serveStatic(“/”, SPIFFS, “/”);
// Route to set GPIO state to HIGH
server.on(“/on”, HTTP_GET, [](AsyncWebServerRequest *request) {
digitalWrite(ledPin, HIGH);
request->send(SPIFFS, “/index.html”, “text/html”, false, processor);
});
// Route to set GPIO state to LOW
server.on(“/off”, HTTP_GET, [](AsyncWebServerRequest *request) {
digitalWrite(ledPin, LOW);
request->send(SPIFFS, “/index.html”, “text/html”, false, processor);
});
server.begin();
}
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(SPIFFS, “/wifimanager.html”, “text/html”);
});
server.serveStatic(“/”, SPIFFS, “/”);
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()){
// 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(SPIFFS, 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(SPIFFS, passPath, pass.c_str());
}
// HTTP POST ip value
if (p->name() == PARAM_INPUT_3) {
ip = p->value().c_str();
Serial.print(“IP Address set to: “);
Serial.println(ip);
// Write file to save value
writeFile(SPIFFS, ipPath, ip.c_str());
}
// HTTP POST gateway value
if (p->name() == PARAM_INPUT_4) {
gateway = p->value().c_str();
Serial.print(“Gateway set to: “);
Serial.println(gateway);
// Write file to save value
writeFile(SPIFFS, gatewayPath, gateway.c_str());
}
if (p->name() == PARAM_INPUT_5) {
chatId = p->value().c_str();
Serial.print(“chatId set to: “);
Serial.println(chatId);
// Write file to save value
writeFile(SPIFFS, chatIdPath, chatId.c_str());
}
if (p->name() == PARAM_INPUT_6) {
BOTtoken = p->value().c_str();
Serial.print(“BOTtoken set to: “);
Serial.println(BOTtoken);
// Write file to save value
writeFile(SPIFFS, BOTtokenPath, BOTtoken.c_str());
}
Serial.printf(“POST[%s]: %s\n”, p->name().c_str(), p->value().c_str());
}
}
request->send(200, “text/plain”, “Done. ESP will restart, connect to your router and go to IP address: ” + ip);
delay(3000);
ESP.restart();
});
server.begin();
}
/* —————————————- */
pinMode(ONBOARD_LED,OUTPUT);
}
void loop() {
// Checks for new messages every 1 second (see “botRequestDelay” value).
if (millis() > lastTimeBotRan + botRequestDelay) {
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while (numNewMessages) {
Serial.println();
Serial.println(“————“);
Serial.println(“Got response”);
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
lastTimeBotRan = millis();
}
delay(1000);
digitalWrite(ONBOARD_LED,HIGH);
Serial.println(“led is on”);
delay(1000);
digitalWrite(ONBOARD_LED,LOW);
Serial.println(“led is off”);
}