Closed iPhilBln closed 3 years ago
I am interested in this topic. I need to use Wifimanager with Universal arduino telegram. Can someone help
hello friends i soved this problem using ESP8266
//NTP server
//Telegram bot
//lista de permissao telegram
String validSenderIds[SENDER_ID_COUNT] = {"2222222", "1111111"};
//variaveis bot telegram uint32_t lastCheckTime = 0; const String STATS = "/status"; const String STATUSID = "/statusid"; const String START = "/start";
//configs bot telegram X509List cert(TELEGRAM_CERTIFICATE_ROOT); WiFiClientSecure secured_client; UniversalTelegramBot bot(BOT_TOKEN, secured_client);
//config NTP WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "pool.ntp.org");
//wifiManager button
//variavel de millis atual uint32_t now;
void setup() {
Serial.begin(9600);
sensor.begin(); //inicializacao sensor de temperatura
//definicao botao do wifiManeger pinMode(TRIGGER_PIN, INPUT);
//definicao de cliente telegram secured_client.setTrustAnchors(&cert);
}
void loop() { now = millis(); //captura milissegundo atual
if ( digitalRead(TRIGGER_PIN) == LOW ) { //wifiManeger OnDemand WiFiManager wifiManager;
if (!wifiManager.startConfigPortal(Dispositivo_ID)){
printSerial("failed to connect and hit timeout",1);
delay(3000);
ESP.reset();
delay(5000);
}
printSerial("connected...yeey :)",1);
//secured_client.setTrustAnchors(&cert);
for(int x = 0; x<SENDER_ID_COUNT; x++){ //apos conexao avisa o status do dispositivo via telegram
handleStatus(validSenderIds[x]);
}
}
//loop Internet connected if (WiFi.status() == WL_CONNECTED){
//verifica novas mensagens no telegram
if (now - timer > intervalo){
timer = now;
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
handleNewMessages(numNewMessages);
}
} }
I am interested in this topic. I need to use Wifimanager with Universal arduino telegram. Can someone help
we also solved our problem. at first its better you use the original wifiManager from tzapu which works very well with universal telegram bot. we used the development branch of wifiManager because we use the ESP32 but there are also examples for the ESP2688. we also seperated our code in different functions and call them into the loop if we need them. we've coded them in different tabs.
here are some snippets of our code:
Main page:
/****************************************************************************************************************************
Autor: Philipp Mielke, Paul Eichner, Joe Fierek, Svenja Meißner
Projekt: smarter Briefkasten
Datum: 07.03.2021
*****************************************************************************************************************************/
//initialisiert das Dateisystem indem die nötigen Bibliotheken eingebunden werden
#include <FS.h> //muss als Erstes angegeben werden
#include <SPIFFS.h>
FS* filesystem = &SPIFFS;
//nötige Bibliotheken der verschiedenen Funktionen
//#include <DNSServer.h>
//#include <WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <WiFi.h> //https://github.com/esp8266/Arduino
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h> //https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
#include <MFRC522.h> //library responsible for communicating with the module RFID-RC522
#include <SPI.h> //library responsible for communicating of SPI bus
//hier werden die nötigen Pins definiert
#define LED_BUILTIN 1 // Pin D1 mapped to pin GPIO1/ADC12 of ESP32, control on-board LED
#define schloss 12 // Pin D12 mapped to schloss
#define REED 34 // Pin D34 mapped to reed contact
#define WifiReset 35 // Pin D35 mapped to wifi/reset button
#define RedLed 32 // Pin D32 mapped to the red led
#define GreenLed 33 // Pin D33 mapped to the green led
#define mosi 23 // Pin D23 mapped to mosi from rfid
#define rst 22 // Pin D22 mapped to reset from rfid
#define sda 21 // Pin D21 mapped to sda from rfid
#define miso 19 // Pin D19 mapped to miso from rfid
#define sck 18 // Pin D18 mapped to sck from rfi
//wird für die Authentifizierung verwendet
MFRC522::MIFARE_Key key;
//Authentifizierung die den Statuscode zurückgibt
MFRC522::StatusCode status;
//definiert die Pins für das Modul RC522
MFRC522 mfrc522(sda, rst);
WiFiClientSecure secured_client;
//Difinition der globen Variablen auf die alle Funktionen zugreifen können
char telegram_chatID[40];
char telegram_token[70];
char schloss_notfall[5] = "nein";
int card_uid[10][4] = {0, 0, 0, 0};
bool wifi_merker = false; //Anzeige, dass die Wifi Verbindung verloren wurde
bool telegram_init_fertig = false; //wird benötigt um den Telegrambot einmalig in der Loopfunktion zu Initialisieren
unsigned long timer_wifi_start = 0; //Zeit um die rote Led zu toggeln bei Wlan Ausfall während des Betriebs
bool timer_wifi_laeuft = false; //true wenn noch auf die Verzögerung gewartet wird
bool daten_speichern = false; //flag um die Daten zu speichern
bool wifi_verbindung_verloren = false; //Flag um den User zu benachrichtigen, dass die Wifi Verbindung verloren wurde
unsigned long karte_eingelesen_start = 0; //Zeit um die grüne Led zu togglen wenn eine Karte eingelesen wurde
bool karte_eingelesen_laeuft = false; //Flag für den Timer nachdem eine Karte erfolgreich eingelesen wurde
unsigned long beginn_oeffnung = 0; //Zeit zu der das das Schloss aufgegangen ist
bool timer_schloss_laeuft = false; //Flag für den Timer, dass das Schloss offen ist
unsigned long wifi_setup_start = 0; //Zeit zu der der WifiReset Button gedrückt wurde
bool wifi_setup_laeuft = false; //Flag, dass der WifiReset Button gedrückt wurde
bool karte_gespeichert = false; //Flag, wenn eine Karte gespeichert wurde
bool karte_geloescht = false; //Flag, wenn eine Karte gelöscht wurde
unsigned long timerNachrichtStart = 0; //Startzeit wann die Post eingegangen ist
bool timerNachrichtLaeuft = false; // true, wenn noch auf die Verzögerung gewartet wird
const uint8_t SECTOR_COUNT = 16;
const uint8_t BYTES_PER_BLOCK = 16;
byte success_counter = 0; //Zähler für RFID Funktion
byte fail_status = 0; //Merker für den Fall, dass bei der RFID Einlesefunktion etwas schiefgegangen ist
byte karte_fertig_eingelesen = 0; //Flag, die gesetzt wird, wenn die Karte fertig eingelesen ist
void setup()
{
Serial.begin(115200);
while (!Serial);
SPI.begin();
//Initialisiert die Leds als Ausgänge
pinMode(LED_BUILTIN, OUTPUT);
pinMode(RedLed, OUTPUT);
pinMode(GreenLed, OUTPUT);
//Initialisiert das Schloss als Ausgang
pinMode(schloss, OUTPUT);
//Initlialisiert die Eingänge
pinMode(WifiReset, INPUT);
pinMode(REED, INPUT);
//Initilialisierung des MFRC522
mfrc522.PCD_Init();
digitalWrite(GreenLed, !LOW);
digitalWrite(RedLed, !HIGH);
//hier können beim Bootvorgang die Wifi/Telegram/RFID Einstellungen zurückgesetzt werden
resetEinstellungen();
//hier wird des Wifi Setup Portal aufgerufen
wifiSettings();
//wenn wir hier angekommen sind, ist der ESP mit dem Wifi verbunden
//Serial.println("local ip");
//Serial.println(WiFi.localIP());
digitalWrite(RedLed, !LOW);
}
void loop() {
if(!karte_gespeichert)
digitalWrite(GreenLed, !HIGH);
else
digitalWrite(GreenLed, !LOW);
if(!karte_geloescht)
digitalWrite(RedLed, !LOW);
else
digitalWrite(RedLed, !HIGH);
//Initialisierung des Telegram Bots
//Benachrichtigung des Benutzers, dass der Bot online ist
if(!telegram_init_fertig)
telegramInit();
//wenn alle Karten verloren gegangen sein sollten, lässt sich hiermit das Schloss
//über den Wifi AP notfalls öffnen
if(strcmp(schloss_notfall, "ja") == 0 || strcmp(schloss_notfall, "Ja") == 0 || timer_schloss_laeuft)
schlossOeffnen("ja");
//bei Posteingang wird die Nachricht per Telegram übermittelt
//Timer wird gestartet damit nur alle 30s eine Benachrichtigung erfolgt
posteingang();
//hiermit kann der Briefkasten per RFID Sender geöffnet werden
//es können neue Karten angelernt werden
//es können alte Karten gelöscht werden
rfid();
//überprüft den aktuellen Verbindungsstatus
//rote Led blinkt mit 1Hz bei verlorener Verbindung
//ebenfalls lässt sich das Wifi Setup Portal über den Wifi Taster öffnen
//nach 10 Minuten startet der ESP automatisch neu und öffnet den AP
wifiCheck();
//wenn der WifiReset Taster für 10 Sekunden gedrückt gehalten wird lässt sich
//auch während des Betriebs das WifiSetupPortal öffnen
wifiSetup();
}
filesystem:
//speichert die Telegram Daten, RFID Card UIDs permanent im Dateisystem
//speichert den Wert um das Schloss notfalls über den AP zu öffnen
void datenSpeichern()
{
//Serial.println("Json Datei wird gelöscht um die Daten neu zu speichern.");
SPIFFS.remove("/config.json");
File konfigurationsdatei = SPIFFS.open("/config.json", "w");
if (!konfigurationsdatei)
{
//Serial.println("Es konnte nicht auf das Dateisystem geschrieben werden.");
}
//Serial.println("Konfigurationsdatei wird gespeichert.");
const size_t json_speicherplatz = JSON_ARRAY_SIZE(40)+1024;
DynamicJsonDocument json(json_speicherplatz);
json["telegram_chatID"] = telegram_chatID;
json["telegram_token"] = telegram_token;
json["schloss_notfall"] = schloss_notfall;
for(int i = 0; i < 10;i++)
{
for(int j = 0; j < 4; j++)
json["Card UIDs"][i][j] = card_uid[i][j];
}
//serializeJson(json, Serial);
serializeJson(json, konfigurationsdatei);
konfigurationsdatei.close();
json.clear();
//Serial.println();
}
//liest die Konfigurationsdatei im json Format vom Dateisystem
void datenLesen()
{
//Serial.println("Dateisystem wird geladen...");
if (SPIFFS.begin()) {
//Serial.println("Dateisystem wurde geladen.");
if (SPIFFS.exists("/config.json")) {
//Datei existiert, wird gelesen und geladen
//Serial.println("Die Konfigurationsdatei wird eingelesen.");
File konfigurationsdatei = SPIFFS.open("/config.json", "r");
if (konfigurationsdatei) {
//Serial.println("Konfigurationsdatei wurde geöffnet.");
size_t size = konfigurationsdatei.size();
//reserviert Speicher um den Eingabestrom in der Datei zu speichern
std::unique_ptr<char[]> buf(new char[size]);
konfigurationsdatei.readBytes(buf.get(), size);
const size_t json_speicherplatz = JSON_ARRAY_SIZE(40)+1024;
DynamicJsonDocument json(json_speicherplatz);
auto deserializeError = deserializeJson(json, buf.get());
serializeJson(json, Serial);
if (!deserializeError ) {
//Serial.println("\nparsed json");
strcpy(telegram_chatID, json["telegram_chatID"]);
strcpy(telegram_token, json["telegram_token"]);
strcpy(schloss_notfall, json["schloss_notfall"]);
for(int i = 0; i < 10;i++)
{
for(int j = 0; j < 4; j++)
card_uid[i][j] = json["Card UIDs"][i][j];
}
arrayAusgeben();
}
else
{
//Serial.println("Die Konfigurationsdatei konnte nicht geöffnet werden.");
}
konfigurationsdatei.close();
}
}
} else {
//Serial.println("Das Dateisystem konnte nicht geöffnet werden.");
}
}
wifi code:
//hiermit können sämtliche Wifi Einstellungen, Telegramdaten und RFID Chips gelöscht werden
void resetEinstellungen()
{
//hier können beim Bootvorgang die Wifi Einstellungen zurückgesetzt werden
if(digitalRead(WifiReset) == HIGH)
{
//Serial.println("Alle Einstellungen werden zurückgesetzt.");
WiFiManager wifiManager;
wifiManager.resetSettings();
//Serial.println("SPIFFS löschen.");
SPIFFS.format();
delay(1000);
//Serial.println("Neustart.");
ESP.restart();
delay(5000);
}
}
//Callback Funktion für die eigegebenen Wifi-Daten
void saveWifiCallback(){
//Serial.println("[CALLBACK] saveCallback fired");
}
//Aufruf für den Wifi Accespoint um die Wifi und Telegram Daten einzutragen oder das Schloss im Notfall zu öffnen
void wifiSettings()
{
digitalWrite(GreenLed, !LOW);
digitalWrite(RedLed, !HIGH);
//liest die aktuellen Daten vom Dateisystem
datenLesen();
//Extraparameter die über das Wifi Setup Portal übergeben werden können (global oder lokal im Setup)
//nach erfolgreicher Verbindung können die Parameter mit parameter.getValue() abgerufen werden
// id/name placeholder/prompt default length
WiFiManagerParameter custom_telegram_chatID("telegram_chatID", "Telegram Chat ID", telegram_chatID, 40);
WiFiManagerParameter custom_telegram_token("telegram_token", "Telegram Token", telegram_token, 70);
WiFiManagerParameter custom_schloss_notfall("schloss_notfall", "Notfallöffnung des Schlosses", schloss_notfall, 5);
//WiFiManager Initialisierung
WiFiManager wifiManager;
//aktiviert den DarkMode als Theme
wifiManager.setClass("invert");
//speichern der Einstellungen aus dem Wifimanager und Benachrichtigung
wifiManager.setSaveConfigCallback(saveWifiCallback);
wifiManager.setBreakAfterConfig(true);
//verhindert Race-Conditions mit der Wifi-Verbindung und dem WiFiManager
//löst die Verbindung auf, bevor er sich wieder mit dem Wifi verbindet
wifiManager.setCleanConnect(true);
//Einstellungen für eine statische IP
wifiManager.setAPStaticIPConfig(IPAddress(10, 1, 1, 1), IPAddress(10, 1, 1, 1), IPAddress(255, 255, 255, 0));
//Einstellung um das aktuelle Land zu setzen
wifiManager.setCountry("US");
//hinzufügen der manuellen Parameter die im Wifi Setup Portal angezeigt werden
wifiManager.addParameter(&custom_telegram_chatID);
wifiManager.addParameter(&custom_telegram_token);
wifiManager.addParameter(&custom_schloss_notfall);
//Minimum der Signalqualität der vorhandenen Wifi Netzwerke die dem User angezeigt werden
//standardmäßig 8%
//wifiManager.setMinimumSignalQuality();
//aktiviert das Timeout des Wifi Setup Portals um erneut zu starten
//in Sekunden
wifiManager.setTimeout(120);
//holt sich die SSID und das Passwort, um sich mit dem bekannten Netzwerk zu verbinden
//wenn das nicht funktioniert hat, wird der Accesspoint gestart mit dem spezifischen Namen und Passwort
//hier: AP:"Briefkasten Wifi Setup" Passwort:"Briefkastensetup"
//blockt den rest des Codes solange das Wifi Setup Portal geöffnet ist
//Bedingung ist, dass das SetupPortal nicht manuel aufgerufen werden soll
if (digitalRead(WifiReset) == LOW && !wifi_setup_laeuft && !wifiManager.autoConnect("Briefkasten WiFi Setup", "Briefkastensetup"))
{
//Serial.println("Verbindung fehlgeschlagen und die Zeit ist abgelaufen.");
delay(3000);
//Restart des ESPs um es erneut zu versuchen
ESP.restart();
delay(1000);
}
//hierüber kann der AP auch während des Betriebs geöffnet werden
if(digitalRead(WifiReset) == HIGH && wifi_setup_laeuft)
{
wifiManager.startConfigPortal("Briefkasten WiFi Setup", "Briefkastensetup");
}
//jetzt ist der Briefkasten online
//Serial.println("Der Briefkasten ist online");
//liest die aktuellen Parameter ein
strcpy(telegram_chatID, custom_telegram_chatID.getValue());
strcpy(telegram_token, custom_telegram_token.getValue());
strcpy(schloss_notfall, custom_schloss_notfall.getValue());
//Serial.println("Folgende Daten wurden vom AP gespeichert: ");
//Serial.println("\ttelegram_chatID : " + String(telegram_chatID));
//Serial.println("\ttelegram_token : " + String(telegram_token));
//Serial.println("\tschloss_notfall : " + String(schloss_notfall));
//speichert die aktualisierten Daten im Dateisystem ab
datenSpeichern();
}
//Funktion um die aktuelle Wifi Verbindung zu überprüfen
//der ESP wird sich automatisch innerhalb von 10 Minuten mit der gespeicherten
//Wifi Verbindung erneut verbinden
//andernfalls startet er neu und baut einen Accesspoint auf
//bei vorlerener Verbindung lässt sich über den WifiReset Button der Accesspoint aufrufen
//die rote Led blinkt mit 1Hz
void wifiCheck()
{
timer_wifi_laeuft = false;
int i = 0;
unsigned long wifi_lost = millis();
while(WiFi.status() != WL_CONNECTED)
{
wifi_verbindung_verloren = true;
telegram_init_fertig = false;
digitalWrite(GreenLed, !LOW);
if(!timer_wifi_laeuft)
{
digitalWrite(RedLed, !digitalRead(RedLed));
timer_wifi_start = millis();
timer_wifi_laeuft = true;
}
if(timer_wifi_laeuft && ((millis() - timer_wifi_start) >= 1000))
{
timer_wifi_laeuft = false;
i++;
if(i>9)
{
//Serial.println();
//Serial.print(__DATE__);
//Serial.print(" ");
//Serial.print(__TIME__);
//Serial.print(": ");
//Serial.print("Wifi Verbindung wurde verloren.");
i = 0;
}
}
if(millis() - wifi_lost >= 600000)
ESP.restart();
if(digitalRead(WifiReset) == HIGH)
{
digitalWrite(RedLed, !HIGH);
//Serial.println("Die Wifi Einstellungen werden geöffnet.");
wifi_verbindung_verloren = false;
//ruft den AP auf
wifi_setup_laeuft = true;
wifiSettings();
wifi_setup_laeuft = false;
}
}
}
//hierüber lässt sich das WifiSetupPortal auch während des Betriebs aufrufen
//dafür muss der WifiReset Taster 10 Sekunden gedrückt gehalten werden
void wifiSetup()
{
if(digitalRead(WifiReset) == HIGH && !wifi_setup_laeuft)
{
wifi_setup_start = millis();
wifi_setup_laeuft = true;
}
if(digitalRead(WifiReset) == HIGH && wifi_setup_laeuft && ((millis() - wifi_setup_start) >= 10000))
{
wifiSettings();
wifi_setup_laeuft = false;
}
if(digitalRead(WifiReset) == LOW && wifi_setup_laeuft)
{
wifi_setup_laeuft = false;
}
}
telegram bot:
//Funktion um mit dem Telegrambot Nachrichten zu senden
void telegramMessage(const char* message)
{
UniversalTelegramBot bot(telegram_token, secured_client);
bot.sendMessage(telegram_chatID, message, "");
}
//Initialiserung des Telegrambots bei vorhandener Wifi Verbindung
void telegramInit()
{
int zaehler = 0;
bool timer = false;
unsigned long timerStart = 0;
//es wird gewartet solange keine Wifi Verbindung hergestellt ist
//rote Led blinkt mit 5 Hz
while(WiFi.status() != WL_CONNECTED)
{
digitalWrite(GreenLed, !LOW);
if(!timer)
{
digitalWrite(RedLed, !digitalRead(RedLed));
timerStart = millis();
timer = true;
}
if(timer && ((millis() - timerStart) >= 200))
{
timer = false;
zaehler++;
if(zaehler>45)
{
//Serial.println("Wifi Verbindung wurde verloren.");
zaehler = 0;
}
}
}
//root Zertifikat für api.telegram.org wird hinzugefügt
secured_client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
//holt sich die UTC Zeit via NTP
//Serial.println("Retrieving time: ");
configTime(0, 0, "pool.ntp.org");
time_t now = time(nullptr);
while (now < 24 * 3600)
{
//Serial.print(".");
delay(100);
now = time(nullptr);
}
//Serial.println(now);
//jetzt ist der Bot online
if(!wifi_verbindung_verloren)
telegramMessage("Der Briefkasten ist online.");
else
{
telegramMessage("Der Briefkasten hat zwischenzeitlich die Internetverbindung verloren und ist jetzt wieder online.\nBitte überprüfe, ob Post angekommen ist.");
wifi_verbindung_verloren = false;
}
telegram_init_fertig = true;
}
You see, after any new wifi connection we initialize the telegram bot and send our messages with this function:
telegramMessage("string to send the message you want");
Hi dudes. We have problems with our connection if we use the WifiManager. So is it possible to use both of them in one sketch? Maybe its helpful to post our sketch.