Add reconnect method to PsychicMqttClient for improved MQTT client management
This commit introduces a new `reconnect` method in the `PsychicMqttClient` class, allowing for re-establishing a connection to the MQTT broker without needing to disconnect first. The method checks if the client is initialized, updates the configuration if necessary, and attempts to reconnect, enhancing the overall connection management. Additionally, the MQTT slot management has been updated to support up to 6 configurable slots, improving flexibility in connection handling.
This commit is contained in:
1 parent
af52a989c4
commit
1b5884bd35
7 files changed
+239
-108
No files matched your search
@@ -311,6 +311,19 @@ void PsychicMqttClient::connect()
|
||||
ESP_LOGI(TAG, "MQTT client started.");
|
||||
}
|
||||
|
||||
void PsychicMqttClient::reconnect()
|
||||
{
|
||||
if (_client == nullptr)
|
||||
{
|
||||
ESP_LOGW(TAG, "MQTT client not initialized, cannot reconnect.");
|
||||
return;
|
||||
}
|
||||
// Update config in case credentials changed (e.g., refreshed JWT token)
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(esp_mqtt_set_config(_client, &_mqtt_cfg));
|
||||
ESP_ERROR_CHECK_WITHOUT_ABORT(esp_mqtt_client_reconnect(_client));
|
||||
ESP_LOGI(TAG, "MQTT client reconnect requested.");
|
||||
}
|
||||
|
||||
void PsychicMqttClient::disconnect()
|
||||
{
|
||||
if (_client == nullptr)
|
||||
|
||||
@@ -301,6 +301,16 @@ public:
|
||||
*/
|
||||
void connect();
|
||||
|
||||
/**
|
||||
* @brief Reconnects a previously started MQTT client.
|
||||
*
|
||||
* Uses esp_mqtt_client_reconnect() which is the correct API for
|
||||
* re-initiating a connection on an already-started client, especially
|
||||
* when auto-reconnect is disabled. Updates config before reconnecting
|
||||
* so credential changes (e.g., refreshed JWT tokens) take effect.
|
||||
*/
|
||||
void reconnect();
|
||||
|
||||
/**
|
||||
* @brief Disconnects the MQTT client from the server.
|
||||
* This call might be blocking until the client is stopped cleanly
|
||||
|
||||
+83
-21
@@ -291,13 +291,15 @@ static void setMQTTPrefsDefaults(MQTTPrefs* prefs) {
|
||||
prefs->mqtt_raw_enabled = 0; // disabled by default
|
||||
prefs->mqtt_tx_enabled = 0; // disabled by default (RX only)
|
||||
prefs->mqtt_status_interval = 300000; // 5 minutes default
|
||||
// Slot presets: analyzer-us and analyzer-eu enabled by default, slot 3 = none
|
||||
// Slot presets: analyzer-us and analyzer-eu enabled by default, rest = none
|
||||
strncpy(prefs->mqtt_slot_preset[0], "analyzer-us", sizeof(prefs->mqtt_slot_preset[0]) - 1);
|
||||
prefs->mqtt_slot_preset[0][sizeof(prefs->mqtt_slot_preset[0]) - 1] = '\0';
|
||||
strncpy(prefs->mqtt_slot_preset[1], "analyzer-eu", sizeof(prefs->mqtt_slot_preset[1]) - 1);
|
||||
prefs->mqtt_slot_preset[1][sizeof(prefs->mqtt_slot_preset[1]) - 1] = '\0';
|
||||
strncpy(prefs->mqtt_slot_preset[2], "none", sizeof(prefs->mqtt_slot_preset[2]) - 1);
|
||||
prefs->mqtt_slot_preset[2][sizeof(prefs->mqtt_slot_preset[2]) - 1] = '\0';
|
||||
for (int i = 2; i < MAX_MQTT_SLOTS; i++) {
|
||||
strncpy(prefs->mqtt_slot_preset[i], "none", sizeof(prefs->mqtt_slot_preset[i]) - 1);
|
||||
prefs->mqtt_slot_preset[i][sizeof(prefs->mqtt_slot_preset[i]) - 1] = '\0';
|
||||
}
|
||||
#ifdef MQTT_WIFI_POWER_SAVE_DEFAULT
|
||||
prefs->wifi_power_save = MQTT_WIFI_POWER_SAVE_DEFAULT; // 0=min, 1=none, 2=max
|
||||
#else
|
||||
@@ -378,8 +380,54 @@ void CommonCLI::loadMQTTPrefs(FILESYSTEM* fs) {
|
||||
// Save migrated prefs in new format
|
||||
saveMQTTPrefs(fs);
|
||||
}
|
||||
} else if (file_size > 0 && file_size <= sizeof(ThreeSlotMQTTPrefs)) {
|
||||
// 3-slot format → 6-slot migration
|
||||
// Array sizes changed from [3] to [6], shifting all field offsets.
|
||||
// Read into old layout struct and field-copy to new layout.
|
||||
ThreeSlotMQTTPrefs old3;
|
||||
memset(&old3, 0, sizeof(old3));
|
||||
size_t bytes_to_read = file_size < sizeof(old3) ? file_size : sizeof(old3);
|
||||
size_t bytes_read = file.read((uint8_t *)&old3, bytes_to_read);
|
||||
file.close();
|
||||
|
||||
if (bytes_read > 0) {
|
||||
MESH_DEBUG_PRINTLN("MQTT: Migrating 3-slot prefs to 6-slot layout");
|
||||
|
||||
// Copy non-slot fields (identical layout)
|
||||
memcpy(_mqtt_prefs.mqtt_origin, old3.mqtt_origin, sizeof(_mqtt_prefs.mqtt_origin));
|
||||
memcpy(_mqtt_prefs.mqtt_iata, old3.mqtt_iata, sizeof(_mqtt_prefs.mqtt_iata));
|
||||
_mqtt_prefs.mqtt_status_enabled = old3.mqtt_status_enabled;
|
||||
_mqtt_prefs.mqtt_packets_enabled = old3.mqtt_packets_enabled;
|
||||
_mqtt_prefs.mqtt_raw_enabled = old3.mqtt_raw_enabled;
|
||||
_mqtt_prefs.mqtt_tx_enabled = old3.mqtt_tx_enabled;
|
||||
_mqtt_prefs.mqtt_status_interval = old3.mqtt_status_interval;
|
||||
memcpy(_mqtt_prefs.wifi_ssid, old3.wifi_ssid, sizeof(_mqtt_prefs.wifi_ssid));
|
||||
memcpy(_mqtt_prefs.wifi_password, old3.wifi_password, sizeof(_mqtt_prefs.wifi_password));
|
||||
_mqtt_prefs.wifi_power_save = old3.wifi_power_save;
|
||||
memcpy(_mqtt_prefs.timezone_string, old3.timezone_string, sizeof(_mqtt_prefs.timezone_string));
|
||||
_mqtt_prefs.timezone_offset = old3.timezone_offset;
|
||||
|
||||
// Copy slot fields for indices 0-2 from old layout
|
||||
for (int i = 0; i < 3; i++) {
|
||||
memcpy(_mqtt_prefs.mqtt_slot_preset[i], old3.mqtt_slot_preset[i], sizeof(_mqtt_prefs.mqtt_slot_preset[i]));
|
||||
memcpy(_mqtt_prefs.mqtt_slot_host[i], old3.mqtt_slot_host[i], sizeof(_mqtt_prefs.mqtt_slot_host[i]));
|
||||
_mqtt_prefs.mqtt_slot_port[i] = old3.mqtt_slot_port[i];
|
||||
memcpy(_mqtt_prefs.mqtt_slot_username[i], old3.mqtt_slot_username[i], sizeof(_mqtt_prefs.mqtt_slot_username[i]));
|
||||
memcpy(_mqtt_prefs.mqtt_slot_password[i], old3.mqtt_slot_password[i], sizeof(_mqtt_prefs.mqtt_slot_password[i]));
|
||||
memcpy(_mqtt_prefs.mqtt_slot_token[i], old3.mqtt_slot_token[i], sizeof(_mqtt_prefs.mqtt_slot_token[i]));
|
||||
memcpy(_mqtt_prefs.mqtt_slot_topic[i], old3.mqtt_slot_topic[i], sizeof(_mqtt_prefs.mqtt_slot_topic[i]));
|
||||
}
|
||||
// Slots 3-5 keep defaults ("none") from setMQTTPrefsDefaults()
|
||||
|
||||
// Copy shared auth fields
|
||||
memcpy(_mqtt_prefs.mqtt_owner_public_key, old3.mqtt_owner_public_key, sizeof(_mqtt_prefs.mqtt_owner_public_key));
|
||||
memcpy(_mqtt_prefs.mqtt_email, old3.mqtt_email, sizeof(_mqtt_prefs.mqtt_email));
|
||||
|
||||
// Save migrated prefs in new 6-slot format
|
||||
saveMQTTPrefs(fs);
|
||||
}
|
||||
} else if (file_size > 0) {
|
||||
// New-format file: read directly (migration-safe for growing struct)
|
||||
// 6-slot format: read directly
|
||||
size_t bytes_to_read = file_size < sizeof(_mqtt_prefs) ? file_size : sizeof(_mqtt_prefs);
|
||||
size_t bytes_read = file.read((uint8_t *)&_mqtt_prefs, bytes_to_read);
|
||||
file.close();
|
||||
@@ -429,7 +477,7 @@ void CommonCLI::syncMQTTPrefsToNodePrefs() {
|
||||
StrHelper::strncpy(_prefs->timezone_string, _mqtt_prefs.timezone_string, sizeof(_prefs->timezone_string));
|
||||
_prefs->timezone_offset = _mqtt_prefs.timezone_offset;
|
||||
// Slot-based fields
|
||||
for (int i = 0; i < 3; i++) {
|
||||
for (int i = 0; i < MAX_MQTT_SLOTS; i++) {
|
||||
StrHelper::strncpy(_prefs->mqtt_slot_preset[i], _mqtt_prefs.mqtt_slot_preset[i], sizeof(_prefs->mqtt_slot_preset[i]));
|
||||
StrHelper::strncpy(_prefs->mqtt_slot_host[i], _mqtt_prefs.mqtt_slot_host[i], sizeof(_prefs->mqtt_slot_host[i]));
|
||||
_prefs->mqtt_slot_port[i] = _mqtt_prefs.mqtt_slot_port[i];
|
||||
@@ -458,7 +506,7 @@ void CommonCLI::syncNodePrefsToMQTTPrefs() {
|
||||
StrHelper::strncpy(_mqtt_prefs.timezone_string, _prefs->timezone_string, sizeof(_mqtt_prefs.timezone_string));
|
||||
_mqtt_prefs.timezone_offset = _prefs->timezone_offset;
|
||||
// Slot-based fields
|
||||
for (int i = 0; i < 3; i++) {
|
||||
for (int i = 0; i < MAX_MQTT_SLOTS; i++) {
|
||||
StrHelper::strncpy(_mqtt_prefs.mqtt_slot_preset[i], _prefs->mqtt_slot_preset[i], sizeof(_mqtt_prefs.mqtt_slot_preset[i]));
|
||||
StrHelper::strncpy(_mqtt_prefs.mqtt_slot_host[i], _prefs->mqtt_slot_host[i], sizeof(_mqtt_prefs.mqtt_slot_host[i]));
|
||||
_mqtt_prefs.mqtt_slot_port[i] = _prefs->mqtt_slot_port[i];
|
||||
@@ -712,9 +760,9 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch
|
||||
uint32_t minutes = (_prefs->mqtt_status_interval + 29999) / 60000; // Round up
|
||||
sprintf(reply, "> %u minutes (%lu ms)", minutes, _prefs->mqtt_status_interval);
|
||||
} else if (config[0] == 'm' && config[1] == 'q' && config[2] == 't' && config[3] == 't' &&
|
||||
config[4] >= '1' && config[4] <= '3' && config[5] == '.') {
|
||||
config[4] >= '1' && config[4] <= ('0' + MAX_MQTT_SLOTS) && config[5] == '.') {
|
||||
// Slot-based commands: get mqtt1.preset, get mqtt1.server, etc.
|
||||
int slot = config[4] - '1'; // 0-2
|
||||
int slot = config[4] - '1'; // 0-5
|
||||
const char* subcmd = &config[6];
|
||||
if (memcmp(subcmd, "preset", 6) == 0) {
|
||||
sprintf(reply, "> %s", _prefs->mqtt_slot_preset[slot]);
|
||||
@@ -1198,9 +1246,9 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch
|
||||
strcpy(reply, "Error: timezone offset must be between -12 and +14");
|
||||
}
|
||||
} else if (config[0] == 'm' && config[1] == 'q' && config[2] == 't' && config[3] == 't' &&
|
||||
config[4] >= '1' && config[4] <= '3' && config[5] == '.') {
|
||||
config[4] >= '1' && config[4] <= ('0' + MAX_MQTT_SLOTS) && config[5] == '.') {
|
||||
// Slot-based commands: set mqtt1.preset <name>, set mqtt1.server <host>, etc.
|
||||
int slot = config[4] - '1'; // 0-2
|
||||
int slot = config[4] - '1'; // 0-5
|
||||
const char* subcmd = &config[6];
|
||||
if (memcmp(subcmd, "preset ", 7) == 0) {
|
||||
const char* preset_name = &subcmd[7];
|
||||
@@ -1208,18 +1256,32 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch
|
||||
if (findMQTTPreset(preset_name) != nullptr ||
|
||||
strcmp(preset_name, MQTT_PRESET_CUSTOM) == 0 ||
|
||||
strcmp(preset_name, MQTT_PRESET_NONE) == 0) {
|
||||
StrHelper::strncpy(_prefs->mqtt_slot_preset[slot], preset_name, sizeof(_prefs->mqtt_slot_preset[slot]));
|
||||
savePrefs();
|
||||
_callbacks->restartBridgeSlot(slot);
|
||||
// Check if the slot has everything it needs to connect
|
||||
const MQTTPresetDef* p = findMQTTPreset(preset_name);
|
||||
if (p && p->topic_style == MQTT_TOPIC_MESHRANK && _prefs->mqtt_slot_token[slot][0] == '\0') {
|
||||
sprintf(reply, "OK - slot %d preset: %s (run 'set mqtt%d.token <your_token>' to connect)", slot + 1, preset_name, slot + 1);
|
||||
} else if (p && p->topic_style == MQTT_TOPIC_MESHCORE &&
|
||||
(strlen(_prefs->mqtt_iata) == 0 || strcmp(_prefs->mqtt_iata, "XXX") == 0)) {
|
||||
sprintf(reply, "OK - slot %d preset: %s (run 'set mqtt.iata <airport_code>' to publish)", slot + 1, preset_name);
|
||||
// Reject duplicate presets (except "none" and "custom")
|
||||
int dup_slot = -1;
|
||||
if (findMQTTPreset(preset_name) != nullptr) {
|
||||
for (int s = 0; s < MAX_MQTT_SLOTS; s++) {
|
||||
if (s != slot && strcmp(_prefs->mqtt_slot_preset[s], preset_name) == 0) {
|
||||
dup_slot = s;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dup_slot >= 0) {
|
||||
sprintf(reply, "Error: preset '%s' is already assigned to slot %d", preset_name, dup_slot + 1);
|
||||
} else {
|
||||
sprintf(reply, "OK - slot %d preset: %s", slot + 1, preset_name);
|
||||
StrHelper::strncpy(_prefs->mqtt_slot_preset[slot], preset_name, sizeof(_prefs->mqtt_slot_preset[slot]));
|
||||
savePrefs();
|
||||
_callbacks->restartBridgeSlot(slot);
|
||||
// Check if the slot has everything it needs to connect
|
||||
const MQTTPresetDef* p = findMQTTPreset(preset_name);
|
||||
if (p && p->topic_style == MQTT_TOPIC_MESHRANK && _prefs->mqtt_slot_token[slot][0] == '\0') {
|
||||
sprintf(reply, "OK - slot %d preset: %s (run 'set mqtt%d.token <your_token>' to connect)", slot + 1, preset_name, slot + 1);
|
||||
} else if (p && p->topic_style == MQTT_TOPIC_MESHCORE &&
|
||||
(strlen(_prefs->mqtt_iata) == 0 || strcmp(_prefs->mqtt_iata, "XXX") == 0)) {
|
||||
sprintf(reply, "OK - slot %d preset: %s (run 'set mqtt.iata <airport_code>' to publish)", slot + 1, preset_name);
|
||||
} else {
|
||||
sprintf(reply, "OK - slot %d preset: %s", slot + 1, preset_name);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
strcpy(reply, "Error: valid presets are: analyzer-us, analyzer-eu, meshmapper, meshrank, waev, cascadiamesh, custom, none");
|
||||
|
||||
+52
-19
@@ -4,6 +4,7 @@
|
||||
#include <helpers/IdentityStore.h>
|
||||
#include <helpers/SensorManager.h>
|
||||
#include <helpers/ClientACL.h>
|
||||
#include <helpers/MQTTPresets.h> // For MAX_MQTT_SLOTS (used in NodePrefs struct layout)
|
||||
|
||||
#if defined(WITH_RS232_BRIDGE) || defined(WITH_ESPNOW_BRIDGE) || defined(WITH_MQTT_BRIDGE)
|
||||
#define WITH_BRIDGE
|
||||
@@ -77,22 +78,22 @@ struct NodePrefs { // persisted to file
|
||||
char timezone_string[32]; // Timezone string (e.g., "America/Los_Angeles")
|
||||
int8_t timezone_offset; // Timezone offset in hours (-12 to +14) - fallback
|
||||
|
||||
// MQTT slot presets (3 slots, each can be a preset name or "custom"/"none")
|
||||
char mqtt_slot_preset[3][24]; // e.g. "analyzer-us", "meshmapper", "custom", "none"
|
||||
// MQTT slot presets (up to MAX_MQTT_SLOTS, each can be a preset name or "custom"/"none")
|
||||
char mqtt_slot_preset[MAX_MQTT_SLOTS][24]; // e.g. "analyzer-us", "meshmapper", "custom", "none"
|
||||
|
||||
// Per-slot custom broker settings (only used when slot preset is "custom")
|
||||
char mqtt_slot_host[3][64];
|
||||
uint16_t mqtt_slot_port[3];
|
||||
char mqtt_slot_username[3][32];
|
||||
char mqtt_slot_password[3][64];
|
||||
char mqtt_slot_host[MAX_MQTT_SLOTS][64];
|
||||
uint16_t mqtt_slot_port[MAX_MQTT_SLOTS];
|
||||
char mqtt_slot_username[MAX_MQTT_SLOTS][32];
|
||||
char mqtt_slot_password[MAX_MQTT_SLOTS][64];
|
||||
|
||||
// Shared MQTT authentication
|
||||
char mqtt_owner_public_key[65]; // Owner public key (hex string, same length as repeater public key)
|
||||
char mqtt_email[64]; // Owner email address for matching nodes with owners
|
||||
|
||||
// Per-slot extended fields
|
||||
char mqtt_slot_token[3][48]; // Per-slot token (e.g., MeshRank account token)
|
||||
char mqtt_slot_topic[3][96]; // Per-slot custom topic template (custom preset only)
|
||||
char mqtt_slot_token[MAX_MQTT_SLOTS][48]; // Per-slot token (e.g., MeshRank account token)
|
||||
char mqtt_slot_topic[MAX_MQTT_SLOTS][96]; // Per-slot custom topic template (custom preset only)
|
||||
|
||||
uint8_t loop_detect;
|
||||
};
|
||||
@@ -142,22 +143,22 @@ struct MQTTPrefs {
|
||||
char timezone_string[32]; // Timezone string (e.g., "America/Los_Angeles")
|
||||
int8_t timezone_offset; // Timezone offset in hours (-12 to +14) - fallback
|
||||
|
||||
// Slot presets (3 slots)
|
||||
char mqtt_slot_preset[3][24]; // e.g. "analyzer-us", "meshmapper", "custom", "none"
|
||||
// Slot presets (up to MAX_MQTT_SLOTS)
|
||||
char mqtt_slot_preset[MAX_MQTT_SLOTS][24]; // e.g. "analyzer-us", "meshmapper", "custom", "none"
|
||||
|
||||
// Per-slot custom broker settings (only used when preset is "custom")
|
||||
char mqtt_slot_host[3][64];
|
||||
uint16_t mqtt_slot_port[3];
|
||||
char mqtt_slot_username[3][32];
|
||||
char mqtt_slot_password[3][64];
|
||||
char mqtt_slot_host[MAX_MQTT_SLOTS][64];
|
||||
uint16_t mqtt_slot_port[MAX_MQTT_SLOTS];
|
||||
char mqtt_slot_username[MAX_MQTT_SLOTS][32];
|
||||
char mqtt_slot_password[MAX_MQTT_SLOTS][64];
|
||||
|
||||
// Shared authentication
|
||||
char mqtt_owner_public_key[65]; // Owner public key (hex string)
|
||||
char mqtt_email[64]; // Owner email address
|
||||
|
||||
// --- Legacy fields (vestigial, kept for binary compatibility) ---
|
||||
// Migration now uses OldMQTTPrefs struct. These fields are unused but must remain
|
||||
// to preserve byte offsets for devices that already saved a new-format /mqtt_prefs file.
|
||||
// Migration now uses OldMQTTPrefs/ThreeSlotMQTTPrefs structs. These fields are unused
|
||||
// but must remain to preserve byte offsets for devices that already saved a new-format /mqtt_prefs file.
|
||||
uint8_t _legacy_analyzer_us_enabled;
|
||||
uint8_t _legacy_analyzer_eu_enabled;
|
||||
char _legacy_mqtt_server[64];
|
||||
@@ -166,9 +167,41 @@ struct MQTTPrefs {
|
||||
char _legacy_mqtt_password[64];
|
||||
|
||||
// --- New fields (appended at end for migration safety) ---
|
||||
// When loading an older/smaller prefs file, these stay zeroed from setMQTTPrefsDefaults().
|
||||
char mqtt_slot_token[3][48]; // Per-slot token (e.g., MeshRank account token)
|
||||
char mqtt_slot_topic[3][96]; // Per-slot custom topic template (custom preset only)
|
||||
char mqtt_slot_token[MAX_MQTT_SLOTS][48]; // Per-slot token (e.g., MeshRank account token)
|
||||
char mqtt_slot_topic[MAX_MQTT_SLOTS][96]; // Per-slot custom topic template (custom preset only)
|
||||
};
|
||||
|
||||
// 3-slot MQTTPrefs layout — used for migrating from 3-slot to 6-slot format.
|
||||
// Changing array sizes from [3] to [6] shifts all field offsets, so raw file.read()
|
||||
// into the new struct would corrupt data. This struct preserves the old binary layout.
|
||||
struct ThreeSlotMQTTPrefs {
|
||||
char mqtt_origin[32];
|
||||
char mqtt_iata[8];
|
||||
uint8_t mqtt_status_enabled;
|
||||
uint8_t mqtt_packets_enabled;
|
||||
uint8_t mqtt_raw_enabled;
|
||||
uint8_t mqtt_tx_enabled;
|
||||
uint32_t mqtt_status_interval;
|
||||
char wifi_ssid[32];
|
||||
char wifi_password[64];
|
||||
uint8_t wifi_power_save;
|
||||
char timezone_string[32];
|
||||
int8_t timezone_offset;
|
||||
char mqtt_slot_preset[3][24];
|
||||
char mqtt_slot_host[3][64];
|
||||
uint16_t mqtt_slot_port[3];
|
||||
char mqtt_slot_username[3][32];
|
||||
char mqtt_slot_password[3][64];
|
||||
char mqtt_owner_public_key[65];
|
||||
char mqtt_email[64];
|
||||
uint8_t _legacy_analyzer_us_enabled;
|
||||
uint8_t _legacy_analyzer_eu_enabled;
|
||||
char _legacy_mqtt_server[64];
|
||||
uint16_t _legacy_mqtt_port;
|
||||
char _legacy_mqtt_username[32];
|
||||
char _legacy_mqtt_password[64];
|
||||
char mqtt_slot_token[3][48];
|
||||
char mqtt_slot_topic[3][96];
|
||||
};
|
||||
#endif
|
||||
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
// Maximum number of configurable MQTT connection slots (available to all builds for struct layout)
|
||||
static const int MAX_MQTT_SLOTS = 6;
|
||||
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
|
||||
enum MQTTAuthType : uint8_t {
|
||||
@@ -107,9 +110,6 @@ static const MQTTPresetDef* findMQTTPreset(const char* name) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Maximum number of concurrent MQTT connection slots
|
||||
static const int MAX_MQTT_SLOTS = 3;
|
||||
|
||||
// Slot preset name constants
|
||||
static const char MQTT_PRESET_NONE[] = "none";
|
||||
static const char MQTT_PRESET_CUSTOM[] = "custom";
|
||||
|
||||
@@ -115,31 +115,8 @@ void MQTTBridge::formatMqttStatusReply(char* buf, size_t bufsize, const NodePref
|
||||
}
|
||||
MQTTBridge* b = s_mqtt_bridge_instance;
|
||||
|
||||
// Build per-slot status strings
|
||||
char slot_info[3][48];
|
||||
for (int i = 0; i < MAX_MQTT_SLOTS; i++) {
|
||||
const MQTTSlot& slot = b->_slots[i];
|
||||
if (!slot.enabled && slot.preset) {
|
||||
// Configured but disabled (e.g., no PSRAM, slot limit reached)
|
||||
snprintf(slot_info[i], sizeof(slot_info[i]), "slot%d: %s (inactive)", i + 1, slot.preset->name);
|
||||
} else if (!slot.enabled) {
|
||||
snprintf(slot_info[i], sizeof(slot_info[i]), "slot%d: none", i + 1);
|
||||
} else if (!b->isSlotReady(i)) {
|
||||
const char* name = slot.preset ? slot.preset->name : "custom";
|
||||
snprintf(slot_info[i], sizeof(slot_info[i]), "slot%d: %s (not ready)", i + 1, name);
|
||||
} else if (slot.preset) {
|
||||
const char* state = slot.connected ? "connected" :
|
||||
slot.circuit_breaker_tripped ? "failed" : "disconnected";
|
||||
snprintf(slot_info[i], sizeof(slot_info[i]), "slot%d: %s (%s)", i + 1,
|
||||
slot.preset->name, state);
|
||||
} else {
|
||||
// Custom broker
|
||||
const char* state = slot.connected ? "connected" :
|
||||
slot.circuit_breaker_tripped ? "failed" : "disconnected";
|
||||
snprintf(slot_info[i], sizeof(slot_info[i]), "slot%d: custom (%s)", i + 1, state);
|
||||
}
|
||||
}
|
||||
|
||||
// Build per-slot status strings (compact format to fit 160-byte reply buffer)
|
||||
// Only show configured slots, skip "none" slots
|
||||
int q = 0;
|
||||
#ifdef ESP_PLATFORM
|
||||
if (b->_packet_queue_handle != nullptr) {
|
||||
@@ -148,8 +125,34 @@ void MQTTBridge::formatMqttStatusReply(char* buf, size_t bufsize, const NodePref
|
||||
#else
|
||||
q = b->_queue_count;
|
||||
#endif
|
||||
snprintf(buf, bufsize, "> msgs: %s, %s, %s, %s, queue: %d",
|
||||
msgs, slot_info[0], slot_info[1], slot_info[2], q);
|
||||
|
||||
int pos = snprintf(buf, bufsize, "> msgs: %s", msgs);
|
||||
for (int i = 0; i < MAX_MQTT_SLOTS && pos < (int)bufsize - 1; i++) {
|
||||
const MQTTSlot& slot = b->_slots[i];
|
||||
const char* name = nullptr;
|
||||
const char* state = nullptr;
|
||||
|
||||
if (!slot.enabled && slot.preset) {
|
||||
name = slot.preset->name;
|
||||
state = "inactive";
|
||||
} else if (!slot.enabled) {
|
||||
continue; // Skip unconfigured slots
|
||||
} else if (!b->isSlotReady(i)) {
|
||||
name = slot.preset ? slot.preset->name : "custom";
|
||||
state = "wait";
|
||||
} else if (slot.connected) {
|
||||
name = slot.preset ? slot.preset->name : "custom";
|
||||
state = "ok";
|
||||
} else if (slot.circuit_breaker_tripped) {
|
||||
name = slot.preset ? slot.preset->name : "custom";
|
||||
state = "fail";
|
||||
} else {
|
||||
name = slot.preset ? slot.preset->name : "custom";
|
||||
state = "disc";
|
||||
}
|
||||
pos += snprintf(buf + pos, bufsize - pos, ", %d: %s (%s)", i + 1, name, state);
|
||||
}
|
||||
snprintf(buf + pos, bufsize - pos, ", q:%d", q);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -266,9 +269,10 @@ void MQTTBridge::begin() {
|
||||
|
||||
// Limit active slots based on available memory.
|
||||
// Each WSS/TLS connection needs ~40KB for mbedTLS buffers.
|
||||
// Without PSRAM, 3 concurrent connections would exhaust internal heap.
|
||||
// Without PSRAM, even 3 concurrent connections would exhaust internal heap.
|
||||
// With PSRAM, cap at 5 for safety (6 configurable but 5 active max).
|
||||
#if defined(ESP_PLATFORM) && defined(BOARD_HAS_PSRAM)
|
||||
_max_active_slots = psramFound() ? MAX_MQTT_SLOTS : 2;
|
||||
_max_active_slots = psramFound() ? 5 : 2;
|
||||
#else
|
||||
_max_active_slots = 2;
|
||||
#endif
|
||||
@@ -459,12 +463,10 @@ void MQTTBridge::end() {
|
||||
_mqtt_task_stack = nullptr;
|
||||
|
||||
// Clean up queued packets from FreeRTOS queue
|
||||
// NOTE: Do NOT free queued.packet - the Dispatcher owns those packets.
|
||||
// We just discard our references to them.
|
||||
// Packets are value-copied in the queue, so no external pointers to clean up.
|
||||
if (_packet_queue_handle != nullptr) {
|
||||
QueuedPacket queued;
|
||||
while (xQueueReceive(_packet_queue_handle, &queued, 0) == pdTRUE) {
|
||||
queued.packet = nullptr;
|
||||
_queue_count--;
|
||||
}
|
||||
vQueueDelete(_packet_queue_handle);
|
||||
@@ -480,11 +482,9 @@ void MQTTBridge::end() {
|
||||
}
|
||||
#else
|
||||
// Clean up queued packet references
|
||||
// NOTE: Do NOT free the packets - the Dispatcher owns those packets.
|
||||
// We just discard our references to them.
|
||||
// Packets are value-copied in the queue, so no external pointers to clean up.
|
||||
for (int i = 0; i < _queue_count; i++) {
|
||||
int index = (_queue_head + i) % MAX_QUEUE_SIZE;
|
||||
_packet_queue[index].packet = nullptr;
|
||||
memset(&_packet_queue[index], 0, sizeof(QueuedPacket));
|
||||
}
|
||||
|
||||
@@ -1039,21 +1039,20 @@ void MQTTBridge::maintainSlotConnection(int index, unsigned long now_millis, uns
|
||||
current_time < slot.token_expires_at &&
|
||||
(slot.token_expires_at - current_time) > 120; // >2 min remaining
|
||||
|
||||
if (token_still_valid) {
|
||||
if (token_still_valid && slot.reconnect_backoff <= 2) {
|
||||
// Lightweight reconnect — reuse existing client but refresh JWT for fresh iat
|
||||
// (brokers like waev enforce iat freshness ±10 min, so stale iat = rejected)
|
||||
if (createSlotAuthToken(index)) {
|
||||
slot.client->setCredentials(_jwt_username, slot.auth_token);
|
||||
MQTT_DEBUG_PRINTLN("MQTT%d lightweight reconnect (fresh token, expires in %lu sec)", index + 1, slot.token_expires_at - (unsigned long)time(nullptr));
|
||||
} else {
|
||||
MQTT_DEBUG_PRINTLN("MQTT%d lightweight reconnect (token refresh failed, using existing)", index + 1);
|
||||
}
|
||||
slot.client->connect();
|
||||
slot.client->reconnect();
|
||||
} else {
|
||||
// Token expired or near expiry — full teardown for fresh TLS + new token
|
||||
// Full teardown: token expired/near expiry, or lightweight reconnect failed (backoff 3+)
|
||||
uint8_t saved_backoff = slot.reconnect_backoff;
|
||||
uint8_t saved_failures = slot.max_backoff_failures;
|
||||
MQTT_DEBUG_PRINTLN("MQTT%d token expired/near expiry, full teardown+setup for reconnect", index + 1);
|
||||
MQTT_DEBUG_PRINTLN("MQTT%d full teardown+setup for reconnect (backoff %d)", index + 1, saved_backoff);
|
||||
teardownSlot(index);
|
||||
setupSlot(index);
|
||||
_slots[index].reconnect_backoff = saved_backoff;
|
||||
@@ -1061,8 +1060,21 @@ void MQTTBridge::maintainSlotConnection(int index, unsigned long now_millis, uns
|
||||
_slots[index].last_reconnect_attempt = now_millis;
|
||||
}
|
||||
} else {
|
||||
// Non-JWT slots: lightweight reconnect on existing client
|
||||
slot.client->connect();
|
||||
// Non-JWT slots
|
||||
if (slot.reconnect_backoff <= 2) {
|
||||
// Lightweight reconnect on existing client
|
||||
slot.client->reconnect();
|
||||
} else {
|
||||
// Full teardown after lightweight reconnect failed (backoff 3+)
|
||||
uint8_t saved_backoff = slot.reconnect_backoff;
|
||||
uint8_t saved_failures = slot.max_backoff_failures;
|
||||
MQTT_DEBUG_PRINTLN("MQTT%d full teardown+setup for reconnect (backoff %d)", index + 1, saved_backoff);
|
||||
teardownSlot(index);
|
||||
setupSlot(index);
|
||||
_slots[index].reconnect_backoff = saved_backoff;
|
||||
_slots[index].max_backoff_failures = saved_failures;
|
||||
_slots[index].last_reconnect_attempt = now_millis;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1732,11 +1744,11 @@ void MQTTBridge::processPacketQueue() {
|
||||
|
||||
_last_no_broker_log = 0;
|
||||
|
||||
// Process up to 1 packet per call to maintain responsiveness
|
||||
// Adaptive drain: burst-process when queue has backlog, gentle otherwise
|
||||
int processed = 0;
|
||||
int max_per_loop = 1;
|
||||
int max_per_loop = (_queue_count > 5) ? 5 : 1;
|
||||
unsigned long loop_start_time = millis();
|
||||
const unsigned long MAX_PROCESSING_TIME_MS = 30;
|
||||
const unsigned long MAX_PROCESSING_TIME_MS = (_queue_count > 5) ? 100 : 30;
|
||||
|
||||
while (processed < max_per_loop) {
|
||||
unsigned long elapsed = millis() - loop_start_time;
|
||||
@@ -1751,7 +1763,7 @@ void MQTTBridge::processPacketQueue() {
|
||||
}
|
||||
|
||||
// Publish packet (use stored raw data if available)
|
||||
publishPacket(queued.packet, queued.is_tx,
|
||||
publishPacket(&queued.packet_copy, queued.is_tx,
|
||||
queued.has_raw_data ? queued.raw_data : nullptr,
|
||||
queued.has_raw_data ? queued.raw_len : 0,
|
||||
queued.has_raw_data ? queued.snr : 0.0f,
|
||||
@@ -1759,12 +1771,9 @@ void MQTTBridge::processPacketQueue() {
|
||||
|
||||
// Publish raw if enabled
|
||||
if (_raw_enabled) {
|
||||
publishRaw(queued.packet);
|
||||
publishRaw(&queued.packet_copy);
|
||||
}
|
||||
|
||||
// NOTE: Do NOT free the packet here - the Dispatcher owns and frees it after logRx() returns.
|
||||
queued.packet = nullptr;
|
||||
|
||||
_queue_count--;
|
||||
processed++;
|
||||
}
|
||||
@@ -1789,10 +1798,11 @@ void MQTTBridge::processPacketQueue() {
|
||||
|
||||
_last_no_broker_log = 0;
|
||||
|
||||
// Adaptive drain: burst-process when queue has backlog, gentle otherwise
|
||||
int processed = 0;
|
||||
int max_per_loop = 1;
|
||||
int max_per_loop = (_queue_count > 5) ? 5 : 1;
|
||||
unsigned long loop_start_time = millis();
|
||||
const unsigned long MAX_PROCESSING_TIME_MS = 30;
|
||||
const unsigned long MAX_PROCESSING_TIME_MS = (_queue_count > 5) ? 100 : 30;
|
||||
|
||||
while (_queue_count > 0 && processed < max_per_loop) {
|
||||
unsigned long elapsed = millis() - loop_start_time;
|
||||
@@ -1802,19 +1812,16 @@ void MQTTBridge::processPacketQueue() {
|
||||
|
||||
QueuedPacket& queued = _packet_queue[_queue_head];
|
||||
|
||||
publishPacket(queued.packet, queued.is_tx,
|
||||
publishPacket(&queued.packet_copy, queued.is_tx,
|
||||
queued.has_raw_data ? queued.raw_data : nullptr,
|
||||
queued.has_raw_data ? queued.raw_len : 0,
|
||||
queued.has_raw_data ? queued.snr : 0.0f,
|
||||
queued.has_raw_data ? queued.rssi : 0.0f);
|
||||
|
||||
if (_raw_enabled) {
|
||||
publishRaw(queued.packet);
|
||||
publishRaw(&queued.packet_copy);
|
||||
}
|
||||
|
||||
// NOTE: Do NOT free the packet here - the Dispatcher owns and frees it after logRx() returns.
|
||||
queued.packet = nullptr;
|
||||
|
||||
dequeuePacket();
|
||||
processed++;
|
||||
}
|
||||
@@ -2045,7 +2052,7 @@ void MQTTBridge::queuePacket(mesh::Packet* packet, bool is_tx) {
|
||||
QueuedPacket queued;
|
||||
memset(&queued, 0, sizeof(QueuedPacket));
|
||||
|
||||
queued.packet = packet;
|
||||
queued.packet_copy = *packet; // full value copy — safe from Dispatcher free
|
||||
queued.timestamp = millis();
|
||||
queued.is_tx = is_tx;
|
||||
queued.has_raw_data = false;
|
||||
@@ -2088,15 +2095,14 @@ void MQTTBridge::queuePacket(mesh::Packet* packet, bool is_tx) {
|
||||
// Non-ESP32: Use circular buffer
|
||||
if (_queue_count >= MAX_QUEUE_SIZE) {
|
||||
QueuedPacket& oldest = _packet_queue[_queue_head];
|
||||
MQTT_DEBUG_PRINTLN("Queue full, dropping oldest packet reference (queue size: %d)", _queue_count);
|
||||
oldest.packet = nullptr;
|
||||
MQTT_DEBUG_PRINTLN("Queue full, dropping oldest packet (queue size: %d)", _queue_count);
|
||||
dequeuePacket();
|
||||
}
|
||||
|
||||
QueuedPacket& queued = _packet_queue[_queue_tail];
|
||||
memset(&queued, 0, sizeof(QueuedPacket));
|
||||
|
||||
queued.packet = packet;
|
||||
queued.packet_copy = *packet; // full value copy — safe from Dispatcher free
|
||||
queued.timestamp = millis();
|
||||
queued.is_tx = is_tx;
|
||||
queued.has_raw_data = false;
|
||||
|
||||
@@ -38,8 +38,8 @@
|
||||
* uplink packet data to multiple MQTT brokers for monitoring and analysis.
|
||||
*
|
||||
* Features:
|
||||
* - Up to 3 configurable MQTT connection slots
|
||||
* - Built-in presets for LetsMesh Analyzer (US/EU) and MeshMapper
|
||||
* - Up to 6 configurable MQTT connection slots (5 active with PSRAM, 2 without)
|
||||
* - Built-in presets for LetsMesh Analyzer (US/EU), MeshMapper, MeshRank, Waev, CascadiaMesh
|
||||
* - Custom broker support with username/password auth
|
||||
* - JWT authentication with Ed25519 device signing
|
||||
* - Automatic reconnection with exponential backoff
|
||||
@@ -101,8 +101,11 @@ private:
|
||||
unsigned long _status_interval;
|
||||
|
||||
// Packet queue for offline scenarios
|
||||
// NOTE: We store a full copy of the packet (not a pointer) because the
|
||||
// Dispatcher frees packets back to the static pool immediately after logRx()
|
||||
// returns. Storing only a pointer would be a use-after-free.
|
||||
struct QueuedPacket {
|
||||
mesh::Packet* packet;
|
||||
mesh::Packet packet_copy; // ~258 bytes, full value copy
|
||||
unsigned long timestamp;
|
||||
bool is_tx;
|
||||
// Store raw radio data with each packet to avoid it being overwritten
|
||||
@@ -113,7 +116,11 @@ private:
|
||||
bool has_raw_data;
|
||||
};
|
||||
|
||||
#if defined(BOARD_HAS_PSRAM)
|
||||
static const int MAX_QUEUE_SIZE = 50;
|
||||
#else
|
||||
static const int MAX_QUEUE_SIZE = 10;
|
||||
#endif
|
||||
|
||||
// FreeRTOS queue for thread-safe packet queuing
|
||||
#ifdef ESP_PLATFORM
|
||||
@@ -141,7 +148,7 @@ private:
|
||||
bool _ntp_synced;
|
||||
bool _ntp_sync_pending; // Flag to trigger NTP sync from loop() instead of event handler
|
||||
bool _slots_setup_done; // Deferred: slots set up after NTP sync
|
||||
int _max_active_slots; // Runtime limit: 3 with PSRAM, 2 without
|
||||
int _max_active_slots; // Runtime limit: 5 with PSRAM, 2 without
|
||||
|
||||
// Pending slot reconfigure: set from CLI (Core 1), processed by MQTT task (Core 0)
|
||||
volatile bool _slot_reconfigure_pending[MAX_MQTT_SLOTS];
|
||||
|
||||
Reference in new issue
Block a user