Enhance MQTT bridge implementation to support a new MeshRank preset, allowing for token-based authentication and custom topic templates. Update CLI commands for slot management, including new commands for setting tokens and topics. Improve documentation to reflect these changes and provide examples for configuring the new preset.
This commit is contained in:
1 parent
c67fb12b44
commit
95874f0c24
8 files changed
+473
-181
No files matched your search
+41
-3
@@ -82,6 +82,7 @@ The MQTT bridge uses a slot-based architecture with up to 3 concurrent connectio
|
||||
| `analyzer-us` | mqtt-us-v1.letsmesh.net:443 | JWT (Ed25519) | WSS |
|
||||
| `analyzer-eu` | mqtt-eu-v1.letsmesh.net:443 | JWT (Ed25519) | WSS |
|
||||
| `meshmapper` | mqtt.meshmapper.cc:443 | JWT (Ed25519) | WSS |
|
||||
| `meshrank` | meshrank.net:8883 | None (token in topic) | MQTT over TLS |
|
||||
| `custom` | User-configured | Username/Password | MQTT or WSS |
|
||||
| `none` | (disabled) | — | — |
|
||||
|
||||
@@ -166,20 +167,33 @@ Each slot (1-3) supports the following commands:
|
||||
- `get mqttN.port` - Get custom server port for slot N
|
||||
- `get mqttN.username` - Get custom username for slot N
|
||||
- `get mqttN.password` - Get custom password for slot N
|
||||
- `get mqttN.token` - Get per-slot token (e.g., MeshRank account token)
|
||||
- `get mqttN.topic` - Get custom topic template for slot N
|
||||
|
||||
#### Set Commands
|
||||
- `set mqtt1.preset analyzer-us` - Set slot 1 to LetsMesh Analyzer US
|
||||
- `set mqtt1.preset analyzer-eu` - Set slot 1 to LetsMesh Analyzer EU
|
||||
- `set mqtt1.preset meshmapper` - Set slot 1 to MeshMapper
|
||||
- `set mqtt1.preset meshrank` - Set slot 1 to MeshRank (requires token)
|
||||
- `set mqtt1.preset custom` - Set slot 1 to custom broker (configure server/port/username/password)
|
||||
- `set mqtt1.preset none` - Disable slot 1
|
||||
- `set mqttN.server <hostname>` - Set custom server hostname for slot N
|
||||
- `set mqttN.port <port>` - Set custom server port for slot N (1-65535)
|
||||
- `set mqttN.username <username>` - Set custom username for slot N
|
||||
- `set mqttN.password <password>` - Set custom password for slot N
|
||||
- `set mqttN.token <token>` - Set per-slot token (required for MeshRank preset)
|
||||
- `set mqttN.topic <template>` - Set custom topic template (custom preset only, see below)
|
||||
|
||||
**Note:** Custom server/port/username/password settings only apply when the slot's preset is `custom`.
|
||||
|
||||
#### Example: Configure MeshRank on Slot 3
|
||||
```bash
|
||||
set mqtt3.preset meshrank
|
||||
set mqtt3.token FE1B34242C5938C39225310081FD6718
|
||||
```
|
||||
|
||||
The token is generated on the MeshRank website and is tied to your account. MeshRank only receives packet data (no status or raw messages).
|
||||
|
||||
#### Example: Configure MeshMapper on Slot 3
|
||||
```bash
|
||||
set mqtt3.preset meshmapper
|
||||
@@ -194,6 +208,29 @@ set mqtt3.username your-username
|
||||
set mqtt3.password your-password
|
||||
```
|
||||
|
||||
#### Example: Custom Broker with Custom Topic Template
|
||||
```bash
|
||||
set mqtt3.preset custom
|
||||
set mqtt3.server my-broker.local
|
||||
set mqtt3.port 1883
|
||||
set mqtt3.topic mynetwork/{device}/{type}
|
||||
```
|
||||
|
||||
### Custom Topic Templates
|
||||
|
||||
When a slot's preset is `custom`, you can define a custom topic template using placeholders:
|
||||
|
||||
| Placeholder | Value | Example |
|
||||
|-------------|-------|---------|
|
||||
| `{iata}` | IATA airport code | `SEA` |
|
||||
| `{device}` | Device public key (64 hex chars) | `CC5D3CFD...` |
|
||||
| `{token}` | Per-slot token from `mqttN.token` | `FE1B3424...` |
|
||||
| `{type}` | Message type | `status`, `packets`, or `raw` |
|
||||
|
||||
If no custom topic is set, custom slots default to: `meshcore/{iata}/{device}/{type}`
|
||||
|
||||
**Note:** Topic templates only apply to `custom` preset slots. Built-in presets (analyzer-us, analyzer-eu, meshmapper, meshrank) always use their hardcoded topic format.
|
||||
|
||||
### MQTT Shared Commands
|
||||
|
||||
These settings apply across all MQTT slots:
|
||||
@@ -345,9 +382,10 @@ Minimal raw packet data for map integration.
|
||||
|
||||
### Slot-Based Preset System
|
||||
- Up to 3 concurrent MQTT connections (with PSRAM), 2 without PSRAM
|
||||
- Built-in presets for LetsMesh Analyzer (US/EU) and MeshMapper
|
||||
- Custom broker support with username/password auth
|
||||
- JWT (Ed25519) authentication for preset brokers
|
||||
- Built-in presets for LetsMesh Analyzer (US/EU), MeshMapper, and MeshRank
|
||||
- Custom broker support with username/password auth and custom topic templates
|
||||
- JWT (Ed25519) authentication for preset brokers, token-in-topic for MeshRank
|
||||
- WSS (WebSocket Secure) and direct MQTT over TLS transport
|
||||
- Automatic reconnection with exponential backoff per slot
|
||||
- JWT token buffers only allocated for JWT-auth slots (memory efficient)
|
||||
- Deferred construction: MQTTBridge is heap-allocated in `begin()` to avoid ESP32 static init crashes
|
||||
|
||||
@@ -269,6 +269,11 @@ public:
|
||||
bridge->begin();
|
||||
}
|
||||
|
||||
void restartBridgeSlot(int slot) override {
|
||||
if (!bridge || !bridge->isRunning()) return;
|
||||
bridge->setSlotPreset(slot, _prefs.mqtt_slot_preset[slot]);
|
||||
}
|
||||
|
||||
int getQueueSize() override {
|
||||
return bridge ? bridge->getQueueSize() : 0;
|
||||
}
|
||||
|
||||
@@ -213,4 +213,59 @@ public:
|
||||
void clearStats() override;
|
||||
void handleCommand(uint32_t sender_timestamp, char* command, char* reply);
|
||||
void loop();
|
||||
|
||||
#if defined(WITH_BRIDGE)
|
||||
void setBridgeState(bool enable) override {
|
||||
if (!bridge) {
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
bridge = new MQTTBridge(&_prefs, _mgr, getRTCClock(), &self_id);
|
||||
#endif
|
||||
if (!bridge) return;
|
||||
}
|
||||
if (enable == bridge->isRunning()) return;
|
||||
if (enable)
|
||||
{
|
||||
char device_id[65];
|
||||
mesh::LocalIdentity self_id = getSelfId();
|
||||
mesh::Utils::toHex(device_id, self_id.pub_key, PUB_KEY_SIZE);
|
||||
bridge->setDeviceID(device_id);
|
||||
bridge->setFirmwareVersion(getFirmwareVer());
|
||||
bridge->setBoardModel(_cli.getBoard()->getManufacturerName());
|
||||
bridge->setBuildDate(getBuildDate());
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
bridge->setStatsSources(this, _radio, _cli.getBoard(), _ms);
|
||||
#endif
|
||||
bridge->begin();
|
||||
}
|
||||
else
|
||||
{
|
||||
bridge->end();
|
||||
}
|
||||
}
|
||||
|
||||
void restartBridge() override {
|
||||
if (!bridge || !bridge->isRunning()) return;
|
||||
bridge->end();
|
||||
char device_id[65];
|
||||
mesh::LocalIdentity self_id = getSelfId();
|
||||
mesh::Utils::toHex(device_id, self_id.pub_key, PUB_KEY_SIZE);
|
||||
bridge->setDeviceID(device_id);
|
||||
bridge->setFirmwareVersion(getFirmwareVer());
|
||||
bridge->setBoardModel(_cli.getBoard()->getManufacturerName());
|
||||
bridge->setBuildDate(getBuildDate());
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
bridge->setStatsSources(this, _radio, _cli.getBoard(), _ms);
|
||||
#endif
|
||||
bridge->begin();
|
||||
}
|
||||
|
||||
void restartBridgeSlot(int slot) override {
|
||||
if (!bridge || !bridge->isRunning()) return;
|
||||
bridge->setSlotPreset(slot, _prefs.mqtt_slot_preset[slot]);
|
||||
}
|
||||
|
||||
int getQueueSize() override {
|
||||
return bridge ? bridge->getQueueSize() : 0;
|
||||
}
|
||||
#endif
|
||||
};
|
||||
+113
-110
@@ -309,7 +309,7 @@ static void setMQTTPrefsDefaults(MQTTPrefs* prefs) {
|
||||
void CommonCLI::loadMQTTPrefs(FILESYSTEM* fs) {
|
||||
// Initialize with defaults first
|
||||
setMQTTPrefsDefaults(&_mqtt_prefs);
|
||||
|
||||
|
||||
bool file_existed = fs->exists("/mqtt_prefs");
|
||||
if (file_existed) {
|
||||
// Load from separate MQTT prefs file
|
||||
@@ -319,119 +319,82 @@ void CommonCLI::loadMQTTPrefs(FILESYSTEM* fs) {
|
||||
File file = fs->open("/mqtt_prefs");
|
||||
#endif
|
||||
if (file) {
|
||||
// Verify file size is correct before reading
|
||||
if (file.size() >= sizeof(_mqtt_prefs)) {
|
||||
size_t bytes_read = file.read((uint8_t *)&_mqtt_prefs, sizeof(_mqtt_prefs));
|
||||
if (bytes_read != sizeof(_mqtt_prefs)) {
|
||||
// File read incomplete - reinitialize to defaults
|
||||
size_t file_size = file.size();
|
||||
|
||||
// Detect old (pre-slot) format by file size.
|
||||
// Old MQTTPrefs was ~472 bytes (no slot fields). New is ~1464 bytes.
|
||||
// If the file is smaller than the new struct but close to OldMQTTPrefs size,
|
||||
// read it with the old layout and migrate.
|
||||
if (file_size > 0 && file_size <= sizeof(OldMQTTPrefs)) {
|
||||
OldMQTTPrefs old_prefs;
|
||||
memset(&old_prefs, 0, sizeof(old_prefs));
|
||||
size_t bytes_read = file.read((uint8_t *)&old_prefs, file_size < sizeof(old_prefs) ? file_size : sizeof(old_prefs));
|
||||
file.close();
|
||||
|
||||
if (bytes_read > 0) {
|
||||
MESH_DEBUG_PRINTLN("MQTT: Migrating old-format prefs to slot-based layout");
|
||||
|
||||
// Copy common fields (identical layout at start of both structs)
|
||||
memcpy(_mqtt_prefs.mqtt_origin, old_prefs.mqtt_origin, sizeof(_mqtt_prefs.mqtt_origin));
|
||||
memcpy(_mqtt_prefs.mqtt_iata, old_prefs.mqtt_iata, sizeof(_mqtt_prefs.mqtt_iata));
|
||||
_mqtt_prefs.mqtt_status_enabled = old_prefs.mqtt_status_enabled;
|
||||
_mqtt_prefs.mqtt_packets_enabled = old_prefs.mqtt_packets_enabled;
|
||||
_mqtt_prefs.mqtt_raw_enabled = old_prefs.mqtt_raw_enabled;
|
||||
_mqtt_prefs.mqtt_tx_enabled = old_prefs.mqtt_tx_enabled;
|
||||
_mqtt_prefs.mqtt_status_interval = old_prefs.mqtt_status_interval;
|
||||
memcpy(_mqtt_prefs.wifi_ssid, old_prefs.wifi_ssid, sizeof(_mqtt_prefs.wifi_ssid));
|
||||
memcpy(_mqtt_prefs.wifi_password, old_prefs.wifi_password, sizeof(_mqtt_prefs.wifi_password));
|
||||
_mqtt_prefs.wifi_power_save = old_prefs.wifi_power_save;
|
||||
memcpy(_mqtt_prefs.timezone_string, old_prefs.timezone_string, sizeof(_mqtt_prefs.timezone_string));
|
||||
_mqtt_prefs.timezone_offset = old_prefs.timezone_offset;
|
||||
|
||||
// Migrate shared auth fields
|
||||
memcpy(_mqtt_prefs.mqtt_owner_public_key, old_prefs.mqtt_owner_public_key, sizeof(_mqtt_prefs.mqtt_owner_public_key));
|
||||
memcpy(_mqtt_prefs.mqtt_email, old_prefs.mqtt_email, sizeof(_mqtt_prefs.mqtt_email));
|
||||
|
||||
// Migrate analyzer presets to slots
|
||||
if (old_prefs.mqtt_analyzer_us_enabled == 1) {
|
||||
strncpy(_mqtt_prefs.mqtt_slot_preset[0], "analyzer-us", sizeof(_mqtt_prefs.mqtt_slot_preset[0]) - 1);
|
||||
} else {
|
||||
strncpy(_mqtt_prefs.mqtt_slot_preset[0], "none", sizeof(_mqtt_prefs.mqtt_slot_preset[0]) - 1);
|
||||
}
|
||||
if (old_prefs.mqtt_analyzer_eu_enabled == 1) {
|
||||
strncpy(_mqtt_prefs.mqtt_slot_preset[1], "analyzer-eu", sizeof(_mqtt_prefs.mqtt_slot_preset[1]) - 1);
|
||||
} else {
|
||||
strncpy(_mqtt_prefs.mqtt_slot_preset[1], "none", sizeof(_mqtt_prefs.mqtt_slot_preset[1]) - 1);
|
||||
}
|
||||
|
||||
// Migrate custom server to slot 3
|
||||
if (old_prefs.mqtt_server[0] != '\0' && old_prefs.mqtt_port > 0) {
|
||||
strncpy(_mqtt_prefs.mqtt_slot_preset[2], "custom", sizeof(_mqtt_prefs.mqtt_slot_preset[2]) - 1);
|
||||
strncpy(_mqtt_prefs.mqtt_slot_host[2], old_prefs.mqtt_server, sizeof(_mqtt_prefs.mqtt_slot_host[2]) - 1);
|
||||
_mqtt_prefs.mqtt_slot_port[2] = old_prefs.mqtt_port;
|
||||
strncpy(_mqtt_prefs.mqtt_slot_username[2], old_prefs.mqtt_username, sizeof(_mqtt_prefs.mqtt_slot_username[2]) - 1);
|
||||
strncpy(_mqtt_prefs.mqtt_slot_password[2], old_prefs.mqtt_password, sizeof(_mqtt_prefs.mqtt_slot_password[2]) - 1);
|
||||
} else {
|
||||
strncpy(_mqtt_prefs.mqtt_slot_preset[2], "none", sizeof(_mqtt_prefs.mqtt_slot_preset[2]) - 1);
|
||||
}
|
||||
|
||||
// Save migrated prefs in new format
|
||||
saveMQTTPrefs(fs);
|
||||
}
|
||||
} else if (file_size > 0) {
|
||||
// New-format file: read directly (migration-safe for growing struct)
|
||||
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();
|
||||
if (bytes_read != bytes_to_read) {
|
||||
setMQTTPrefsDefaults(&_mqtt_prefs);
|
||||
}
|
||||
} else {
|
||||
// File too small - reinitialize to defaults
|
||||
file.close();
|
||||
setMQTTPrefsDefaults(&_mqtt_prefs);
|
||||
}
|
||||
file.close();
|
||||
|
||||
// Migration: check if legacy fields have data but new slot fields are empty
|
||||
bool slots_empty = (_mqtt_prefs.mqtt_slot_preset[0][0] == '\0' &&
|
||||
_mqtt_prefs.mqtt_slot_preset[1][0] == '\0' &&
|
||||
_mqtt_prefs.mqtt_slot_preset[2][0] == '\0');
|
||||
bool has_legacy = (_mqtt_prefs._legacy_analyzer_us_enabled != 0 ||
|
||||
_mqtt_prefs._legacy_analyzer_eu_enabled != 0 ||
|
||||
_mqtt_prefs._legacy_mqtt_server[0] != '\0');
|
||||
if (slots_empty && has_legacy) {
|
||||
MESH_DEBUG_PRINTLN("MQTT: Migrating legacy prefs to slot-based presets");
|
||||
// Migrate analyzer US
|
||||
if (_mqtt_prefs._legacy_analyzer_us_enabled == 1) {
|
||||
strncpy(_mqtt_prefs.mqtt_slot_preset[0], "analyzer-us", sizeof(_mqtt_prefs.mqtt_slot_preset[0]) - 1);
|
||||
_mqtt_prefs.mqtt_slot_preset[0][sizeof(_mqtt_prefs.mqtt_slot_preset[0]) - 1] = '\0';
|
||||
} else {
|
||||
strncpy(_mqtt_prefs.mqtt_slot_preset[0], "none", sizeof(_mqtt_prefs.mqtt_slot_preset[0]) - 1);
|
||||
_mqtt_prefs.mqtt_slot_preset[0][sizeof(_mqtt_prefs.mqtt_slot_preset[0]) - 1] = '\0';
|
||||
}
|
||||
// Migrate analyzer EU
|
||||
if (_mqtt_prefs._legacy_analyzer_eu_enabled == 1) {
|
||||
strncpy(_mqtt_prefs.mqtt_slot_preset[1], "analyzer-eu", sizeof(_mqtt_prefs.mqtt_slot_preset[1]) - 1);
|
||||
_mqtt_prefs.mqtt_slot_preset[1][sizeof(_mqtt_prefs.mqtt_slot_preset[1]) - 1] = '\0';
|
||||
} else {
|
||||
strncpy(_mqtt_prefs.mqtt_slot_preset[1], "none", sizeof(_mqtt_prefs.mqtt_slot_preset[1]) - 1);
|
||||
_mqtt_prefs.mqtt_slot_preset[1][sizeof(_mqtt_prefs.mqtt_slot_preset[1]) - 1] = '\0';
|
||||
}
|
||||
// Migrate custom server to slot 3
|
||||
if (_mqtt_prefs._legacy_mqtt_server[0] != '\0' && _mqtt_prefs._legacy_mqtt_port > 0) {
|
||||
strncpy(_mqtt_prefs.mqtt_slot_preset[2], "custom", sizeof(_mqtt_prefs.mqtt_slot_preset[2]) - 1);
|
||||
_mqtt_prefs.mqtt_slot_preset[2][sizeof(_mqtt_prefs.mqtt_slot_preset[2]) - 1] = '\0';
|
||||
strncpy(_mqtt_prefs.mqtt_slot_host[2], _mqtt_prefs._legacy_mqtt_server, sizeof(_mqtt_prefs.mqtt_slot_host[2]) - 1);
|
||||
_mqtt_prefs.mqtt_slot_host[2][sizeof(_mqtt_prefs.mqtt_slot_host[2]) - 1] = '\0';
|
||||
_mqtt_prefs.mqtt_slot_port[2] = _mqtt_prefs._legacy_mqtt_port;
|
||||
strncpy(_mqtt_prefs.mqtt_slot_username[2], _mqtt_prefs._legacy_mqtt_username, sizeof(_mqtt_prefs.mqtt_slot_username[2]) - 1);
|
||||
_mqtt_prefs.mqtt_slot_username[2][sizeof(_mqtt_prefs.mqtt_slot_username[2]) - 1] = '\0';
|
||||
strncpy(_mqtt_prefs.mqtt_slot_password[2], _mqtt_prefs._legacy_mqtt_password, sizeof(_mqtt_prefs.mqtt_slot_password[2]) - 1);
|
||||
_mqtt_prefs.mqtt_slot_password[2][sizeof(_mqtt_prefs.mqtt_slot_password[2]) - 1] = '\0';
|
||||
} else {
|
||||
strncpy(_mqtt_prefs.mqtt_slot_preset[2], "none", sizeof(_mqtt_prefs.mqtt_slot_preset[2]) - 1);
|
||||
_mqtt_prefs.mqtt_slot_preset[2][sizeof(_mqtt_prefs.mqtt_slot_preset[2]) - 1] = '\0';
|
||||
}
|
||||
// Clear legacy fields
|
||||
_mqtt_prefs._legacy_analyzer_us_enabled = 0;
|
||||
_mqtt_prefs._legacy_analyzer_eu_enabled = 0;
|
||||
memset(_mqtt_prefs._legacy_mqtt_server, 0, sizeof(_mqtt_prefs._legacy_mqtt_server));
|
||||
_mqtt_prefs._legacy_mqtt_port = 0;
|
||||
memset(_mqtt_prefs._legacy_mqtt_username, 0, sizeof(_mqtt_prefs._legacy_mqtt_username));
|
||||
memset(_mqtt_prefs._legacy_mqtt_password, 0, sizeof(_mqtt_prefs._legacy_mqtt_password));
|
||||
// Save migrated prefs
|
||||
saveMQTTPrefs(fs);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Migration: Try to read from old /com_prefs file if it exists
|
||||
// This handles the case where MQTT settings were previously stored in /com_prefs
|
||||
if (fs->exists("/com_prefs")) {
|
||||
#if defined(RP2040_PLATFORM)
|
||||
File file = fs->open("/com_prefs", "r");
|
||||
#else
|
||||
File file = fs->open("/com_prefs");
|
||||
#endif
|
||||
if (file) {
|
||||
// Skip to MQTT section (after advert_loc_policy at offset 161)
|
||||
// Calculate offset: we need to skip everything up to and including advert_loc_policy
|
||||
size_t offset_to_mqtt =
|
||||
sizeof(_prefs->airtime_factor) + sizeof(_prefs->node_name) + 4 + // pad
|
||||
sizeof(_prefs->node_lat) + sizeof(_prefs->node_lon) +
|
||||
sizeof(_prefs->password) + sizeof(_prefs->freq) +
|
||||
sizeof(_prefs->tx_power_dbm) + sizeof(_prefs->disable_fwd) +
|
||||
sizeof(_prefs->advert_interval) + sizeof(_prefs->rx_boosted_gain) +
|
||||
sizeof(_prefs->rx_delay_base) + sizeof(_prefs->tx_delay_factor) +
|
||||
sizeof(_prefs->guest_password) + sizeof(_prefs->direct_tx_delay_factor) + 4 + // pad
|
||||
sizeof(_prefs->sf) + sizeof(_prefs->cr) +
|
||||
sizeof(_prefs->allow_read_only) + sizeof(_prefs->multi_acks) +
|
||||
sizeof(_prefs->bw) + sizeof(_prefs->agc_reset_interval) + 3 + // pad
|
||||
sizeof(_prefs->flood_max) + sizeof(_prefs->flood_advert_interval) +
|
||||
sizeof(_prefs->interference_threshold) + sizeof(_prefs->bridge_enabled) +
|
||||
sizeof(_prefs->bridge_delay) + sizeof(_prefs->bridge_pkt_src) +
|
||||
sizeof(_prefs->bridge_baud) + sizeof(_prefs->bridge_channel) +
|
||||
sizeof(_prefs->bridge_secret) + 4 + // pad
|
||||
sizeof(_prefs->gps_enabled) + sizeof(_prefs->gps_interval) +
|
||||
sizeof(_prefs->advert_loc_policy);
|
||||
|
||||
// Check if file is large enough and seek succeeded
|
||||
if (file.size() >= offset_to_mqtt + sizeof(_mqtt_prefs)) {
|
||||
if (file.seek(offset_to_mqtt)) {
|
||||
size_t bytes_read = file.read((uint8_t *)&_mqtt_prefs, sizeof(_mqtt_prefs));
|
||||
if (bytes_read == sizeof(_mqtt_prefs)) {
|
||||
// Successfully migrated - save to new location for future use
|
||||
file.close();
|
||||
saveMQTTPrefs(fs);
|
||||
return; // Migration successful
|
||||
}
|
||||
}
|
||||
}
|
||||
file.close();
|
||||
// Migration failed - defaults already set, just return
|
||||
return;
|
||||
}
|
||||
}
|
||||
// No file exists and migration didn't happen - defaults already set
|
||||
// No /mqtt_prefs file — defaults already set
|
||||
// (Legacy /com_prefs migration removed: the old offset-based approach was fragile
|
||||
// and the pre-MQTT firmware never wrote MQTT fields to /com_prefs anyway.)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -472,6 +435,8 @@ void CommonCLI::syncMQTTPrefsToNodePrefs() {
|
||||
_prefs->mqtt_slot_port[i] = _mqtt_prefs.mqtt_slot_port[i];
|
||||
StrHelper::strncpy(_prefs->mqtt_slot_username[i], _mqtt_prefs.mqtt_slot_username[i], sizeof(_prefs->mqtt_slot_username[i]));
|
||||
StrHelper::strncpy(_prefs->mqtt_slot_password[i], _mqtt_prefs.mqtt_slot_password[i], sizeof(_prefs->mqtt_slot_password[i]));
|
||||
StrHelper::strncpy(_prefs->mqtt_slot_token[i], _mqtt_prefs.mqtt_slot_token[i], sizeof(_prefs->mqtt_slot_token[i]));
|
||||
StrHelper::strncpy(_prefs->mqtt_slot_topic[i], _mqtt_prefs.mqtt_slot_topic[i], sizeof(_prefs->mqtt_slot_topic[i]));
|
||||
}
|
||||
StrHelper::strncpy(_prefs->mqtt_owner_public_key, _mqtt_prefs.mqtt_owner_public_key, sizeof(_prefs->mqtt_owner_public_key));
|
||||
StrHelper::strncpy(_prefs->mqtt_email, _mqtt_prefs.mqtt_email, sizeof(_prefs->mqtt_email));
|
||||
@@ -499,6 +464,8 @@ void CommonCLI::syncNodePrefsToMQTTPrefs() {
|
||||
_mqtt_prefs.mqtt_slot_port[i] = _prefs->mqtt_slot_port[i];
|
||||
StrHelper::strncpy(_mqtt_prefs.mqtt_slot_username[i], _prefs->mqtt_slot_username[i], sizeof(_mqtt_prefs.mqtt_slot_username[i]));
|
||||
StrHelper::strncpy(_mqtt_prefs.mqtt_slot_password[i], _prefs->mqtt_slot_password[i], sizeof(_mqtt_prefs.mqtt_slot_password[i]));
|
||||
StrHelper::strncpy(_mqtt_prefs.mqtt_slot_token[i], _prefs->mqtt_slot_token[i], sizeof(_mqtt_prefs.mqtt_slot_token[i]));
|
||||
StrHelper::strncpy(_mqtt_prefs.mqtt_slot_topic[i], _prefs->mqtt_slot_topic[i], sizeof(_mqtt_prefs.mqtt_slot_topic[i]));
|
||||
}
|
||||
StrHelper::strncpy(_mqtt_prefs.mqtt_owner_public_key, _prefs->mqtt_owner_public_key, sizeof(_mqtt_prefs.mqtt_owner_public_key));
|
||||
StrHelper::strncpy(_mqtt_prefs.mqtt_email, _prefs->mqtt_email, sizeof(_mqtt_prefs.mqtt_email));
|
||||
@@ -759,6 +726,18 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch
|
||||
sprintf(reply, "> %s", _prefs->mqtt_slot_username[slot]);
|
||||
} else if (memcmp(subcmd, "password", 8) == 0) {
|
||||
sprintf(reply, "> %s", _prefs->mqtt_slot_password[slot]);
|
||||
} else if (memcmp(subcmd, "token", 5) == 0) {
|
||||
if (_prefs->mqtt_slot_token[slot][0] != '\0') {
|
||||
sprintf(reply, "> %s", _prefs->mqtt_slot_token[slot]);
|
||||
} else {
|
||||
strcpy(reply, "> (not set)");
|
||||
}
|
||||
} else if (memcmp(subcmd, "topic", 5) == 0) {
|
||||
if (_prefs->mqtt_slot_topic[slot][0] != '\0') {
|
||||
sprintf(reply, "> %s", _prefs->mqtt_slot_topic[slot]);
|
||||
} else {
|
||||
strcpy(reply, "> (default: meshcore/{iata}/{device}/{type})");
|
||||
}
|
||||
} else {
|
||||
sprintf(reply, "??: %s", config);
|
||||
}
|
||||
@@ -1126,6 +1105,7 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch
|
||||
_prefs->mqtt_iata[i] = toupper(_prefs->mqtt_iata[i]);
|
||||
}
|
||||
savePrefs();
|
||||
_callbacks->restartBridge();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(config, "mqtt.status ", 12) == 0) {
|
||||
_prefs->mqtt_status_enabled = memcmp(&config[12], "on", 2) == 0;
|
||||
@@ -1230,10 +1210,19 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch
|
||||
strcmp(preset_name, MQTT_PRESET_NONE) == 0) {
|
||||
StrHelper::strncpy(_prefs->mqtt_slot_preset[slot], preset_name, sizeof(_prefs->mqtt_slot_preset[slot]));
|
||||
savePrefs();
|
||||
_callbacks->restartBridge();
|
||||
sprintf(reply, "OK - slot %d preset: %s", slot + 1, preset_name);
|
||||
_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, custom, none");
|
||||
strcpy(reply, "Error: valid presets are: analyzer-us, analyzer-eu, meshmapper, meshrank, custom, none");
|
||||
}
|
||||
} else if (memcmp(subcmd, "server ", 7) == 0) {
|
||||
StrHelper::strncpy(_prefs->mqtt_slot_host[slot], &subcmd[7], sizeof(_prefs->mqtt_slot_host[slot]));
|
||||
@@ -1256,6 +1245,20 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, const char* command, ch
|
||||
StrHelper::strncpy(_prefs->mqtt_slot_password[slot], &subcmd[9], sizeof(_prefs->mqtt_slot_password[slot]));
|
||||
savePrefs();
|
||||
strcpy(reply, "OK");
|
||||
} else if (memcmp(subcmd, "token ", 6) == 0) {
|
||||
StrHelper::strncpy(_prefs->mqtt_slot_token[slot], &subcmd[6], sizeof(_prefs->mqtt_slot_token[slot]));
|
||||
savePrefs();
|
||||
_callbacks->restartBridgeSlot(slot);
|
||||
sprintf(reply, "OK - slot %d token set", slot + 1);
|
||||
} else if (memcmp(subcmd, "topic ", 6) == 0) {
|
||||
if (strcmp(_prefs->mqtt_slot_preset[slot], "custom") != 0) {
|
||||
sprintf(reply, "Error: topic template only applies to custom preset slots");
|
||||
} else {
|
||||
StrHelper::strncpy(_prefs->mqtt_slot_topic[slot], &subcmd[6], sizeof(_prefs->mqtt_slot_topic[slot]));
|
||||
savePrefs();
|
||||
_callbacks->restartBridgeSlot(slot);
|
||||
sprintf(reply, "OK - slot %d topic: %s", slot + 1, _prefs->mqtt_slot_topic[slot]);
|
||||
}
|
||||
} else {
|
||||
sprintf(reply, "unknown config: %s", config);
|
||||
}
|
||||
|
||||
+41
-3
@@ -90,10 +90,38 @@ struct NodePrefs { // persisted to file
|
||||
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)
|
||||
|
||||
uint8_t loop_detect;
|
||||
};
|
||||
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
// Old MQTT preferences layout (pre-slot firmware) — used only for migration detection
|
||||
struct OldMQTTPrefs {
|
||||
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_server[64];
|
||||
uint16_t mqtt_port;
|
||||
char mqtt_username[32];
|
||||
char mqtt_password[64];
|
||||
uint8_t mqtt_analyzer_us_enabled;
|
||||
uint8_t mqtt_analyzer_eu_enabled;
|
||||
char mqtt_owner_public_key[65];
|
||||
char mqtt_email[64];
|
||||
};
|
||||
|
||||
// MQTT preferences stored in separate file to avoid conflicts with upstream NodePrefs changes
|
||||
struct MQTTPrefs {
|
||||
// MQTT settings
|
||||
@@ -127,15 +155,20 @@ struct MQTTPrefs {
|
||||
char mqtt_owner_public_key[65]; // Owner public key (hex string)
|
||||
char mqtt_email[64]; // Owner email address
|
||||
|
||||
// --- Legacy fields for migration detection ---
|
||||
// These are read during loadMQTTPrefs to detect old-format prefs and auto-migrate.
|
||||
// After migration they are zeroed out and not used again.
|
||||
// --- 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.
|
||||
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];
|
||||
|
||||
// --- 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)
|
||||
};
|
||||
#endif
|
||||
|
||||
@@ -173,6 +206,11 @@ public:
|
||||
// no op by default
|
||||
};
|
||||
|
||||
virtual void restartBridgeSlot(int slot) {
|
||||
// Default: fall back to full restart
|
||||
restartBridge();
|
||||
};
|
||||
|
||||
virtual int getQueueSize() {
|
||||
return 0; // no op by default
|
||||
};
|
||||
|
||||
@@ -8,12 +8,18 @@ enum MQTTAuthType : uint8_t {
|
||||
MQTT_AUTH_JWT // Ed25519-signed JWT (device identity)
|
||||
};
|
||||
|
||||
enum MQTTTopicStyle : uint8_t {
|
||||
MQTT_TOPIC_MESHCORE, // meshcore/{iata}/{device_id}/{status|packets|raw}
|
||||
MQTT_TOPIC_MESHRANK, // meshrank/uplink/{token}/{device_id}/packets (packets only)
|
||||
};
|
||||
|
||||
struct MQTTPresetDef {
|
||||
const char* name; // Preset identifier: "analyzer-us", "analyzer-eu", "meshmapper"
|
||||
const char* server_url; // Full URL including scheme: "wss://host:port/path" or "mqtt://host:port"
|
||||
const char* jwt_audience; // JWT audience field (only for MQTT_AUTH_JWT)
|
||||
const char* name; // Preset identifier: "analyzer-us", "analyzer-eu", "meshmapper", "meshrank"
|
||||
const char* server_url; // Full URL including scheme: "wss://host:port/path" or "mqtts://host:port"
|
||||
const char* jwt_audience; // JWT audience field (only for MQTT_AUTH_JWT, nullptr otherwise)
|
||||
const char* ca_cert; // PEM CA certificate (nullptr to skip cert pinning)
|
||||
MQTTAuthType auth_type;
|
||||
MQTTTopicStyle topic_style;
|
||||
};
|
||||
|
||||
// Google Trust Services - GTS Root R4 (used by LetsMesh Analyzer)
|
||||
@@ -75,13 +81,14 @@ static const char ISRG_ROOT_X1[] PROGMEM =
|
||||
"-----END CERTIFICATE-----\n";
|
||||
|
||||
// Number of built-in presets
|
||||
static const int MQTT_PRESET_COUNT = 3;
|
||||
static const int MQTT_PRESET_COUNT = 4;
|
||||
|
||||
// Built-in preset definitions (stored in flash)
|
||||
static const MQTTPresetDef MQTT_PRESETS[MQTT_PRESET_COUNT] = {
|
||||
{ "analyzer-us", "wss://mqtt-us-v1.letsmesh.net:443/mqtt", "mqtt-us-v1.letsmesh.net", GTS_ROOT_R4, MQTT_AUTH_JWT },
|
||||
{ "analyzer-eu", "wss://mqtt-eu-v1.letsmesh.net:443/mqtt", "mqtt-eu-v1.letsmesh.net", GTS_ROOT_R4, MQTT_AUTH_JWT },
|
||||
{ "meshmapper", "wss://mqtt.meshmapper.cc:443/mqtt", "mqtt.meshmapper.cc", ISRG_ROOT_X1, MQTT_AUTH_JWT },
|
||||
{ "analyzer-us", "wss://mqtt-us-v1.letsmesh.net:443/mqtt", "mqtt-us-v1.letsmesh.net", GTS_ROOT_R4, MQTT_AUTH_JWT, MQTT_TOPIC_MESHCORE },
|
||||
{ "analyzer-eu", "wss://mqtt-eu-v1.letsmesh.net:443/mqtt", "mqtt-eu-v1.letsmesh.net", GTS_ROOT_R4, MQTT_AUTH_JWT, MQTT_TOPIC_MESHCORE },
|
||||
{ "meshmapper", "wss://mqtt.meshmapper.cc:443/mqtt", "mqtt.meshmapper.cc", ISRG_ROOT_X1, MQTT_AUTH_JWT, MQTT_TOPIC_MESHCORE },
|
||||
{ "meshrank", "mqtts://meshrank.net:8883", nullptr, ISRG_ROOT_X1, MQTT_AUTH_NONE, MQTT_TOPIC_MESHRANK },
|
||||
};
|
||||
|
||||
// Find a preset by name, returns nullptr if not found
|
||||
|
||||
@@ -124,6 +124,9 @@ void MQTTBridge::formatMqttStatusReply(char* buf, size_t bufsize, const NodePref
|
||||
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) {
|
||||
snprintf(slot_info[i], sizeof(slot_info[i]), "slot%d: %s (%s)", i + 1,
|
||||
slot.preset->name,
|
||||
@@ -198,6 +201,7 @@ MQTTBridge::MQTTBridge(NodePrefs *prefs, mesh::PacketManager *mgr, mesh::RTCCloc
|
||||
_slots[i].last_reconnect_attempt = 0;
|
||||
_slots[i].last_log_time = 0;
|
||||
_slots[i].port = 1883;
|
||||
_slot_reconfigure_pending[i] = false;
|
||||
}
|
||||
|
||||
// Initialize JWT username
|
||||
@@ -445,8 +449,6 @@ void MQTTBridge::end() {
|
||||
if (_mqtt_task_handle != nullptr) {
|
||||
vTaskDelete(_mqtt_task_handle);
|
||||
_mqtt_task_handle = nullptr;
|
||||
// Give task time to clean up
|
||||
vTaskDelay(pdMS_TO_TICKS(100));
|
||||
}
|
||||
// Free PSRAM task stack
|
||||
psram_free(_mqtt_task_stack);
|
||||
@@ -617,6 +619,11 @@ void MQTTBridge::mqttTaskLoop() {
|
||||
_slots[i].enabled = false; // Disable so other loops skip it
|
||||
continue;
|
||||
}
|
||||
char reason[80];
|
||||
if (!isSlotReady(i, reason, sizeof(reason))) {
|
||||
MQTT_DEBUG_PRINTLN("Slot %d not ready — run '%s' to connect", i, reason);
|
||||
continue;
|
||||
}
|
||||
setupSlot(i);
|
||||
active_count++;
|
||||
// Stagger connections: 5s between slots to avoid simultaneous TLS handshakes
|
||||
@@ -628,6 +635,15 @@ void MQTTBridge::mqttTaskLoop() {
|
||||
}
|
||||
}
|
||||
|
||||
// Process pending slot reconfigures (queued from CLI on Core 1)
|
||||
for (int i = 0; i < MAX_MQTT_SLOTS; i++) {
|
||||
if (_slot_reconfigure_pending[i]) {
|
||||
_slot_reconfigure_pending[i] = false;
|
||||
MQTT_DEBUG_PRINTLN("Applying deferred reconfigure for slot %d (preset: %s)", i, _prefs->mqtt_slot_preset[i]);
|
||||
applySlotPreset(i, _prefs->mqtt_slot_preset[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Maintain slot connections (token renewal, reconnect with backoff)
|
||||
maintainSlotConnections();
|
||||
|
||||
@@ -1026,25 +1042,95 @@ bool MQTTBridge::publishToAllSlots(const char* topic, const char* payload, bool
|
||||
return published;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Topic building - resolves the correct topic for a given slot and message type.
|
||||
// Presets use hardcoded topic logic; custom slots support user-defined templates.
|
||||
// ---------------------------------------------------------------------------
|
||||
bool MQTTBridge::substituteTopicTemplate(const char* tmpl, MQTTMessageType type, int slot_index, char* buf, size_t buf_size) {
|
||||
const char* type_str = (type == MSG_STATUS) ? "status" : (type == MSG_PACKETS) ? "packets" : "raw";
|
||||
const char* token = _prefs->mqtt_slot_token[slot_index];
|
||||
|
||||
size_t out = 0;
|
||||
const char* p = tmpl;
|
||||
while (*p && out < buf_size - 1) {
|
||||
if (*p == '{') {
|
||||
if (strncmp(p, "{iata}", 6) == 0) {
|
||||
size_t len = strlen(_iata);
|
||||
if (out + len >= buf_size) return false;
|
||||
memcpy(buf + out, _iata, len);
|
||||
out += len;
|
||||
p += 6;
|
||||
} else if (strncmp(p, "{device}", 8) == 0) {
|
||||
size_t len = strlen(_device_id);
|
||||
if (out + len >= buf_size) return false;
|
||||
memcpy(buf + out, _device_id, len);
|
||||
out += len;
|
||||
p += 8;
|
||||
} else if (strncmp(p, "{token}", 7) == 0) {
|
||||
size_t len = strlen(token);
|
||||
if (out + len >= buf_size) return false;
|
||||
memcpy(buf + out, token, len);
|
||||
out += len;
|
||||
p += 7;
|
||||
} else if (strncmp(p, "{type}", 6) == 0) {
|
||||
size_t len = strlen(type_str);
|
||||
if (out + len >= buf_size) return false;
|
||||
memcpy(buf + out, type_str, len);
|
||||
out += len;
|
||||
p += 6;
|
||||
} else {
|
||||
buf[out++] = *p++;
|
||||
}
|
||||
} else {
|
||||
buf[out++] = *p++;
|
||||
}
|
||||
}
|
||||
buf[out] = '\0';
|
||||
return out > 0;
|
||||
}
|
||||
|
||||
bool MQTTBridge::buildTopicForSlot(int index, MQTTMessageType type, char* topic_buf, size_t buf_size) {
|
||||
if (index < 0 || index >= MAX_MQTT_SLOTS) return false;
|
||||
const MQTTSlot& slot = _slots[index];
|
||||
|
||||
// Preset slots: use hardcoded topic logic
|
||||
if (slot.preset) {
|
||||
if (slot.preset->topic_style == MQTT_TOPIC_MESHRANK) {
|
||||
// MeshRank: packets only, uses per-slot token in topic path
|
||||
if (type != MSG_PACKETS) return false;
|
||||
const char* token = _prefs->mqtt_slot_token[index];
|
||||
if (!token || token[0] == '\0') return false;
|
||||
snprintf(topic_buf, buf_size, "meshrank/uplink/%s/%s/packets", token, _device_id);
|
||||
return true;
|
||||
}
|
||||
// MQTT_TOPIC_MESHCORE (default for all other presets)
|
||||
if (!isIATAValid()) return false;
|
||||
const char* type_str = (type == MSG_STATUS) ? "status" : (type == MSG_PACKETS) ? "packets" : "raw";
|
||||
snprintf(topic_buf, buf_size, "meshcore/%s/%s/%s", _iata, _device_id, type_str);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Custom slots: use topic template if set, otherwise default meshcore format
|
||||
if (_prefs->mqtt_slot_topic[index][0] != '\0') {
|
||||
return substituteTopicTemplate(_prefs->mqtt_slot_topic[index], type, index, topic_buf, buf_size);
|
||||
}
|
||||
// Default: meshcore format
|
||||
if (!isIATAValid()) return false;
|
||||
const char* type_str = (type == MSG_STATUS) ? "status" : (type == MSG_PACKETS) ? "packets" : "raw";
|
||||
snprintf(topic_buf, buf_size, "meshcore/%s/%s/%s", _iata, _device_id, type_str);
|
||||
return true;
|
||||
}
|
||||
|
||||
void MQTTBridge::publishStatusToSlot(int index) {
|
||||
if (index < 0 || index >= MAX_MQTT_SLOTS) return;
|
||||
MQTTSlot& slot = _slots[index];
|
||||
if (!slot.client || !slot.connected) return;
|
||||
|
||||
// Check if IATA is configured before attempting to publish
|
||||
if (!isIATAValid()) {
|
||||
static unsigned long last_iata_warning = 0;
|
||||
unsigned long now = millis();
|
||||
if (now - last_iata_warning > 300000) {
|
||||
MQTT_DEBUG_PRINTLN("MQTT: Cannot publish status to slot %d - IATA code not configured (current: '%s')", index, _iata);
|
||||
last_iata_warning = now;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Create status message
|
||||
// Build per-slot topic (handles IATA check for meshcore, token check for meshrank)
|
||||
char status_topic[128];
|
||||
snprintf(status_topic, sizeof(status_topic), "meshcore/%s/%s/status", _iata, _device_id);
|
||||
if (!buildTopicForSlot(index, MSG_STATUS, status_topic, sizeof(status_topic))) {
|
||||
return; // Slot doesn't support status (e.g., meshrank) or missing required config
|
||||
}
|
||||
|
||||
static const size_t STATUS_JSON_SIZE = 768;
|
||||
char* json_buffer = (char*)psram_malloc(STATUS_JSON_SIZE);
|
||||
@@ -1130,6 +1216,23 @@ bool MQTTBridge::isAnySlotConnected() {
|
||||
|
||||
void MQTTBridge::setSlotPreset(int slot_index, const char* preset_name) {
|
||||
if (slot_index < 0 || slot_index >= MAX_MQTT_SLOTS) return;
|
||||
|
||||
// On ESP32, teardown/setup involves TLS and must run on the MQTT task (Core 0).
|
||||
// Set a flag so the MQTT task picks it up on its next loop iteration.
|
||||
#ifdef ESP_PLATFORM
|
||||
if (_mqtt_task_handle != nullptr) {
|
||||
_slot_reconfigure_pending[slot_index] = true;
|
||||
MQTT_DEBUG_PRINTLN("Slot %d reconfigure queued (preset: %s)", slot_index, preset_name);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
// Non-ESP32 or bridge not yet started: apply directly
|
||||
applySlotPreset(slot_index, preset_name);
|
||||
}
|
||||
|
||||
void MQTTBridge::applySlotPreset(int slot_index, const char* preset_name) {
|
||||
if (slot_index < 0 || slot_index >= MAX_MQTT_SLOTS) return;
|
||||
MQTTSlot& slot = _slots[slot_index];
|
||||
|
||||
teardownSlot(slot_index);
|
||||
@@ -1155,6 +1258,11 @@ void MQTTBridge::setSlotPreset(int slot_index, const char* preset_name) {
|
||||
slot.enabled = true;
|
||||
slot.preset = preset;
|
||||
if (_initialized) {
|
||||
char reason[80];
|
||||
if (!isSlotReady(slot_index, reason, sizeof(reason))) {
|
||||
MQTT_DEBUG_PRINTLN("Slot %d (%s) not ready — run '%s' to connect", slot_index, preset_name, reason);
|
||||
return;
|
||||
}
|
||||
setupSlot(slot_index);
|
||||
}
|
||||
}
|
||||
@@ -1278,6 +1386,35 @@ bool MQTTBridge::isIATAValid() const {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MQTTBridge::isSlotReady(int index, char* reason_buf, size_t reason_size) const {
|
||||
if (index < 0 || index >= MAX_MQTT_SLOTS) return false;
|
||||
const MQTTSlot& slot = _slots[index];
|
||||
|
||||
if (!slot.enabled) return true; // disabled slots are "ready" (nothing to do)
|
||||
|
||||
if (slot.preset) {
|
||||
if (slot.preset->topic_style == MQTT_TOPIC_MESHRANK) {
|
||||
if (_prefs->mqtt_slot_token[index][0] == '\0') {
|
||||
if (reason_buf) snprintf(reason_buf, reason_size, "set mqtt%d.token <your_token>", index + 1);
|
||||
return false;
|
||||
}
|
||||
} else if (slot.preset->topic_style == MQTT_TOPIC_MESHCORE) {
|
||||
if (!isIATAValid()) {
|
||||
if (reason_buf) snprintf(reason_buf, reason_size, "set mqtt.iata <airport_code>");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Custom slot without a topic template uses meshcore format, needs IATA
|
||||
if (_prefs->mqtt_slot_topic[index][0] == '\0' && !isIATAValid()) {
|
||||
if (reason_buf) snprintf(reason_buf, reason_size, "set mqtt.iata <airport_code> or set mqtt%d.topic <template>", index + 1);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// loop() - non-ESP32 main loop (ESP32 uses mqttTaskLoop via FreeRTOS task)
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1307,12 +1444,23 @@ void MQTTBridge::loop() {
|
||||
_slots[i].enabled = false;
|
||||
continue;
|
||||
}
|
||||
if (!isSlotReady(i)) {
|
||||
continue;
|
||||
}
|
||||
setupSlot(i);
|
||||
active_count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process pending slot reconfigures
|
||||
for (int i = 0; i < MAX_MQTT_SLOTS; i++) {
|
||||
if (_slot_reconfigure_pending[i]) {
|
||||
_slot_reconfigure_pending[i] = false;
|
||||
applySlotPreset(i, _prefs->mqtt_slot_preset[i]);
|
||||
}
|
||||
}
|
||||
|
||||
// Maintain slot connections (token renewal, reconnect with backoff)
|
||||
maintainSlotConnections();
|
||||
|
||||
@@ -1560,17 +1708,6 @@ void MQTTBridge::processPacketQueue() {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
bool MQTTBridge::publishStatus() {
|
||||
// Check if IATA is configured before attempting to publish
|
||||
if (!isIATAValid()) {
|
||||
static unsigned long last_iata_warning = 0;
|
||||
unsigned long now = millis();
|
||||
if (now - last_iata_warning > 300000) {
|
||||
MQTT_DEBUG_PRINTLN("MQTT: Cannot publish status - IATA code not configured (current: '%s'). Please set mqtt.iata via CLI.", _iata);
|
||||
last_iata_warning = now;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!_cached_has_connected_slots) {
|
||||
return false;
|
||||
}
|
||||
@@ -1631,13 +1768,23 @@ bool MQTTBridge::publishStatus() {
|
||||
);
|
||||
|
||||
if (len > 0) {
|
||||
bool published = false;
|
||||
bool any_slot_wants_status = false;
|
||||
char topic[128];
|
||||
snprintf(topic, sizeof(topic), "meshcore/%s/%s/status", _iata, _device_id);
|
||||
|
||||
bool published = publishToAllSlots(topic, json_buffer, true);
|
||||
|
||||
if (published) {
|
||||
MQTT_DEBUG_PRINTLN("Status published");
|
||||
for (int i = 0; i < MAX_MQTT_SLOTS; i++) {
|
||||
if (_slots[i].enabled && _slots[i].client && _slots[i].connected) {
|
||||
if (buildTopicForSlot(i, MSG_STATUS, topic, sizeof(topic))) {
|
||||
any_slot_wants_status = true;
|
||||
if (publishToSlot(i, topic, json_buffer, true)) {
|
||||
published = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// If no connected slot accepts status topics (e.g. meshrank is packets-only),
|
||||
// treat as success to avoid infinite retry loops
|
||||
if (published || !any_slot_wants_status) {
|
||||
if (published) MQTT_DEBUG_PRINTLN("Status published");
|
||||
psram_free(json_buffer);
|
||||
return true;
|
||||
}
|
||||
@@ -1652,17 +1799,6 @@ void MQTTBridge::publishPacket(mesh::Packet* packet, bool is_tx,
|
||||
float snr, float rssi) {
|
||||
if (!packet) return;
|
||||
|
||||
// Check if IATA is configured before attempting to publish
|
||||
if (!isIATAValid()) {
|
||||
static unsigned long last_iata_warning = 0;
|
||||
unsigned long now = millis();
|
||||
if (now - last_iata_warning > 300000) {
|
||||
MQTT_DEBUG_PRINTLN("MQTT: Cannot publish packet - IATA code not configured (current: '%s'). Please set mqtt.iata via CLI.", _iata);
|
||||
last_iata_warning = now;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Memory pressure check: Skip publishes when heap is severely fragmented
|
||||
#ifdef ESP32
|
||||
unsigned long now = millis();
|
||||
@@ -1721,8 +1857,13 @@ void MQTTBridge::publishPacket(mesh::Packet* packet, bool is_tx,
|
||||
|
||||
if (len > 0) {
|
||||
char topic[128];
|
||||
snprintf(topic, sizeof(topic), "meshcore/%s/%s/packets", _iata, _device_id);
|
||||
publishToAllSlots(topic, active_buffer, false);
|
||||
for (int i = 0; i < MAX_MQTT_SLOTS; i++) {
|
||||
if (_slots[i].enabled && _slots[i].client && _slots[i].connected) {
|
||||
if (buildTopicForSlot(i, MSG_PACKETS, topic, sizeof(topic))) {
|
||||
publishToSlot(i, topic, active_buffer, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
uint8_t packet_type = packet->getPayloadType();
|
||||
if (packet_type == 4 || packet_type == 9) {
|
||||
@@ -1735,16 +1876,6 @@ void MQTTBridge::publishPacket(mesh::Packet* packet, bool is_tx,
|
||||
void MQTTBridge::publishRaw(mesh::Packet* packet) {
|
||||
if (!packet) return;
|
||||
|
||||
if (!isIATAValid()) {
|
||||
static unsigned long last_iata_warning = 0;
|
||||
unsigned long now = millis();
|
||||
if (now - last_iata_warning > 300000) {
|
||||
MQTT_DEBUG_PRINTLN("MQTT: Cannot publish raw packet - IATA code not configured (current: '%s'). Please set mqtt.iata via CLI.", _iata);
|
||||
last_iata_warning = now;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// JSON buffer: prefer PSRAM; fallback to stack if allocation fails
|
||||
char* json_buffer_psram = (char*)psram_malloc(2048);
|
||||
char json_buffer_stack[1024];
|
||||
@@ -1770,8 +1901,13 @@ void MQTTBridge::publishRaw(mesh::Packet* packet) {
|
||||
|
||||
if (len > 0) {
|
||||
char topic[128];
|
||||
snprintf(topic, sizeof(topic), "meshcore/%s/%s/raw", _iata, _device_id);
|
||||
publishToAllSlots(topic, active_buffer, false);
|
||||
for (int i = 0; i < MAX_MQTT_SLOTS; i++) {
|
||||
if (_slots[i].enabled && _slots[i].client && _slots[i].connected) {
|
||||
if (buildTopicForSlot(i, MSG_RAW, topic, sizeof(topic))) {
|
||||
publishToSlot(i, topic, active_buffer, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
psram_free(json_buffer_psram);
|
||||
}
|
||||
@@ -1884,7 +2020,7 @@ void MQTTBridge::dequeuePacket() {
|
||||
void MQTTBridge::storeRawRadioData(const uint8_t* raw_data, int len, float snr, float rssi) {
|
||||
if (len > 0 && len <= LAST_RAW_DATA_SIZE && _last_raw_data) {
|
||||
#ifdef ESP_PLATFORM
|
||||
if (_raw_data_mutex != nullptr && xSemaphoreTake(_raw_data_mutex, pdMS_TO_TICKS(100)) == pdTRUE) {
|
||||
if (_raw_data_mutex != nullptr && xSemaphoreTake(_raw_data_mutex, pdMS_TO_TICKS(5)) == pdTRUE) {
|
||||
memcpy(_last_raw_data, raw_data, len);
|
||||
_last_raw_len = len;
|
||||
_last_snr = snr;
|
||||
|
||||
@@ -141,6 +141,9 @@ private:
|
||||
bool _slots_setup_done; // Deferred: slots set up after NTP sync
|
||||
int _max_active_slots; // Runtime limit: 3 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];
|
||||
|
||||
// Timezone handling
|
||||
Timezone* _timezone;
|
||||
|
||||
@@ -190,6 +193,11 @@ private:
|
||||
mesh::MainBoard* _board; // For battery voltage
|
||||
mesh::MillisecondClock* _ms; // For uptime
|
||||
|
||||
// Topic building
|
||||
enum MQTTMessageType { MSG_STATUS, MSG_PACKETS, MSG_RAW };
|
||||
bool buildTopicForSlot(int index, MQTTMessageType type, char* topic_buf, size_t buf_size);
|
||||
bool substituteTopicTemplate(const char* tmpl, MQTTMessageType type, int slot_index, char* buf, size_t buf_size);
|
||||
|
||||
// Internal methods - slot management
|
||||
void setupSlot(int index); // Create/destroy client for a slot based on its preset
|
||||
void teardownSlot(int index); // Disconnect and free slot resources
|
||||
@@ -226,6 +234,7 @@ private:
|
||||
Timezone* createTimezoneFromString(const char* tz_string);
|
||||
void checkConfigurationMismatch();
|
||||
bool isIATAValid() const;
|
||||
bool isSlotReady(int index, char* reason_buf = nullptr, size_t reason_size = 0) const;
|
||||
|
||||
void optimizeMqttClientConfig(PsychicMqttClient* client, bool needs_large_buffer = false);
|
||||
void getClientVersion(char* buffer, size_t buffer_size) const;
|
||||
@@ -249,6 +258,7 @@ public:
|
||||
* @param preset_name Preset name: "analyzer-us", "analyzer-eu", "meshmapper", "custom", "none"
|
||||
*/
|
||||
void setSlotPreset(int slot_index, const char* preset_name);
|
||||
void applySlotPreset(int slot_index, const char* preset_name);
|
||||
|
||||
/**
|
||||
* Configure custom broker settings for a slot. Only applies when the
|
||||
|
||||
Reference in new issue
Block a user