From d510422e161c4707d6f967e5f4a7ee6b5a67ff23 Mon Sep 17 00:00:00 2001 From: Serge NOEL Date: Sat, 31 Oct 2026 11:30:06 +0100 Subject: [PATCH] =?UTF-8?q?Version=201.0=20=C3=A0=20tester?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 9 +-- include/mqtt.h | 4 ++ platformio.ini | 1 + src/main.cpp | 4 +- src/mqtt.cpp | 152 +++++++++++++++++++++++++++++++++++++++++++++++++ src/wifi.cpp | 12 ++++ 6 files changed, 177 insertions(+), 5 deletions(-) create mode 100644 include/mqtt.h create mode 100644 src/mqtt.cpp diff --git a/README.md b/README.md index df9b0de..0a309a4 100644 --- a/README.md +++ b/README.md @@ -10,15 +10,16 @@ avec un payload ## Fonctionnalités - **Configuration Wi-Fi** avec WiFiManager. Le point d'accès de configuration porte un nom `Legende-XXXX`, où `XXXX` correspond aux deux derniers octets de l'adresse MAC. -- **Paramètres MQTT** (serveur, utilisateur, mot de passe et topic) saisis dans le portail et enregistrés en EEPROM. Le client MQTT n'est pas encore implémenté. - - Lors de l'allumage, publication de l'état dur /status (NB: voir comment déterminer si l'ESP répond - keepalive ?) - - L'ESP écoute le topic pour recevoir des ordres ON/OFF sur le GPIO désigné /gpio payload +- **Commandes MQTT** : le serveur, l'utilisateur, le mot de passe et le topic sont saisis dans le portail et enregistrés en EEPROM. + - L'ESP publie l'état conservé `online` sur `/status` et utilise `offline` comme message Last Will. + - L'ESP écoute `/#` et commande la sortie correspondante avec les topics `/gpio` et les payloads `On` ou `Off`. + - La reconnexion au broker est tentée automatiquement toutes les cinq secondes. - **Mise à jour du firmware** par ArduinoOTA après connexion au Wi-Fi. ## Prérequis et compilation -Installer Visual Studio Code avec l'extension PlatformIO IDE, ou PlatformIO Core. La cible et la dépendance WiFiManager sont définies dans [`platformio.ini`](./platformio.ini). +Installer Visual Studio Code avec l'extension PlatformIO IDE, ou PlatformIO Core. La cible et les dépendances WiFiManager et PubSubClient sont définies dans [`platformio.ini`](./platformio.ini). Depuis la racine du projet : diff --git a/include/mqtt.h b/include/mqtt.h new file mode 100644 index 0000000..02c7c79 --- /dev/null +++ b/include/mqtt.h @@ -0,0 +1,4 @@ +#pragma once + +void setupMqtt(void); +void loopMqtt(void); \ No newline at end of file diff --git a/platformio.ini b/platformio.ini index 78a3149..ba2e6d3 100644 --- a/platformio.ini +++ b/platformio.ini @@ -9,6 +9,7 @@ monitor_filters = esp32_exception_decoder lib_compat_mode = strict lib_deps = tzapu/WiFiManager@^2.0.17 + knolleary/PubSubClient@^2.8 build_flags = -D LANG_FR \ No newline at end of file diff --git a/src/main.cpp b/src/main.cpp index c156ebe..98ef57a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -4,6 +4,7 @@ #include "eeprom_storage.h" #include "ota.h" #include "wifi_config.h" +#include "mqtt.h" /** @@ -27,7 +28,7 @@ void setup() WifiSetup(); Serial.print("SSID: "); Serial.println(myConfig.ssid); - //setupMQTT(); + setupMqtt(); OtaSetup(); } @@ -35,4 +36,5 @@ void loop() { OtaLoop(); WifiLoop(); delay(100); + loopMqtt(); } \ No newline at end of file diff --git a/src/mqtt.cpp b/src/mqtt.cpp new file mode 100644 index 0000000..7a7ecd7 --- /dev/null +++ b/src/mqtt.cpp @@ -0,0 +1,152 @@ +#include +#include +#include +#include + +#include + +#include "main.h" +#include "mqtt.h" +#include "wifi_config.h" + +namespace { +WiFiClient networkClient; +PubSubClient mqttClient(networkClient); +String commandTopicPrefix; +String subscriptionTopic; +String statusTopic; +uint32_t lastConnectionAttempt = 0; +bool mqttInitialized = false; + +constexpr uint32_t ReconnectIntervalMs = 5000; + +bool isConfiguredValue(const char* value) { + return value[0] != '\0' && strcmp(value, "undefined") != 0; +} + +void handleMqttMessage(char* topic, uint8_t* payload, unsigned int length) { + const size_t prefixLength = commandTopicPrefix.length(); + const size_t topicLength = strlen(topic); + if (topicLength <= prefixLength || + strncmp(topic, commandTopicPrefix.c_str(), prefixLength) != 0) { + return; + } + + uint32_t pin = 0; + for (size_t i = prefixLength; i < topicLength; ++i) { + const char digit = topic[i]; + if (digit < '0' || digit > '9') { + Serial.println("Commande MQTT ignorée : le topic doit se terminer par un numéro GPIO."); + return; + } + + pin = pin * 10 + static_cast(digit - '0'); + if (pin >= GPIO_NUM_MAX) { + Serial.println("Commande MQTT ignorée : numéro GPIO hors limites."); + return; + } + } + + const gpio_num_t gpio = static_cast(pin); + if (!GPIO_IS_VALID_OUTPUT_GPIO(gpio)) { + Serial.println("Commande MQTT ignorée : ce GPIO ne peut pas être utilisé en sortie."); + return; + } + + const bool turnOn = length == 2 && payload[0] == 'O' && payload[1] == 'n'; + const bool turnOff = length == 3 && payload[0] == 'O' && + payload[1] == 'f' && payload[2] == 'f'; + if (!turnOn && !turnOff) { + Serial.println("Commande MQTT ignorée : le payload doit être « On » ou « Off »."); + return; + } + + pinMode(static_cast(pin), OUTPUT); + digitalWrite(static_cast(pin), turnOn ? HIGH : LOW); + Serial.printf("GPIO %u : %s\n", static_cast(pin), turnOn ? "On" : "Off"); +} + +void connectMqttIfDue() { + if (mqttClient.connected() || WiFi.status() != WL_CONNECTED) { + return; + } + + const uint32_t now = millis(); + if (now - lastConnectionAttempt < ReconnectIntervalMs) { + return; + } + lastConnectionAttempt = now; + + uint8_t mac[6]; + WiFi.macAddress(mac); + char clientId[24]; + snprintf(clientId, sizeof(clientId), "Legende-%02X%02X%02X", mac[3], mac[4], mac[5]); + + const char* mqttUser = isConfiguredValue(myConfig.mqtt_user) ? myConfig.mqtt_user : ""; + const char* mqttPassword = + isConfiguredValue(myConfig.mqtt_passw) ? myConfig.mqtt_passw : ""; + Serial.println("Connexion au broker MQTT..."); + bool connected; + if (mqttUser[0] != '\0' || mqttPassword[0] != '\0') { + connected = mqttClient.connect( + clientId, mqttUser, mqttPassword, + statusTopic.c_str(), 1, true, "offline"); + } else { + connected = mqttClient.connect( + clientId, statusTopic.c_str(), 1, true, "offline"); + } + + if (!connected) { + Serial.print("Échec de connexion au broker MQTT, rc="); + Serial.println(mqttClient.state()); + return; + } + + Serial.println("Connecté au broker MQTT !"); + if (!mqttClient.subscribe(subscriptionTopic.c_str())) { + Serial.println("Échec de l'abonnement aux commandes MQTT."); + } + if (!mqttClient.publish(statusTopic.c_str(), "online", true)) { + Serial.println("Échec de publication de l'état MQTT."); + } +} +} + +void setupMqtt(void) { + if (mqttClient.connected()) { + mqttClient.disconnect(); + } + mqttInitialized = false; + + if (!isConfiguredValue(myConfig.mqtt_server) || !isConfiguredValue(myConfig.topic)) { + Serial.println("Configuration MQTT absente : serveur et topic requis."); + return; + } + + String topic = myConfig.topic; + while (topic.endsWith("/") && topic.length() > 0) { + topic.remove(topic.length() - 1); + } + if (topic.length() == 0) { + Serial.println("Configuration MQTT invalide : le topic est vide."); + return; + } + + commandTopicPrefix = topic + "/gpio"; + subscriptionTopic = topic + "/#"; + statusTopic = topic + "/status"; + + mqttClient.setServer(myConfig.mqtt_server, 1883); + mqttClient.setCallback(handleMqttMessage); + mqttInitialized = true; + lastConnectionAttempt = millis() - ReconnectIntervalMs; +} + +void loopMqtt(void) { + if (!mqttInitialized) { + return; + } + + connectMqttIfDue(); + mqttClient.loop(); +} diff --git a/src/wifi.cpp b/src/wifi.cpp index c314340..008d438 100644 --- a/src/wifi.cpp +++ b/src/wifi.cpp @@ -7,6 +7,7 @@ #include "eeprom_storage.h" #include "main.h" +#include "mqtt.h" #include "wifi_config.h" MyConfig myConfig; @@ -46,6 +47,16 @@ bool setStationCredentials(const MyConfig& config) { } return true; } + +void saveMqttParameters() { + copyConfigString(myConfig.mqtt_server, sizeof(myConfig.mqtt_server), customMqttServer.getValue()); + copyConfigString(myConfig.mqtt_user, sizeof(myConfig.mqtt_user), customMqttUser.getValue()); + copyConfigString(myConfig.mqtt_passw, sizeof(myConfig.mqtt_passw), customMqttPassword.getValue()); + copyConfigString(myConfig.topic, sizeof(myConfig.topic), customTopic.getValue()); + SaveConfig(); + Serial.println("Paramètres MQTT enregistrés depuis le portail web."); + setupMqtt(); +} } /** @@ -73,6 +84,7 @@ void WifiSetup(void) { wifiManager.setWebServerCallback([]() { Serial.println("Page de configuration web accessible."); }); + wifiManager.setSaveParamsCallback(saveMqttParameters); if (!WiFi.mode(WIFI_STA) || !setStationCredentials(myConfig) || !wifiManager.autoConnect(accessPointName, "")) {