feat(mqtt): enhance packet filter functionality with named types

Add support for named packet types in per-slot filters, allowing users
to specify packet types using descriptive names alongside numeric values.
This improves usability and clarity in configuring MQTT slot filters.
Updates include modifications to the parsing logic, WebConfig interface,
and related documentation to reflect the new naming conventions.
This commit is contained in:
agessaman committed 2026-07-27 22:29:11 -07:00
1 parent e00b29b4b8
commit 52bd27190f
17 files changed
+830 -87

No files matched your search

+6 -3
View File
@@ -944,12 +944,15 @@ bool CommonCLI::saveMQTTPrefs(FILESYSTEM* fs) {
}
// Write header and payload sequentially so the transaction needs no second
// full-size (2.8 KiB) staging buffer on constrained targets.
const MQTTPrefsHeader header = MQTTPrefsCodec::makeHeader();
// full-size (2.8 KiB) staging buffer on constrained targets. The length is
// the shortest that still round-trips this config, so a node with default
// packet filters keeps writing a payload older firmware can read.
const size_t payload_len = MQTTPrefsCodec::payloadLenFor(_mqtt_prefs);
const MQTTPrefsHeader header = MQTTPrefsCodec::makeHeader(payload_len);
MQTTPrefsFileStore store(fs);
const MQTTPrefsAtomicStore::Result result = MQTTPrefsAtomicStore::write(
store, (const uint8_t *)&header, sizeof(header),
(const uint8_t *)&_mqtt_prefs, sizeof(_mqtt_prefs));
(const uint8_t *)&_mqtt_prefs, payload_len);
if (!MQTTPrefsAtomicStore::committed(result)) {
MESH_DEBUG_PRINTLN("MQTT: atomic /mqtt_prefs save failed at %s; source preserved",
mqttPrefsSaveResultName(result));
+13 -1
View File
@@ -536,13 +536,25 @@ bool CommonCLI::handleObserverSetCmd(uint32_t sender_timestamp, const char* conf
const char* filter_value = subcmd[6] == '\0' ? "" : &subcmd[7];
uint16_t filter_mask = 0;
if (!MQTTPacketFilter::parse(filter_value, &filter_mask)) {
strcpy(reply, "Error: filter must be all, none, or CSV packet types 0-15");
strcpy(reply, "Error: filter must be all, none, or a CSV of types 0-15 / names (advert,txt_msg,...)");
} else {
_mqtt_prefs.mqtt_slot_packet_filter[slot] = filter_mask;
savePrefs();
char filter_text[MQTTPacketFilter::kFilterTextSize];
MQTTPacketFilter::format(filter_mask, filter_text, sizeof(filter_text));
snprintf(reply, 160, "OK - slot %d packet types: %s", slot + 1, filter_text);
// A non-default filter extends /mqtt_prefs past what pre-filter
// firmware can read (see MQTTPrefsCodec::payloadLenFor), so say when
// that cost buys nothing: slots beyond the runtime array are never
// published to on this board, the same warning `preset` gives.
if (slot >= RUNTIME_MQTT_SLOTS &&
filter_mask != MQTTPacketFilter::kAllPacketTypes) {
size_t used = strlen(reply);
if (used < 158) {
snprintf(reply + used, 160 - used,
" (slot inactive on this hardware; blocks firmware rollback)");
}
}
}
} else {
sprintf(reply, "unknown config: %s", config);
+123 -23
View File
@@ -23,11 +23,58 @@ inline bool tokenEquals(const char* begin, size_t len, const char* token) {
return token != nullptr && strlen(token) == len && memcmp(begin, token, len) == 0;
}
// Parse a canonical allowlist value. Empty input means "all" so WebConfig can
// clear a field and retain the same backwards-compatible default as an older
// /mqtt_prefs file. Keywords are deliberately lowercase and cannot be mixed
// with numeric entries. Decimal entries may contain surrounding ASCII
// whitespace, must be in 0..15, and may be repeated.
// Payload-type spellings accepted alongside the decimal form, mirroring the
// PAYLOAD_TYPE_* names in src/Packet.h. Types 12-14 are reserved upstream and
// have no name, so they stay reachable only by number.
struct NamedPacketType {
const char* name;
uint8_t type;
};
inline const NamedPacketType* namedPacketTypes(size_t* count_out) {
static const NamedPacketType kNames[] = {
{"req", 0}, {"response", 1}, {"txt_msg", 2}, {"ack", 3},
{"advert", 4}, {"grp_txt", 5}, {"grp_data", 6}, {"anon_req", 7},
{"path", 8}, {"trace", 9}, {"multipart", 10}, {"control", 11},
{"raw_custom", 15},
};
if (count_out != nullptr) *count_out = sizeof(kNames) / sizeof(kNames[0]);
return kNames;
}
// Resolve one already-trimmed list entry to a payload type. Decimal and named
// spellings are interchangeable within a list; "all"/"none" are whole-value
// keywords and deliberately do not resolve here, so "all,2" stays invalid.
inline bool resolveToken(const char* begin, size_t len, uint8_t* type_out) {
if (begin == nullptr || type_out == nullptr || len == 0) return false;
if (*begin >= '0' && *begin <= '9') {
unsigned value = 0;
for (size_t i = 0; i < len; ++i) {
if (begin[i] < '0' || begin[i] > '9') return false;
value = value * 10u + static_cast<unsigned>(begin[i] - '0');
if (value > kMaxPacketType) return false;
}
*type_out = static_cast<uint8_t>(value);
return true;
}
size_t name_count = 0;
const NamedPacketType* names = namedPacketTypes(&name_count);
for (size_t i = 0; i < name_count; ++i) {
if (tokenEquals(begin, len, names[i].name)) {
*type_out = names[i].type;
return true;
}
}
return false;
}
// Parse an allowlist value. Empty input means "all" so WebConfig can clear a
// field and retain the same backwards-compatible default as an older
// /mqtt_prefs file. Keywords and type names are deliberately lowercase; "all"
// and "none" cannot be mixed into a list. Entries may be decimal (0..15) or
// named, may carry surrounding ASCII whitespace, and may be repeated.
inline bool parse(const char* input, uint16_t* mask_out) {
if (input == nullptr || mask_out == nullptr) return false;
@@ -48,23 +95,23 @@ inline bool parse(const char* input, uint16_t* mask_out) {
uint16_t parsed = 0;
const char* cursor = begin;
while (cursor < end) {
while (cursor < end && isAsciiSpace(*cursor)) cursor++;
if (cursor >= end || *cursor < '0' || *cursor > '9') return false;
for (;;) {
const char* comma = cursor;
while (comma < end && *comma != ',') comma++;
unsigned value = 0;
while (cursor < end && *cursor >= '0' && *cursor <= '9') {
value = value * 10u + static_cast<unsigned>(*cursor - '0');
if (value > kMaxPacketType) return false;
cursor++;
const char* token_begin = cursor;
const char* token_end = comma;
while (token_begin < token_end && isAsciiSpace(*token_begin)) token_begin++;
while (token_end > token_begin && isAsciiSpace(token_end[-1])) token_end--;
uint8_t type = 0;
if (!resolveToken(token_begin, static_cast<size_t>(token_end - token_begin), &type)) {
return false;
}
while (cursor < end && isAsciiSpace(*cursor)) cursor++;
parsed |= static_cast<uint16_t>(1u << type);
parsed |= static_cast<uint16_t>(1u << value);
if (cursor == end) break;
if (*cursor != ',') return false;
cursor++;
if (cursor == end) return false;
if (comma >= end) break;
cursor = comma + 1;
}
*mask_out = parsed;
@@ -104,17 +151,70 @@ inline bool format(uint16_t mask, char* output, size_t output_size) {
return true;
}
// The keyword shortcut above means format() never actually emits the whole
// 0..15 list, but the emit loop is written for every type, so the internal
// buffer must still hold it: 22 digits + 15 separators + NUL.
static_assert(kFilterTextSize >= 38, "filter text buffer must hold the full 0..15 list");
inline bool allows(uint16_t mask, uint8_t packet_type) {
return packet_type <= kMaxPacketType &&
(mask & static_cast<uint16_t>(1u << packet_type)) != 0;
}
// Eligibility deliberately excludes connection state. A temporarily
// disconnected broker that is configured for this type still requires the
// shared queue's existing bounded retry policy.
// How many types a mask allows. Lets a length-constrained reply fall back to
// "N/16" instead of a clipped list, which would read as a different allowlist.
inline uint8_t countTypes(uint16_t mask) {
uint8_t total = 0;
for (uint8_t type = kMinPacketType; type <= kMaxPacketType; ++type) {
if ((mask & static_cast<uint16_t>(1u << type)) != 0) total++;
}
return total;
}
// Conservative "could any configured broker want this type?" mask, used to
// reject a packet before it is copied into the publish queue. Disabled slots
// contribute nothing; a slot whose topic style later turns out not to support
// the publication is still counted here, so the gate never drops a packet the
// per-slot pass would have published.
inline uint16_t enabledUnion(const uint16_t* masks, const bool* enabled, size_t count) {
if (masks == nullptr) return 0;
uint16_t combined = 0;
for (size_t i = 0; i < count; ++i) {
if (enabled != nullptr && !enabled[i]) continue;
combined = static_cast<uint16_t>(combined | masks[i]);
}
return combined;
}
// True when every slot still carries the default all-types mask, i.e. nothing
// depends on the packet-filter tail of /mqtt_prefs being written.
inline bool allMasksDefault(const uint16_t* masks, size_t count) {
if (masks == nullptr) return true;
for (size_t i = 0; i < count; ++i) {
if (masks[i] != kAllPacketTypes) return false;
}
return true;
}
// Stage one of the publish gate: everything decidable before a packet is
// serialised or a topic is built. Cheap enough to run per packet per slot.
inline bool slotCandidate(bool slot_enabled, uint16_t mask, uint8_t packet_type) {
return slot_enabled && allows(mask, packet_type);
}
// The complete gate, once the slot's topic support is known. Eligibility
// deliberately excludes connection state: a temporarily disconnected broker
// that is configured for this type still requires the shared queue's existing
// bounded retry policy.
//
// eligiblePacketSlots() calls this directly, using slotCandidate() first only
// to skip the topic build for slots the mask already rejects. A slot that
// passes both therefore has its topic built again in the publish loop; that
// second build is the accepted cost of not carrying six 128-byte topics on the
// MQTT task stack.
inline bool slotEligible(bool slot_enabled, bool topic_supported,
uint16_t mask, uint8_t packet_type) {
return slot_enabled && topic_supported && allows(mask, packet_type);
return slotCandidate(slot_enabled, mask, packet_type) && topic_supported;
}
// A fully filtered/topic-incompatible packet is intentionally complete. Once
+27 -6
View File
@@ -2,6 +2,7 @@
#include <string.h>
#include "MQTTPacketFilter.h"
#include "MQTTPrefsStorage.h"
#ifdef WITH_MQTT_BRIDGE
@@ -41,20 +42,40 @@ static const size_t kV1PreFilterPayloadSize = MQTT_PREFS_V1_PRE_FILTER_PAYLOAD_S
static const size_t kV1BaselinePayloadSize = MQTT_PREFS_V1_FULL_PAYLOAD_SIZE;
static const size_t kEncodedSize = sizeof(MQTTPrefsHeader) + kV1BaselinePayloadSize;
inline MQTTPrefsHeader makeHeader() {
// Shortest payload length that still round-trips this configuration.
//
// The packet-filter tail is the only optional part of the current layout, and
// its default (all types) is exactly what a pre-filter decoder supplies for a
// missing tail. So a device whose filters are all default keeps writing the
// 2864-byte payload that pre-filter firmware can still read. That matters
// because /mqtt_prefs also carries the WiFi credentials: an unrecognised
// longer payload sends older firmware to defaults with no network, and it
// refuses to overwrite the file, so the node cannot be recovered over the air.
// Touching any filter opts that node into the longer payload — a deliberate,
// operator-initiated trade rather than a side effect of upgrading.
inline size_t payloadLenFor(const MQTTPrefs& prefs) {
return MQTTPacketFilter::allMasksDefault(prefs.mqtt_slot_packet_filter,
MQTT_PREFS_SLOT_COUNT)
? kV1PreFilterPayloadSize
: kV1BaselinePayloadSize;
}
inline MQTTPrefsHeader makeHeader(size_t payload_len) {
MQTTPrefsHeader header;
memcpy(header.magic, MQTT_PREFS_MAGIC, sizeof(header.magic));
header.version = MQTT_PREFS_VERSION;
header.payload_len = static_cast<uint16_t>(kV1BaselinePayloadSize);
header.payload_len = static_cast<uint16_t>(payload_len);
return header;
}
inline size_t encode(const MQTTPrefs& prefs, uint8_t* output, size_t output_size) {
if (output == nullptr || output_size < kEncodedSize) return 0;
const MQTTPrefsHeader header = makeHeader();
const size_t payload_len = payloadLenFor(prefs);
const size_t encoded_size = sizeof(MQTTPrefsHeader) + payload_len;
if (output == nullptr || output_size < encoded_size) return 0;
const MQTTPrefsHeader header = makeHeader(payload_len);
memcpy(output, &header, sizeof(header));
memcpy(output + sizeof(header), &prefs, sizeof(prefs));
return kEncodedSize;
memcpy(output + sizeof(header), &prefs, payload_len);
return encoded_size;
}
inline bool isMagicPrefix(const uint8_t* input, size_t available) {
+5
View File
@@ -140,6 +140,11 @@ static const uint32_t MQTT_NEIGHBORS_DEFAULT_INTERVAL_MS = MQTT_NEIGHBORS_DEFAUL
// - PRE_NEIGHBORS (2860): full observer tail, no neighbors fields yet.
// - PRE_FILTER (2864): neighbors tail, no per-slot packet filters.
// - FULL (2876): current baseline, with six uint16_t filter masks.
//
// FULL is the maximum written, not the default: MQTTPrefsCodec::payloadLenFor()
// keeps emitting PRE_FILTER while every slot holds the all-types default, so a
// node that never touches a filter stays readable by pre-filter firmware. See
// the rollback note there — /mqtt_prefs also carries the WiFi credentials.
static const size_t MQTT_PREFS_V1_PRE_OBSERVER_PAYLOAD_SIZE = 2736;
static const size_t MQTT_PREFS_V1_PRE_NEIGHBORS_PAYLOAD_SIZE = 2860;
static const size_t MQTT_PREFS_V1_PRE_FILTER_PAYLOAD_SIZE = 2864;
+110 -17
View File
@@ -330,10 +330,17 @@ void MQTTBridge::formatMqttStatsReply(char* buf, size_t bufsize) {
// drops=<outbox>/<skipped>: outbox-cap drops vs. memory-pressure skips.
int pos = 0;
replyAppendf(buf, bufsize, &pos, "> Free=%d Max=%d q:%d/%d Outbox=%u drops=%lu/%d |",
replyAppendf(buf, bufsize, &pos, "> Free=%d Max=%d q:%d/%d Outbox=%u drops=%lu/%d",
(int)ESP.getFreeHeap(), (int)ESP.getMaxAllocHeap(),
q, MAX_QUEUE_SIZE, (unsigned)outbox_total,
outbox_drops, b->_skipped_publishes);
// filt=<n>: packets the per-slot type filters rejected before the queue.
// Omitted while zero so an unfiltered node's reply keeps its former length —
// the per-slot list below is what usually gets clamped away first.
if (b->_filtered_packets > 0) {
replyAppendf(buf, bufsize, &pos, " filt=%lu", b->_filtered_packets);
}
replyAppendf(buf, bufsize, &pos, " |");
for (int i = 0; i < RUNTIME_MQTT_SLOTS; i++) {
if (!b->_slots[i].enabled || !b->_slots[i].client) continue;
replyAppendf(buf, bufsize, &pos, " s%d=%lu/%lu", i + 1,
@@ -370,6 +377,9 @@ bool MQTTBridge::getSlotStatusSnapshot(int slot_index, SlotStatusSnapshot* out)
}
out->publish_ok = slot.client ? slot.client->getPublishOk() : 0;
out->publish_err = slot.client ? slot.client->getPublishErr() : 0;
// Lets the portal show why a healthy slot is quiet.
out->filter_mask = b->_obs ? b->_obs->mqtt_slot_packet_filter[slot_index]
: MQTTPacketFilter::kAllPacketTypes;
return true;
}
@@ -476,6 +486,17 @@ void MQTTBridge::formatSlotDiagReply(char* buf, size_t bufsize, int slot_index)
// replyAppendf clamps pos on every call, so the chained appends below can't
// walk past the reply buffer even if the accumulated text exceeds it (A1).
// A non-default filter is the one healthy-looking reason for a slot to stop
// publishing, so it has to appear — but appended last. replyAppendf clamps at
// the 160-byte reply, and an error tail (TLS + mbedTLS + errno + age) can
// already reach ~117 chars, so putting the filter first would push the
// operator's diagnostic detail off the end of a failing slot's line.
const uint16_t filter_mask = b->_obs ? b->_obs->mqtt_slot_packet_filter[slot_index]
: MQTTPacketFilter::kAllPacketTypes;
char filter_text[MQTTPacketFilter::kFilterTextSize];
const bool show_filter = filter_mask != MQTTPacketFilter::kAllPacketTypes &&
MQTTPacketFilter::format(filter_mask, filter_text, sizeof(filter_text));
int pos = 0;
replyAppendf(buf, bufsize, &pos, "> mqtt%d: %s", slot_index + 1, state);
if (slot.disconnect_count > 0) {
@@ -486,14 +507,10 @@ void MQTTBridge::formatSlotDiagReply(char* buf, size_t bufsize, int slot_index)
}
}
// If connected with no errors, we're done
// Connected with no errors: nothing more to say about the connection.
if (slot.connected && slot.last_error_time == 0) {
replyAppendf(buf, bufsize, &pos, ", no errors");
return;
}
// Show last error if we have one
if (slot.last_error_time > 0) {
} else if (slot.last_error_time > 0) {
// TLS error with human-friendly description
if (slot.last_tls_err != 0) {
const char* desc = tlsErrorStr(slot.last_tls_err);
@@ -523,6 +540,26 @@ void MQTTBridge::formatSlotDiagReply(char* buf, size_t bufsize, int slot_index)
} else if (!slot.connected) {
replyAppendf(buf, bufsize, &pos, ", no error info");
}
// Appended last so it never displaces connection diagnostics. replyAppendf
// clamps rather than overflows, but a clipped type list is worse than no
// list: "…,13,14," parses as a real, different allowlist, and this is the
// one line an operator reads to find out why a slot is quiet. So the exact
// text is only emitted when it fits whole; otherwise fall back to a count,
// which cannot be misread. `get mqttN.filter` always has the exact value.
if (show_filter) {
static const int kFilterLabelLen = (int)sizeof(", filter:") - 1;
const int remaining = pos < (int)bufsize ? (int)bufsize - 1 - pos : 0;
const uint8_t allowed = MQTTPacketFilter::countTypes(filter_mask);
const int compact_len = kFilterLabelLen + (allowed >= 10 ? 5 : 4); // "N/16"
if (kFilterLabelLen + (int)strlen(filter_text) <= remaining) {
replyAppendf(buf, bufsize, &pos, ", filter:%s", filter_text);
} else if (compact_len <= remaining) {
replyAppendf(buf, bufsize, &pos, ", filter:%u/16", (unsigned)allowed);
}
// Neither fits: the slot is reporting so much error detail that the filter
// is the least useful field on the line. Omit it rather than mislead.
}
}
// Bounded cooperative-stop timeout for end() (see MQTTLifecycle::Coordinator).
@@ -2699,15 +2736,16 @@ void MQTTBridge::loop() {
void MQTTBridge::onPacketReceived(mesh::Packet *packet) {
if (!_initialized || !_obs->mqtt_packets_enabled || !_obs->mqtt_rx_enabled) return;
// Check if we have any enabled slots to send to
bool has_valid_slots = false;
for (int i = 0; i < RUNTIME_MQTT_SLOTS; i++) {
if (_slots[i].enabled && _slots[i].client) {
has_valid_slots = true;
break;
}
// Drop before the queue copy when no configured slot allows this payload
// type. A QueuedPacket carries the packet plus up to 256 bytes of raw radio
// data and crosses to Core 0, so filtering here (not at publish time) is
// what actually saves the queue slot and the memcpy. This also subsumes the
// older "is any slot configured at all?" pre-check.
bool filtered = false;
if (!shouldQueuePacketType(packet->getPayloadType(), filtered)) {
if (filtered) _filtered_packets++;
return;
}
if (!has_valid_slots) return;
// Queue packet for transmission
queuePacket(packet, false);
@@ -2725,6 +2763,13 @@ void MQTTBridge::sendPacket(mesh::Packet *packet) {
if (!_identity || memcmp(_identity->pub_key, packet->payload, PUB_KEY_SIZE) != 0) return;
}
// Same pre-queue filter gate as the RX path.
bool filtered = false;
if (!shouldQueuePacketType(packet->getPayloadType(), filtered)) {
if (filtered) _filtered_packets++;
return;
}
// Queue packet for transmission
queuePacket(packet, true);
}
@@ -3021,8 +3066,21 @@ void MQTTBridge::processPacketQueue() {
// Publishing
// ---------------------------------------------------------------------------
// Which slots will actually take this payload type, resolved in two stages so
// the cheap test runs first: the filter/enabled check costs a bit test, while
// the topic build costs an snprintf. Both are far cheaper than the ~2 KB JSON
// serialisation they gate, so this must complete before a caller builds a
// message — a slot that cannot form a topic (MeshRank raw, or a meshcore
// preset with no IATA set) would otherwise pay for a document nobody receives.
//
// A slot's connection state is deliberately not consulted: a configured but
// disconnected broker is still a target, so the packet stays on the queue for
// the existing bounded retry rather than being dropped as complete.
uint8_t MQTTBridge::eligiblePacketSlots(uint8_t packet_type, MQTTMessageType type) {
static_assert(RUNTIME_MQTT_SLOTS <= 8, "eligible slot mask must fit in uint8_t");
// Per-slot filters cover packet traffic only. Status and neighbors are
// documented as never filtered, so refuse those publication types here
// rather than silently applying a packet mask if a caller is added later.
if (!_obs || (type != MSG_PACKETS && type != MSG_RAW)) return 0;
uint8_t eligible_slots = 0;
@@ -3030,9 +3088,9 @@ uint8_t MQTTBridge::eligiblePacketSlots(uint8_t packet_type, MQTTMessageType typ
for (int i = 0; i < RUNTIME_MQTT_SLOTS; ++i) {
const bool slot_enabled = _slots[i].enabled && _slots[i].client != nullptr;
// Load once so a live CLI/WebConfig update cannot split this packet's
// eligibility decision across two different masks.
// decision across two different masks.
const uint16_t filter_mask = _obs->mqtt_slot_packet_filter[i];
if (!slot_enabled || !MQTTPacketFilter::allows(filter_mask, packet_type)) continue;
if (!MQTTPacketFilter::slotCandidate(slot_enabled, filter_mask, packet_type)) continue;
const bool topic_supported = buildTopicForSlot(i, type, topic, sizeof(topic));
if (MQTTPacketFilter::slotEligible(slot_enabled, topic_supported,
@@ -3043,6 +3101,34 @@ uint8_t MQTTBridge::eligiblePacketSlots(uint8_t packet_type, MQTTMessageType typ
return eligible_slots;
}
// Conservative pre-queue gate: the OR of every configured slot's mask. Runs on
// Core 1 in the radio callback, so it must stay cheap — a packet no broker
// wants is rejected before it is copied into the queue at all. `filtered`
// separates "a broker is configured but none wants this type" (worth counting)
// from "no broker configured at all" (the pre-existing silent drop).
bool MQTTBridge::shouldQueuePacketType(uint8_t packet_type, bool& filtered) {
filtered = false;
if (!_obs) return false;
uint16_t masks[RUNTIME_MQTT_SLOTS];
bool enabled[RUNTIME_MQTT_SLOTS];
bool any_enabled = false;
for (int i = 0; i < RUNTIME_MQTT_SLOTS; ++i) {
masks[i] = _obs->mqtt_slot_packet_filter[i];
enabled[i] = _slots[i].enabled && _slots[i].client != nullptr;
any_enabled = any_enabled || enabled[i];
}
if (!any_enabled) return false;
if (MQTTPacketFilter::allows(
MQTTPacketFilter::enabledUnion(masks, enabled, RUNTIME_MQTT_SLOTS),
packet_type)) {
return true;
}
filtered = true;
return false;
}
bool MQTTBridge::publishStatus() {
if (!_cached_has_connected_slots) {
return false;
@@ -3151,6 +3237,8 @@ bool MQTTBridge::publishPacket(mesh::Packet* packet, bool is_tx,
const uint8_t packet_type = packet->getPayloadType();
const uint8_t eligible_slots = eligiblePacketSlots(packet_type, MSG_PACKETS);
has_eligible_target = eligible_slots != 0;
// Filtered out everywhere, or no slot can form a packets topic: intentionally
// complete, and nothing below (JSON build included) is worth paying for.
if (!has_eligible_target) return false;
refreshOriginFromPrefs();
@@ -3258,6 +3346,9 @@ bool MQTTBridge::publishPacket(mesh::Packet* packet, bool is_tx,
bool published = false;
char topic[128];
for (int i = 0; i < RUNTIME_MQTT_SLOTS; i++) {
// Eligibility already proved this slot's topic builds; rebuilding it is
// one snprintf, cheaper than carrying a RUNTIME_MQTT_SLOTS x 128 topic
// cache on the MQTT task's 8 KB stack alongside the JSON buffer.
if ((eligible_slots & static_cast<uint8_t>(1u << i)) != 0 &&
_slots[i].enabled && _slots[i].client && _slots[i].connected) {
if (buildTopicForSlot(i, MSG_PACKETS, topic, sizeof(topic))) {
@@ -3283,6 +3374,8 @@ bool MQTTBridge::publishRaw(mesh::Packet* packet, bool& has_eligible_target) {
const uint8_t packet_type = packet->getPayloadType();
const uint8_t eligible_slots = eligiblePacketSlots(packet_type, MSG_RAW);
has_eligible_target = eligible_slots != 0;
// Filtered out everywhere, or no slot has a raw topic (MeshRank is
// packets-only): intentionally complete, and no JSON is built.
if (!has_eligible_target) return false;
refreshOriginFromPrefs();
+8
View File
@@ -326,6 +326,10 @@ private:
unsigned long _last_memory_check;
bool _memory_pressure = false; // Cached max-alloc verdict; re-sampled at most once per interval in publishPacket() so the heap walk isn't paid per-packet under pressure
int _skipped_publishes; // Exposed via SNMP; count of publishes skipped when max_alloc is too low
// Packets rejected by the per-slot filters before reaching the queue. Written
// on Core 1 (radio callbacks), read on Core 0 for `mqtt.stats`; a torn read of
// a diagnostic counter is harmless, so no atomic is warranted.
unsigned long _filtered_packets = 0;
// Status publish retry tracking
unsigned long _last_status_retry; // Track last retry attempt (separate from successful publish)
@@ -371,6 +375,7 @@ private:
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);
uint8_t eligiblePacketSlots(uint8_t packet_type, MQTTMessageType type);
bool shouldQueuePacketType(uint8_t packet_type, bool& filtered);
// Internal methods - slot management
// Lifetime model (Phase 1 of MQTT memory-defrag):
@@ -593,6 +598,9 @@ public:
const char* state; // "inactive" | "wait" | "ok" | "fail" | "disc"
unsigned long publish_ok;
unsigned long publish_err;
// Raw packet-type allowlist. Kept as the mask rather than canonical text so
// the 1 KB stats JSON stays compact; the portal renders it.
uint16_t filter_mask;
};
static bool getSlotStatusSnapshot(int slot_index, SlotStatusSnapshot* out);
/** True when WiFi is set and at least one MQTT slot can run (preset + custom host if needed). */
+22 -1
View File
@@ -746,11 +746,32 @@ void WebConfigServer::handleConfigPost(AsyncWebServerRequest* req) {
// top-level `password` command, so it persists exactly as the CLI does.
int pos = admin_pwd ? snprintf(e.cmd, sizeof(e.cmd), "password ")
: snprintf(e.cmd, sizeof(e.cmd), "set %s ", key);
for (const char* p = val; *p && pos < (int)sizeof(e.cmd) - 1; p++) {
bool overflow = false;
for (const char* p = val; *p; p++) {
if (*p == '\r' || *p == '\n') continue;
if (pos >= (int)sizeof(e.cmd) - 1) { overflow = true; break; }
e.cmd[pos++] = *p;
}
e.cmd[pos] = 0;
// A value that doesn't fit used to be truncated here and applied anyway.
// For length-checked keys the CLI would reject the remainder, but a key
// whose grammar stays valid when clipped (mqttN.filter: "advert,2" cut to
// "advert") would silently persist a *different* setting and still answer
// OK. Refuse the batch instead — the caller can shorten and retry.
if (overflow) {
// Name the key, like the "bad key" rejection above: a 20-field batch is
// rejected whole, so without it the operator has nothing to correct.
char safe_key[33];
strncpy(safe_key, key, sizeof(safe_key) - 1);
safe_key[sizeof(safe_key) - 1] = 0;
StaticJsonDocument<128> ed;
ed["error"] = "value too long";
ed["key"] = safe_key;
String out;
serializeJson(ed, out);
req->send(400, "application/json", out);
return;
}
count++;
}
// Phase 2: the count is now known, so the remaining NoChanges/Accept arms