I have created a ESP8266 project connected to my house alarm it will send messages via the Telegram App when it is triggered. The WiFi and Telegram credentials were hard coded and I wanted a way to be able to alter them easily. I have tried to do this by using Wifimanager which will open a AP portal where I can enter all the parameters and write to littleFS.
The wifimanager code works fine as I expected - It will save the WiFi and Telegram credentials and I can write them to the serial port OK. The problems came when I tried to incorporate this into the original code. I think the issue is that the Telegram credentials are not been passed to the function - UniversalTelegramBot bot(BOTtoken, client). When you look in the code I'm sure you will see it is in the wrong place, but I have tried allsorts of things but I cannot get it to communicate with Telegram. I have had to remove some (hopefully irrelevent) code to be able to upload it. I suspect it's something stupid but with my current knowledge I'm struggling! I am using the 6.17.2 version of arduinojson. Any help greatly appreciated.
#include <FS.h>
#include <LittleFS.h>
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
char function_option[2];
char chat_id[20];
char telegram_token[50];
char function[2] = "9";
char chat[20] = "MY chat_id";
char BOTtoken[50] = "MY telegram_token";
const char* ssid;
bool shouldSaveConfig = false;
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
unsigned long elapsedTime = 0; //Number of millis elapsed
int messageCount = 0; // Number of messages sent after bell triggered
int maxMessages = 9; //Max number of times that the "Alarm has been triggered" message will be sent
int setReading; // the current reading from the input pin
int setPrevious = LOW; // the previous reading from the input pin
int delayBetweenChecks = 1000; //milliseconds between checking for messages
unsigned long lastTimeChecked; //last time messages' scan has been done
boolean bellRinging = false;
void saveConfigCallback () { //callback notifying us of the need to save config
Serial.println("Void saveConfiCallback Loop");
shouldSaveConfig = true;
}
void setupLittleFS() {
Serial.println(" Void setupLittleFS loop");
if (LittleFS.begin()) { // Check to see if the file system has been set-up OK
Serial.println("mounted file system");
if (LittleFS.exists("/config.json")) { //****If a file exists, open and read to configFile
//file exists, reading and loading
Serial.println("reading config file");
File configFile = LittleFS.open("/config.json", "r");
if (configFile) {
Serial.println("opened config file");
size_t size = configFile.size();
Serial.println("Config file Size: ");
Serial.print(size);
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonDocument doc(200);
DeserializationError error = deserializeJson(doc, buf.get());
if (!error) {
Serial.println("");
Serial.println("Parsed Json.......");
const char* function_option = doc["function_option"];
const char* chat_id = doc["chat_id"];
const char* telegram_token = doc["telegram_token"];
const char* function = function_option;
const char* chat = chat_id;
const char* BOTtoken = telegram_token;
Serial.println (function_option);
Serial.println (chat_id);
Serial.println (telegram_token);
Serial.println("");
char fsSetupLoop[] = "This is from the FS Setup loop!!";
} else {
Serial.println("failed to load json config");
}
}
}
} else {
Serial.println("failed to mount FS");
}
}
void setup() {
Serial.begin(115200);
Serial.println();
Serial.println("VOID SETUP");
setupLittleFS();
WiFiManager wm;
wm.setSaveConfigCallback(saveConfigCallback);//set config save notify callback
WiFiManagerParameter custom_function_option("server", "Function Option", function_option, 2);
WiFiManagerParameter custom_telegram_token("api", "Telegram Token", telegram_token, 50);
WiFiManagerParameter custom_chat_id("port", "Chat ID", chat_id, 20);
wm.addParameter(&custom_function_option); //add all your parameters here......
wm.addParameter(&custom_telegram_token);
wm.addParameter(&custom_chat_id);
//automatically connect using saved credentials if they exist
//If connection fails it starts an access point with the specified name
//here "AutoConnectAP" if empty will auto generate basedcon chipid, if password is blank it will be anonymous
//and goes into a blocking loop awaiting configuration
if (!wm.autoConnect("AutoConnectAP", "password")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
// if we still have not connected restart and try all over again
ESP.restart();
delay(5000);
}
Serial.println("connected to WiFi...yeey :)");
//read updated parameters
strcpy(function_option, custom_function_option.getValue()); //These below may need to be changed************************************************
strcpy(chat_id, custom_chat_id.getValue());
strcpy(telegram_token, custom_telegram_token.getValue());
//save the custom parameters to FS
if (shouldSaveConfig) { // This loops saves the parameters if required and is onlyexecurted when no saved parameters or cannot connect?
Serial.println("saving config");
DynamicJsonDocument doc(200);
doc["function_option"] = function_option;
doc["chat_id"] = chat_id;
doc["telegram_token"] = telegram_token;
File configFile = LittleFS.open("/config.json", "w");// W is for writing to the SPIFFS file from configFile
if (!configFile) {
Serial.println("failed to open config file for writing");
}
serializeJson(doc, configFile);//*************modified***********
configFile.close();
//end save
shouldSaveConfig = false;
}
Serial.println("local ip");
Serial.println(WiFi.localIP());
Serial.println(WiFi.gatewayIP());
Serial.println(WiFi.subnetMask());
File configFile = LittleFS.open("/config.json", "r");
if (configFile) {
Serial.println("opened config file");
size_t size = configFile.size();
Serial.println("Config file Size: ");
Serial.print(size);
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonDocument doc(200);
DeserializationError error = deserializeJson(doc, buf.get());
if (!error) {
Serial.println("");
Serial.println("Parsed Json.......");
const char* function_option = doc["function_option"];
strcpy ( function, (const char*)doc["function_option"]); // TEST
const char* chat_id = doc["chat_id"];
strcpy ( chat, (const char*)doc["chat_id"]); // TEST
const char* telegram_token = doc["telegram_token"];
strcpy ( BOTtoken, (const char*)doc["telegram_token"]); // TEST
Serial.println ("These are the parameters in the setup loop");
Serial.println (function);
Serial.println (chat);
Serial.println (BOTtoken);
Serial.println("");
} else {
Serial.println("failed to load json config");
}
}
}
void handleNewMessages(int numNewMessages) { //******This loop needs altering to reflect this sketch*******
for (int i = 0; i < numNewMessages; i++) {
// If the type is a "callback_query", a inline keyboard button was pressed
if (bot.messages[i].type == F("callback_query")) {
String text = bot.messages[i].text;
}
}
}
void loop() {
Serial.println("Void Loop");
Serial.println (function);
Serial.println (chat);
Serial.println (BOTtoken);
bot.sendMessage(chat, "***Message sent from Void Loop***", "");
if (millis() > lastTimeChecked + delayBetweenChecks) {
// getUpdates returns 1 if there is a new message from Telegram
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
if (numNewMessages) {
Serial.println("got response");
handleNewMessages(numNewMessages);
}
lastTimeChecked = millis();
}
}