Bonjour à tous,
Dans un projet de domotic de ma maison et de mon jardin, j'ai plusieurs ESP32 qui communiquent avec un serveur sous RapberryPi 4. Tout fonctionne bien mais j'ai quelques soucis de reconnexion automatique de mes ESP32 lorsque mon réseau wifi de ma box est instable. Je suis obligé la plupart du temps d'appuyer sur le bouton de reboot de chaque ESP32 pour retrouver une connectivité.
J'aimerais pour faciliter le déploiment de mes projets faire un sketch qui serve de base pour tous mes projets et qui intègre une routine de redémarrage automatique de l'ESP32 en cas de déconnexion.
J'ai crée une fonction qui reboot l'ESP32 au bout de 30 secondes si la connexion Wifi est perdu.
Une fonction reconnect()
de la bibliothèque PubSubClient relance la connexion au serveur MQTT toutes les 5 secondes si la connexion au serveur est perdu.
Voici le code :
// _________________________________________________________ Connection wifi __________________________________________________________
#include <WiFi.h>
#define ssid "###"
#define password "######"
unsigned long tempsPrecedentRedemarrage = 0;
unsigned long tempsPrecedentStatusWifi = 0;
unsigned long tempsDeRebootESP = 30000;
const int tempsDeStatusWifi = 3000;
//___________________________________________________________ WIFI __________________________________________________________________
void setupWifi() {
Serial.println("\n");
WiFi.begin(ssid, password);
Serial.print("Tentative de connexion...");
while(WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.println("\n");
Serial.println("Connexion etablie : ");
Serial.print("Adresse IP : ");
Serial.println(WiFi.localIP());
Serial.print("Force du signal RSSI: ");
Serial.println(WiFi.RSSI());
delay(1000);
}
// ________________________________________________________ Connection au borker MOSQUITTO ____________________________________________________________
#include <PubSubClient.h>
#define mqtt_server "192.168.####"
const char* mqttUser = "#############";
char message_buff[100];
long lastMsg = 0;
// long lastRecu = 0;
bool debug = false;
char msg[50];
int value = 0;
String consigne;
WiFiClient espClient;
PubSubClient client(espClient);
// ----------------- déclaration des topics de souscription MQTT --------------------
// String callbackOuvertureFermeturePortail;
// String callbackOuverturePortailPortillon;
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
payload[length]='\0';
String cons = String((char*)payload);
consigne = cons;
Serial.println();
// -------------------- Exécution des souscription au topic MQTT ----------------------------------
/*
if(topic[9] == 'v') { // On va choisir le bon topic que l'on veut recupérer avec des lettres ici la lettre o de osmolation.
payload[length]='\0'; // Ensuite on recupére la valeur entière (length) du topic.
callbackOuvertureFermeturePortail = String((char*)payload); // On la stock dans une variable pour l'utiliser ailleurs dans le code.
Serial.println();
} else if (topic[7] == 'p') {
payload[length]='\0';
callbackOuverturePortailPortillon = String((char*)payload);
Serial.println();
}*/
}
void reconnect(){ //Boucle jusqu'à obtenur une reconnexion
while (!client.connected()) {
Serial.println("Connexion au serveur MQTT...");
if (client.connect("Titre de l'ESP32", mqttUser, mqttPassword )) {
Serial.println("Connexion réussie à : Titre de l'ESP32");
// ------------------------------------------------- Souscription au topic nodered ----------------------------------------
/*
client.subscribe("Relais/ouverture/portail");
client.subscribe("Relais/fermeture/portail");
client.subscribe("Relais/portillon");
*/
debug = true;
} else {
Serial.println("Erreur de connexion au serveur MQTT : ");
debug = false;
Serial.println("5 secondes avant de recommencer une tentative de connexion");
delay(5000);
}
}
}
// ----------------- Déclaration des abonnements MQTT ----------------------------
//#define sonde1_topic "Etat/capteur/portail/ferme"
// ______________________________________________________________________________ SETUP ____________________________________________________________________________________
void setup() {
Serial.begin(115200);
setupWifi();
delay(1000);
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
// ______________________________________________________________________________ LOOP ____________________________________________________________________________________
void loop() {
client.loop();
unsigned long tempsActuelStatus = millis();
if (( WiFi.status() == WL_CONNECTED ) && ( tempsActuelStatus - tempsPrecedentStatusWifi ) >= tempsDeStatusWifi ) {
Serial.print("ESP32 correctement connnecter au reseau wifi : ");
Serial.println(WiFi.SSID());
tempsPrecedentStatusWifi = tempsActuelStatus;
}
if ( WiFi.status() != WL_CONNECTED ) {
Serial.println("Problème de connection de l'ESP32");
unsigned long tempsActuelRedemarrage = millis();
if ((tempsActuelRedemarrage - tempsPrecedentRedemarrage) >= tempsDeRebootESP ) {
Serial.println("preparation au reboot ESP32");
delay(3000);
Serial.println("Reboot de l'ESP32");
ESP.restart();
tempsPrecedentRedemarrage = tempsActuelRedemarrage;
}
}
if (!client.connected()) {
reconnect();
}
}
Le code vous parait il ok ou des améliorations sont à apporter pour rendre encore plus stable la connexion ?