Version 1.0 à tester
This commit is contained in:
1 parent
e5598884c6
commit
d510422e16
6 files changed
+177
-5
No files matched your search
@@ -10,15 +10,16 @@ avec un payload <On/Off>
|
||||
## 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 <topic>/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é <topic>/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 `<topic>/status` et utilise `offline` comme message Last Will.
|
||||
- L'ESP écoute `<topic>/#` et commande la sortie correspondante avec les topics `<topic>/gpio<numéro>` 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 :
|
||||
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
#pragma once
|
||||
|
||||
void setupMqtt(void);
|
||||
void loopMqtt(void);
|
||||
@@ -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
|
||||
+3
-1
@@ -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();
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
#include <Arduino.h>
|
||||
#include <PubSubClient.h>
|
||||
#include <WiFi.h>
|
||||
#include <driver/gpio.h>
|
||||
|
||||
#include <cstring>
|
||||
|
||||
#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<uint32_t>(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<gpio_num_t>(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<uint8_t>(pin), OUTPUT);
|
||||
digitalWrite(static_cast<uint8_t>(pin), turnOn ? HIGH : LOW);
|
||||
Serial.printf("GPIO %u : %s\n", static_cast<unsigned int>(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();
|
||||
}
|
||||
@@ -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, "")) {
|
||||
|
||||
Reference in new issue
Block a user