Add WebConfig CLI and standalone WiFi controls

This commit is contained in:
mikecarper committed 2026-07-29 13:13:37 -07:00
1 parent 0dcb4b7d19
commit a6ace6076c
24 files changed
+2698 -1224

No files matched your search

+108
View File
@@ -1,10 +1,118 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
namespace mesh {
namespace cli {
enum class StandaloneWiFiKey : uint8_t {
None = 0,
SSID,
Password,
PowerSave,
Status,
CLI,
};
enum class NoArgCommandMatch : uint8_t {
NoMatch = 0,
Exact,
HasArguments,
};
inline StandaloneWiFiKey classifyStandaloneWiFiGet(const char* config) {
if (config == nullptr) return StandaloneWiFiKey::None;
if (strcmp(config, "wifi.ssid") == 0) return StandaloneWiFiKey::SSID;
if (strcmp(config, "wifi.status") == 0) return StandaloneWiFiKey::Status;
if (strcmp(config, "wifi.powersave") == 0) {
return StandaloneWiFiKey::PowerSave;
}
if (strcmp(config, "wifi.cli") == 0) return StandaloneWiFiKey::CLI;
return StandaloneWiFiKey::None;
}
inline StandaloneWiFiKey classifyStandaloneWiFiSet(const char* config,
const char** value) {
if (value != nullptr) *value = nullptr;
if (config == nullptr) return StandaloneWiFiKey::None;
struct Entry {
const char* name;
StandaloneWiFiKey key;
};
const Entry entries[] = {
{"wifi.ssid", StandaloneWiFiKey::SSID},
{"wifi.pwd", StandaloneWiFiKey::Password},
{"wifi.powersave", StandaloneWiFiKey::PowerSave},
{"wifi.cli", StandaloneWiFiKey::CLI},
};
for (const Entry& entry : entries) {
const size_t len = strlen(entry.name);
if (strncmp(config, entry.name, len) != 0) continue;
if (config[len] != 0 && config[len] != ' ') continue;
if (value != nullptr) {
*value = config[len] == ' ' ? config + len + 1 : config + len;
}
return entry.key;
}
return StandaloneWiFiKey::None;
}
inline bool standaloneWiFiSSIDValid(const char* value) {
if (value == nullptr) return false;
const size_t len = strlen(value);
return len >= 1 && len <= 31;
}
inline bool standaloneWiFiPasswordValid(const char* value) {
return value != nullptr && strlen(value) <= 63;
}
inline bool parseStandaloneWiFiPowerSave(const char* value,
uint8_t& power_save) {
if (value == nullptr) return false;
if (strcmp(value, "min") == 0) {
power_save = 0;
return true;
}
if (strcmp(value, "none") == 0) {
power_save = 1;
return true;
}
if (strcmp(value, "max") == 0) {
power_save = 2;
return true;
}
return false;
}
inline NoArgCommandMatch matchNoArgCommand(const char* command,
const char* expected) {
if (command == nullptr || expected == nullptr) {
return NoArgCommandMatch::NoMatch;
}
const size_t len = strlen(expected);
if (strncmp(command, expected, len) != 0) {
return NoArgCommandMatch::NoMatch;
}
if (command[len] == 0) return NoArgCommandMatch::Exact;
if (command[len] != ' ') return NoArgCommandMatch::NoMatch;
const char* rest = command + len;
while (*rest == ' ') rest++;
return *rest == 0 ? NoArgCommandMatch::Exact
: NoArgCommandMatch::HasArguments;
}
inline void formatUnknownSetting(char* reply, size_t capacity,
const char* setting) {
if (reply == nullptr || capacity == 0) return;
snprintf(reply, capacity, "Error: unknown setting: %s",
setting != nullptr ? setting : "");
}
// Mobile keyboards commonly capitalize the first word entered into a CLI
// field. Command verbs are identifiers, so normalize only that first token and
// leave every argument (names, passwords, keys, and other values) untouched.
+73 -10
View File
@@ -3016,9 +3016,49 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
}
return;
}
#endif
#if defined(ESP_PLATFORM) && defined(ADMIN_PASSWORD) && !defined(WEBCONFIG_DISABLED)
const char* cli_value = nullptr;
if (mesh::cli::classifyStandaloneWiFiSet(config, &cli_value) ==
mesh::cli::StandaloneWiFiKey::CLI) {
if (!_callbacks->setWiFiCLI(cli_value, reply)) {
strcpy(reply, "Error: WiFi CLI unavailable on this build");
}
return;
}
#endif
// Observer/MQTT/WiFi/timezone/alert/SNMP commands live in CommonCLI_Observer.cpp.
if (handleObserverSetCmd(sender_timestamp, config, reply)) return;
#if defined(ESP_PLATFORM) && defined(ADMIN_PASSWORD) && \
!defined(WEBCONFIG_DISABLED) && !defined(WITH_MQTT_BRIDGE)
const char* wifi_value = nullptr;
const mesh::cli::StandaloneWiFiKey wifi_key =
mesh::cli::classifyStandaloneWiFiSet(config, &wifi_value);
bool wifi_supported = true;
switch (wifi_key) {
case mesh::cli::StandaloneWiFiKey::SSID:
wifi_supported = _callbacks->setWiFiSSID(wifi_value, reply);
break;
case mesh::cli::StandaloneWiFiKey::Password:
wifi_supported = _callbacks->setWiFiPassword(wifi_value, reply);
break;
case mesh::cli::StandaloneWiFiKey::PowerSave:
wifi_supported = _callbacks->setWiFiPowerSave(wifi_value, reply);
break;
case mesh::cli::StandaloneWiFiKey::CLI:
wifi_supported = _callbacks->setWiFiCLI(wifi_value, reply);
break;
default:
wifi_supported = false;
break;
}
if (wifi_key != mesh::cli::StandaloneWiFiKey::None) {
if (!wifi_supported) {
strcpy(reply, "Error: standalone WiFi settings unavailable on this build");
}
return;
}
#endif
#if defined(PORTABLE_ESP32_RADIO_CLI)
// Portable WiFi-heavy images keep the controls needed to configure and
// diagnose their radio. The full parser remains available in the FULL image.
@@ -4063,22 +4103,45 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
}
return;
}
#endif
#if defined(ESP_PLATFORM) && defined(ADMIN_PASSWORD) && !defined(WEBCONFIG_DISABLED)
if (mesh::cli::classifyStandaloneWiFiGet(config) ==
mesh::cli::StandaloneWiFiKey::CLI) {
if (!_callbacks->getWiFiCLI(reply)) {
strcpy(reply, "Error: WiFi CLI unavailable on this build");
}
return;
}
#endif
// Observer/MQTT/WiFi/timezone/alert/SNMP commands live in CommonCLI_Observer.cpp.
if (handleObserverGetCmd(sender_timestamp, config, reply)) return;
#if defined(ESP_PLATFORM) && defined(ADMIN_PASSWORD) && !defined(WEBCONFIG_DISABLED)
// Non-MQTT FULL repeater/room-server builds keep WiFi only for WebConfig.
// Their credentials live in the standalone WebConfig NVS namespace rather
// than MQTTPrefs, so expose the useful read-only status through the role.
if (strcmp(config, "wifi.ssid") == 0) {
if (!_callbacks->getWiFiSSID(reply)) {
strcpy(reply, "Error: WiFi SSID unavailable on this build");
}
return;
// than MQTTPrefs, so expose the WiFi configuration through the role.
const mesh::cli::StandaloneWiFiKey wifi_key =
mesh::cli::classifyStandaloneWiFiGet(config);
bool wifi_supported = true;
switch (wifi_key) {
case mesh::cli::StandaloneWiFiKey::SSID:
wifi_supported = _callbacks->getWiFiSSID(reply);
break;
case mesh::cli::StandaloneWiFiKey::Status:
wifi_supported = _callbacks->getWiFiStatus(reply);
break;
case mesh::cli::StandaloneWiFiKey::PowerSave:
wifi_supported = _callbacks->getWiFiPowerSave(reply);
break;
case mesh::cli::StandaloneWiFiKey::CLI:
wifi_supported = _callbacks->getWiFiCLI(reply);
break;
default:
wifi_supported = false;
break;
}
if (strcmp(config, "wifi.status") == 0) {
if (!_callbacks->getWiFiStatus(reply)) {
strcpy(reply, "Error: WiFi status unavailable on this build");
if (wifi_key != mesh::cli::StandaloneWiFiKey::None) {
if (!wifi_supported) {
strcpy(reply, "Error: WiFi information unavailable on this build");
}
return;
}
@@ -4434,7 +4497,7 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
sprintf(reply, "> %d", (uint8_t)_prefs->reboot_interval);
}
} else {
sprintf(reply, "??: %s", config);
mesh::cli::formatUnknownSetting(reply, 160, config);
}
#endif
}
+28
View File
@@ -402,6 +402,34 @@ public:
(void)reply;
return false;
};
virtual bool getWiFiPowerSave(char* reply) const {
(void)reply;
return false;
};
virtual bool getWiFiCLI(char* reply) const {
(void)reply;
return false;
};
virtual bool setWiFiSSID(const char* value, char* reply) {
(void)value;
(void)reply;
return false;
};
virtual bool setWiFiPassword(const char* value, char* reply) {
(void)value;
(void)reply;
return false;
};
virtual bool setWiFiPowerSave(const char* value, char* reply) {
(void)value;
(void)reply;
return false;
};
virtual bool setWiFiCLI(const char* value, char* reply) {
(void)value;
(void)reply;
return false;
};
virtual int getQueueSize() {
return 0; // no op by default
+20 -7
View File
@@ -12,6 +12,7 @@
#include <Arduino.h>
#include "CommonCLI.h"
#include "CLICommandUtils.h"
#include "TxtDataHelpers.h"
#include "AlertReporter.h" // for alertReporterBannedChannelMatch[Hex]()
#include "MQTTObserverValidation.h" // pure input validators (host-testable)
@@ -21,6 +22,10 @@
#include <WiFiClientSecure.h>
#include <esp_wifi.h>
#endif
#if defined(ESP32_PLATFORM) && defined(ENABLE_OTA) && \
(defined(WIFI_OTA_SEEDER) || defined(WIFI_SSID))
#include "esp32/WiFiOtaSeeder.h"
#endif
#ifdef WITH_MQTT_BRIDGE
#include "bridges/MQTTBridge.h"
#include "MQTTConnectionPolicy.h" // classifySlotActivation() -- "will this slot connect here?"
@@ -321,14 +326,18 @@ bool CommonCLI::handleObserverSetCmd(uint32_t sender_timestamp, const char* conf
strcpy(reply, "OK - saved");
#endif
}
} else if (memcmp(config, "wifi.ssid ", 10) == 0) {
if (valueTooLong(&config[10], sizeof(_mqtt_prefs.wifi_ssid), reply, "wifi.ssid")) return true;
StrHelper::strncpy(_mqtt_prefs.wifi_ssid, &config[10], sizeof(_mqtt_prefs.wifi_ssid));
} else if (memcmp(config, "wifi.ssid ", 10) == 0
|| strcmp(config, "wifi.ssid") == 0) {
const char* value = config[9] == 0 ? config + 9 : config + 10;
if (valueTooLong(value, sizeof(_mqtt_prefs.wifi_ssid), reply, "wifi.ssid")) return true;
StrHelper::strncpy(_mqtt_prefs.wifi_ssid, value, sizeof(_mqtt_prefs.wifi_ssid));
savePrefs();
strcpy(reply, "OK");
} else if (memcmp(config, "wifi.pwd ", 9) == 0) {
if (valueTooLong(&config[9], sizeof(_mqtt_prefs.wifi_password), reply, "wifi.pwd")) return true;
StrHelper::strncpy(_mqtt_prefs.wifi_password, &config[9], sizeof(_mqtt_prefs.wifi_password));
} else if (memcmp(config, "wifi.pwd ", 9) == 0
|| strcmp(config, "wifi.pwd") == 0) {
const char* value = config[8] == 0 ? config + 8 : config + 9;
if (valueTooLong(value, sizeof(_mqtt_prefs.wifi_password), reply, "wifi.pwd")) return true;
StrHelper::strncpy(_mqtt_prefs.wifi_password, value, sizeof(_mqtt_prefs.wifi_password));
savePrefs();
strcpy(reply, "OK");
} else if (memcmp(config, "wifi.powersave ", 15) == 0) {
@@ -881,7 +890,7 @@ bool CommonCLI::handleObserverGetCmd(uint32_t sender_timestamp, const char* conf
} else if (memcmp(subcmd, "diag", 4) == 0) {
MQTTBridge::formatSlotDiagReply(reply, 160, slot);
} else {
sprintf(reply, "??: %s", config);
mesh::cli::formatUnknownSetting(reply, 160, config);
}
} else if (memcmp(config, "wifi.ssid", 9) == 0) {
sprintf(reply, "> %s", _mqtt_prefs.wifi_ssid);
@@ -948,6 +957,10 @@ bool CommonCLI::handleObserverGetCmd(uint32_t sender_timestamp, const char* conf
sprintf(reply, "> %s (code: %d)", status_str, status);
#endif
}
#if defined(ESP32_PLATFORM) && defined(ENABLE_OTA) && \
(defined(WIFI_OTA_SEEDER) || defined(WIFI_SSID))
mesh::ota::WiFiOtaSeeder::appendStatus(reply, 160);
#endif
} else if (memcmp(config, "wifi.powersave", 14) == 0) {
uint8_t ps = _mqtt_prefs.wifi_power_save;
const char* ps_name = (ps == 1) ? "none" : (ps == 2) ? "max" : "min";
+15
View File
@@ -96,3 +96,18 @@ static inline bool wcIsValidReqId(const char* reqid) {
}
return true;
}
// The browser terminal submits exactly one command through the existing
// 160-byte CLI buffer. Reject blank, oversized, or multiline input so a JSON
// request cannot smuggle a second command into the dispatcher.
static inline bool wcIsValidCliCommand(const char* command) {
if (command == NULL) return false;
const size_t len = strnlen(command, 161);
if (len == 0 || len > 159) return false;
bool has_text = false;
for (size_t i = 0; i < len; i++) {
if (command[i] == '\r' || command[i] == '\n') return false;
if (command[i] != ' ' && command[i] != '\t') has_text = true;
}
return has_text;
}
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
namespace WiFiOtaSeederStatus {
inline bool append(char* reply, size_t capacity, bool listening,
bool client_attached, uint16_t port) {
if (!reply || capacity == 0 || !listening) return false;
const size_t used = strnlen(reply, capacity);
if (used >= capacity) return false;
const int written = snprintf(
reply + used, capacity - used, ", OTA TCP %u: %s",
static_cast<unsigned>(port),
client_attached ? "client connected" : "listening");
return written >= 0 && static_cast<size_t>(written) < capacity - used;
}
} // namespace WiFiOtaSeederStatus
File diff suppressed because it is too large. Load diff
+363 -4
View File
@@ -12,6 +12,11 @@
#include <esp_system.h>
#include <esp_heap_caps.h>
#if defined(ESP32_PLATFORM) && defined(ENABLE_OTA) && \
(defined(WIFI_OTA_SEEDER) || defined(WIFI_SSID))
#include <helpers/esp32/WiFiOtaSeeder.h>
#endif
#ifdef WITH_MQTT_BRIDGE
#include <helpers/MQTTPrefs.h>
#include <helpers/MQTTPresets.h>
@@ -19,6 +24,7 @@
#endif
#include "WebConfigHtml.h"
#include "helpers/CLICommandUtils.h"
#include "helpers/WebConfigKeys.h"
// Placeholder sent instead of stored secrets; POSTs carrying it are dropped
@@ -50,6 +56,16 @@ static bool fixedTimeEquals(const char* a, const char* b, size_t max_len) {
return diff == 0;
}
static void appendOtaSeederStatus(char* reply, size_t reply_len) {
#if defined(ESP32_PLATFORM) && defined(ENABLE_OTA) && \
(defined(WIFI_OTA_SEEDER) || defined(WIFI_SSID))
mesh::ota::WiFiOtaSeeder::appendStatus(reply, reply_len);
#else
(void)reply;
(void)reply_len;
#endif
}
// RAII lock; tolerates a null mutex (allocation failure) by not locking.
struct WCLock {
SemaphoreHandle_t h;
@@ -68,6 +84,7 @@ WebConfigServer::WebConfigServer(Callbacks* callbacks, void* mqtt_prefs, bool ow
: _cb(callbacks), _mqtt_prefs(mqtt_prefs), _owns_wifi(owns_wifi), _pub_key(pub_key),
_fw_ver(fw_ver), _role(role), _board_name(board_name) {
_mux = xSemaphoreCreateMutex();
_cli_enabled = loadCliEnabled(true);
#ifdef WITH_MQTT_BRIDGE
MQTTPrefs* obs = static_cast<MQTTPrefs*>(_mqtt_prefs);
@@ -112,6 +129,22 @@ bool WebConfigServer::saveEnabled(bool enabled) {
return written == sizeof(uint8_t);
}
bool WebConfigServer::loadCliEnabled(bool default_value) {
Preferences nvs;
if (!nvs.begin("mesh-webui", true)) return default_value;
bool enabled = nvs.getBool("cli", default_value);
nvs.end();
return enabled;
}
bool WebConfigServer::saveCliEnabled(bool enabled) {
Preferences nvs;
if (!nvs.begin("mesh-webui", false)) return false;
size_t written = nvs.putBool("cli", enabled);
nvs.end();
return written == sizeof(uint8_t);
}
bool WebConfigServer::loadStandaloneWiFi(char* ssid, size_t ssid_len,
char* password, size_t password_len,
uint8_t* power_save) {
@@ -124,14 +157,16 @@ bool WebConfigServer::loadStandaloneWiFi(char* ssid, size_t ssid_len,
String stored_password = nvs.getString("password", "");
uint8_t stored_ps = nvs.getUChar("powersave", 1);
nvs.end();
if (stored_ssid.length() == 0 || stored_ssid.length() >= ssid_len
|| stored_password.length() >= password_len) return false;
if (stored_ssid.length() >= ssid_len
|| stored_password.length() >= password_len) {
return false;
}
strncpy(ssid, stored_ssid.c_str(), ssid_len - 1);
ssid[ssid_len - 1] = 0;
strncpy(password, stored_password.c_str(), password_len - 1);
password[password_len - 1] = 0;
if (power_save) *power_save = stored_ps <= 2 ? stored_ps : 1;
return true;
return stored_ssid.length() != 0;
}
bool WebConfigServer::saveStandaloneWiFi(const char* ssid, const char* password,
@@ -151,6 +186,113 @@ bool WebConfigServer::saveStandaloneWiFi(const char* ssid, const char* password,
return ok;
}
bool WebConfigServer::setStandaloneWiFiSSID(const char* value, char* reply,
size_t reply_len) {
if (!reply || reply_len == 0) return false;
if (!mesh::cli::standaloneWiFiSSIDValid(value)) {
snprintf(reply, reply_len, "Error: WiFi SSID must be 1-31 characters");
return false;
}
Preferences nvs;
if (!nvs.begin("mesh-wifi", false)) {
snprintf(reply, reply_len, "Error: failed to open WiFi settings");
return false;
}
const bool ok = nvs.putString("ssid", value) == strlen(value);
nvs.end();
snprintf(reply, reply_len, ok ? "OK - WiFi SSID saved"
: "Error: failed to save WiFi SSID");
return ok;
}
bool WebConfigServer::setStandaloneWiFiPassword(const char* value, char* reply,
size_t reply_len) {
if (!reply || reply_len == 0) return false;
if (!mesh::cli::standaloneWiFiPasswordValid(value)) {
snprintf(reply, reply_len,
"Error: WiFi password must be at most 63 characters");
return false;
}
Preferences nvs;
if (!nvs.begin("mesh-wifi", false)) {
snprintf(reply, reply_len, "Error: failed to open WiFi settings");
return false;
}
nvs.putString("password", value);
const bool ok = nvs.getString("password", "\x01") == value;
nvs.end();
snprintf(reply, reply_len, ok ? "OK - WiFi password saved"
: "Error: failed to save WiFi password");
return ok;
}
bool WebConfigServer::setStandaloneWiFiPowerSave(const char* value, char* reply,
size_t reply_len) {
if (!reply || reply_len == 0) return false;
uint8_t power_save = 1;
if (!mesh::cli::parseStandaloneWiFiPowerSave(value, power_save)) {
snprintf(reply, reply_len, "Error: power save must be none, min, or max");
return false;
}
Preferences nvs;
if (!nvs.begin("mesh-wifi", false)) {
snprintf(reply, reply_len, "Error: failed to open WiFi settings");
return false;
}
const bool ok =
nvs.putUChar("powersave", power_save) == sizeof(uint8_t);
nvs.end();
if (!ok) {
snprintf(reply, reply_len, "Error: failed to save WiFi power save");
return false;
}
esp_err_t apply_result = ESP_OK;
if (WiFi.getMode() != WIFI_OFF) {
const wifi_ps_type_t ps_mode =
power_save == 1 ? WIFI_PS_NONE
: power_save == 2 ? WIFI_PS_MAX_MODEM
: WIFI_PS_MIN_MODEM;
apply_result = esp_wifi_set_ps(ps_mode);
}
if (apply_result == ESP_OK) {
snprintf(reply, reply_len, "OK - WiFi power save set to %s", value);
} else {
snprintf(reply, reply_len,
"OK - saved; WiFi power save applies on next connection");
}
return true;
}
bool WebConfigServer::setWiFiCliEnabled(const char* value, char* reply,
size_t reply_len) {
if (!reply || reply_len == 0) return false;
if (!value || (strcmp(value, "on") != 0 && strcmp(value, "off") != 0)) {
snprintf(reply, reply_len, "Error: use set wifi.cli on|off");
return false;
}
const bool enabled = strcmp(value, "on") == 0;
if (!saveCliEnabled(enabled)) {
snprintf(reply, reply_len, "Error: failed to save WiFi CLI setting");
return false;
}
WebConfigServer* active = _active;
if (active) active->_cli_enabled = enabled;
snprintf(reply, reply_len,
enabled ? "OK - WiFi CLI on; active with WiFi client"
: "OK - WiFi CLI off");
return true;
}
bool WebConfigServer::reloadStandaloneWiFi() {
return loadStandaloneWiFi(
_wifi_ssid, sizeof(_wifi_ssid),
_wifi_password, sizeof(_wifi_password), &_wifi_power_save);
}
bool WebConfigServer::formatWiFiSSID(char* reply, size_t reply_len) {
if (!reply || reply_len == 0) return false;
@@ -169,6 +311,46 @@ bool WebConfigServer::formatWiFiSSID(char* reply, size_t reply_len) {
return true;
}
bool WebConfigServer::formatWiFiPowerSave(char* reply, size_t reply_len) {
if (!reply || reply_len == 0) return false;
uint8_t power_save = 1;
if (_active) {
power_save = _active->_wifi_power_save;
} else {
char ssid[32] = "";
char password[64] = "";
loadStandaloneWiFi(
ssid, sizeof(ssid), password, sizeof(password), &power_save);
}
const char* name = "none";
if (power_save == 0) {
name = "min";
} else if (power_save == 2) {
name = "max";
}
snprintf(reply, reply_len, "> %s", name);
return true;
}
bool WebConfigServer::formatWiFiCliStatus(char* reply, size_t reply_len) {
if (!reply || reply_len == 0) return false;
WebConfigServer* active = _active;
const bool enabled = active ? active->_cli_enabled : loadCliEnabled(true);
const bool available = active && active->_cb->supportsCliTerminal();
const bool running = enabled && available && active->_mode == MODE_LAN
&& WiFi.status() == WL_CONNECTED;
if (!enabled) {
snprintf(reply, reply_len, "> off");
} else if (running) {
snprintf(reply, reply_len, "> on, active");
} else {
snprintf(reply, reply_len, "> on, waiting for WiFi client");
}
return true;
}
bool WebConfigServer::formatWiFiStatus(char* reply, size_t reply_len) {
if (!reply || reply_len == 0) return false;
@@ -189,23 +371,27 @@ bool WebConfigServer::formatWiFiStatus(char* reply, size_t reply_len) {
char ip[16] = "";
getSetupInfo(ap_ssid, sizeof(ap_ssid), ip, sizeof(ip));
snprintf(reply, reply_len, "> setup AP, SSID: %s, IP: %s", ap_ssid, ip);
appendOtaSeederStatus(reply, reply_len);
return true;
}
if (active && active->_mode == MODE_CONNECTING) {
snprintf(reply, reply_len, "> connecting, SSID: %s",
configured ? ssid : "(not configured)");
appendOtaSeederStatus(reply, reply_len);
return true;
}
const wl_status_t status = WiFi.status();
if (status == WL_CONNECTED) {
snprintf(reply, reply_len, "> connected, SSID: %s, IP: %s, RSSI: %d dBm",
configured ? ssid : WiFi.SSID().c_str(),
WiFi.SSID().c_str(),
WiFi.localIP().toString().c_str(), WiFi.RSSI());
appendOtaSeederStatus(reply, reply_len);
return true;
}
if (!configured) {
strcpy(reply, "> not configured; run 'start webconfig'");
appendOtaSeederStatus(reply, reply_len);
return true;
}
@@ -228,6 +414,7 @@ bool WebConfigServer::formatWiFiStatus(char* reply, size_t reply_len) {
}
break;
}
appendOtaSeederStatus(reply, reply_len);
return true;
}
@@ -419,6 +606,10 @@ void WebConfigServer::finalizeTeardown() {
_batch_state = BATCH_IDLE;
_batch_next = 0;
_batch_reboot_armed = false;
_cli_state = CLI_IDLE;
_cli_reqid[0] = 0;
_cli_command[0] = 0;
_cli_reply[0] = 0;
_session_token[0] = 0;
_stats_json[0] = 0;
if (_cb) _cb->onWebConfigStopped();
@@ -464,6 +655,7 @@ void WebConfigServer::tick(uint32_t now) {
if (_dns) _dns->processNextRequest();
if (_cli_state == CLI_PENDING) drainCliCommand();
if (_batch_state == BATCH_PENDING) drainBatch(now);
if (WebConfigBatch::rebootDue(_reboot_at, now)) {
@@ -493,6 +685,26 @@ void WebConfigServer::tick(uint32_t now) {
}
}
void WebConfigServer::drainCliCommand() {
char command[160];
{
WCLock lock(_mux);
if (_cli_state != CLI_PENDING) return;
strncpy(command, _cli_command, sizeof(command) - 1);
command[sizeof(command) - 1] = 0;
}
char reply[160] = "";
_cb->execAdminCommand(command, reply);
if (reply[0] == 0) strcpy(reply, "(no reply)");
WCLock lock(_mux);
if (_cli_state != CLI_PENDING) return;
strncpy(_cli_reply, reply, sizeof(_cli_reply) - 1);
_cli_reply[sizeof(_cli_reply) - 1] = 0;
_cli_state = CLI_DONE;
}
void WebConfigServer::drainBatch(uint32_t now) {
// One command per call, spaced out. Each `set` persists prefs with a flash
// write, and flash writes stall the WiFi task (flash cache off); running a
@@ -681,6 +893,13 @@ void WebConfigServer::registerRoutes() {
dispatchRequest(r, &WebConfigServer::handleConfigPost);
},
NULL, collectBody);
_server->on("/api/cli/result", HTTP_GET, [](AsyncWebServerRequest* r) {
dispatchRequest(r, &WebConfigServer::handleCliResult);
});
_server->on("/api/cli", HTTP_POST, [](AsyncWebServerRequest* r) {
dispatchRequest(r, &WebConfigServer::handleCliPost);
},
NULL, collectBody);
_server->on("/api/stats", HTTP_GET, [](AsyncWebServerRequest* r) {
dispatchRequest(r, &WebConfigServer::handleStats);
});
@@ -788,6 +1007,8 @@ void WebConfigServer::handleStatus(AsyncWebServerRequest* req) {
doc["active_slots"] = 0;
#endif
doc["mqtt"] = has_mqtt;
doc["cli"] = _cli_enabled && _mode == MODE_LAN
&& WiFi.status() == WL_CONNECTED && _cb->supportsCliTerminal();
doc["capabilities"] = node.capabilities;
AsyncResponseStream* res = req->beginResponseStream("application/json");
@@ -961,6 +1182,11 @@ void WebConfigServer::handleConfigPost(AsyncWebServerRequest* req) {
JsonObject set = doc["set"];
WCLock lock(_mux);
if (_cli_state == CLI_PENDING) {
req->send(409, "application/json",
"{\"error\":\"CLI command is still running\"}");
return;
}
const WebConfigBatch::State bstate = toSpecState(_batch_state);
const bool reqid_matches = strcmp(reqid, _batch_reqid) == 0;
const WebConfigBatch::PostOutcome pre =
@@ -1135,6 +1361,139 @@ void WebConfigServer::handleConfigResult(AsyncWebServerRequest* req) {
req->send(res);
}
void WebConfigServer::handleCliPost(AsyncWebServerRequest* req) {
if (_mode != MODE_LAN) {
req->send(403, "application/json",
"{\"error\":\"terminal requires LAN mode\"}");
return;
}
if (!_cb->supportsCliTerminal()) {
req->send(404, "application/json",
"{\"error\":\"terminal unavailable on this role\"}");
return;
}
if (!_cli_enabled) {
req->send(403, "application/json",
"{\"error\":\"terminal disabled; set wifi.cli on\"}");
return;
}
if (!checkAuth(req)) {
req->send(401, "application/json", "{\"error\":\"auth\"}");
return;
}
if (req->contentLength() > 512) {
req->send(413, "application/json", "{\"error\":\"body too large\"}");
return;
}
const char* body = (const char*)req->_tempObject;
DynamicJsonDocument doc(512);
if (!body || deserializeJson(doc, body) != DeserializationError::Ok) {
req->send(400, "application/json", "{\"error\":\"bad json\"}");
return;
}
const char* reqid = doc["reqid"] | "";
const char* command = doc["command"] | "";
if (!wcIsValidReqId(reqid)) {
req->send(400, "application/json", "{\"error\":\"bad reqid\"}");
return;
}
if (!wcIsValidCliCommand(command)) {
req->send(400, "application/json",
"{\"error\":\"command must be one nonblank line up to 159 bytes\"}");
return;
}
WCLock lock(_mux);
const bool same_request = strcmp(reqid, _cli_reqid) == 0;
if (_cli_state == CLI_PENDING || same_request) {
if (!same_request) {
StaticJsonDocument<96> busy;
busy["error"] = "busy";
busy["reqid"] = (const char*)_cli_reqid;
String out;
serializeJson(busy, out);
req->send(409, "application/json", out);
return;
}
StaticJsonDocument<96> replay;
replay["state"] = _cli_state == CLI_DONE ? "done" : "pending";
replay["reqid"] = (const char*)_cli_reqid;
String out;
serializeJson(replay, out);
req->send(202, "application/json", out);
return;
}
if (_batch_state == BATCH_PENDING) {
req->send(409, "application/json",
"{\"error\":\"configuration change is still running\"}");
return;
}
strncpy(_cli_reqid, reqid, sizeof(_cli_reqid) - 1);
_cli_reqid[sizeof(_cli_reqid) - 1] = 0;
strncpy(_cli_command, command, sizeof(_cli_command) - 1);
_cli_command[sizeof(_cli_command) - 1] = 0;
_cli_reply[0] = 0;
_cli_state = CLI_PENDING;
StaticJsonDocument<96> ack;
ack["state"] = "pending";
ack["reqid"] = (const char*)_cli_reqid;
String out;
serializeJson(ack, out);
req->send(202, "application/json", out);
}
void WebConfigServer::handleCliResult(AsyncWebServerRequest* req) {
if (_mode != MODE_LAN) {
req->send(403, "application/json",
"{\"error\":\"terminal requires LAN mode\"}");
return;
}
if (!_cb->supportsCliTerminal()) {
req->send(404, "application/json",
"{\"error\":\"terminal unavailable on this role\"}");
return;
}
if (!checkAuth(req)) {
req->send(401, "application/json", "{\"error\":\"auth\"}");
return;
}
if (!req->hasParam("reqid")) {
req->send(400, "application/json", "{\"error\":\"bad reqid\"}");
return;
}
String requested_reqid = req->getParam("reqid")->value();
if (!wcIsValidReqId(requested_reqid.c_str())) {
req->send(400, "application/json", "{\"error\":\"bad reqid\"}");
return;
}
WCLock lock(_mux);
if (_cli_state == CLI_IDLE) {
StaticJsonDocument<64> idle;
idle["state"] = "idle";
idle["reqid"] = requested_reqid;
String out;
serializeJson(idle, out);
req->send(200, "application/json", out);
return;
}
if (strcmp(requested_reqid.c_str(), _cli_reqid) != 0) {
req->send(404, "application/json", "{\"error\":\"unknown request\"}");
return;
}
DynamicJsonDocument doc(512);
doc["state"] = _cli_state == CLI_DONE ? "done" : "pending";
doc["reqid"] = (const char*)_cli_reqid;
if (_cli_state == CLI_DONE) doc["reply"] = (const char*)_cli_reply;
AsyncResponseStream* res = req->beginResponseStream("application/json");
serializeJson(doc, *res);
req->send(res);
}
void WebConfigServer::handleStats(AsyncWebServerRequest* req) {
if (_mode == MODE_OFF) { req->send(503); return; }
if (!checkAuth(req)) { req->send(401, "application/json", "{\"error\":\"auth\"}"); return; }
+34 -3
View File
@@ -12,9 +12,9 @@
//
// Concurrency model: AsyncWebServer handlers run on the async_tcp task and
// must never touch the CLI, prefs persistence, or the radio. Config writes
// are marshaled into a single-slot command batch that tick() - called from
// MyMesh::loop() on the Arduino loop task - drains through the existing CLI
// `set` handlers. Prefs-struct reads and batch state are guarded by _mux.
// and browser-terminal commands are marshaled to tick() - called from
// MyMesh::loop() on the Arduino loop task - and run through the existing CLI
// handlers there. Prefs-struct reads and request state are guarded by _mux.
//
// The master switch and standalone WiFi credentials use independent NVS
// namespaces, so role-specific prefs-file layouts remain untouched.
@@ -93,6 +93,12 @@ public:
virtual void getNodeSnapshot(NodeSnapshot& snapshot) = 0;
// Run one CLI command. Called from tick() only (loop task); reply is 160 bytes.
virtual void execCommand(char* cmd, char* reply) = 0;
// Browser terminal commands use remote-admin semantics so serial-only
// secrets and destructive maintenance commands remain unavailable.
virtual bool supportsCliTerminal() const { return false; }
virtual void execAdminCommand(char* cmd, char* reply) {
execCommand(cmd, reply);
}
virtual void rebootNow() = 0;
// Bracket a config batch so bridge restarts triggered by individual
// `set` handlers can be coalesced into one.
@@ -126,13 +132,25 @@ public:
// namespaces. This avoids changing NodePrefs or MQTTPrefs file layouts.
static bool loadEnabled(bool default_value = false);
static bool saveEnabled(bool enabled);
static bool loadCliEnabled(bool default_value = true);
static bool saveCliEnabled(bool enabled);
static bool loadStandaloneWiFi(char* ssid, size_t ssid_len,
char* password, size_t password_len,
uint8_t* power_save = NULL);
static bool saveStandaloneWiFi(const char* ssid, const char* password,
uint8_t power_save);
static bool setStandaloneWiFiSSID(const char* value, char* reply,
size_t reply_len);
static bool setStandaloneWiFiPassword(const char* value, char* reply,
size_t reply_len);
static bool setStandaloneWiFiPowerSave(const char* value, char* reply,
size_t reply_len);
static bool setWiFiCliEnabled(const char* value, char* reply,
size_t reply_len);
static bool formatWiFiSSID(char* reply, size_t reply_len);
static bool formatWiFiStatus(char* reply, size_t reply_len);
static bool formatWiFiPowerSave(char* reply, size_t reply_len);
static bool formatWiFiCliStatus(char* reply, size_t reply_len);
// UI tasks use an otherwise-unused multi-click gesture without reaching into
// MyMesh directly. The mesh loop consumes the request and performs the NVS /
@@ -143,6 +161,7 @@ public:
bool startSetupMode(char reply[]); // open SoftAP + DNS captive portal
bool startLanMode(char reply[]); // bind to existing STA connection
bool startAutoMode(char reply[]); // use saved WiFi, or setup AP when absent
bool reloadStandaloneWiFi();
void requestStop(); // stop listening and detach this session
void tick(uint32_t now); // call every loop iteration
@@ -155,6 +174,7 @@ private:
static const size_t MAX_BODY = 4096;
static const uint32_t STOP_WARN_MS = WebConfigBatch::kStopWarnMs;
enum BatchState : uint8_t { BATCH_IDLE = 0, BATCH_PENDING, BATCH_DONE };
enum CliState : uint8_t { CLI_IDLE = 0, CLI_PENDING, CLI_DONE };
static WebConfigBatch::State toSpecState(BatchState state) {
switch (state) {
case BATCH_PENDING: return WebConfigBatch::State::Pending;
@@ -187,6 +207,7 @@ private:
char _wifi_ssid[32] = {0};
char _wifi_password[64] = {0};
uint8_t _wifi_power_save = 1;
bool _cli_enabled = true;
char _ap_ssid[33] = {0};
// Currently attached session, also used by the display's setup-info poll.
@@ -207,6 +228,13 @@ private:
bool _standalone_wifi_dirty = false;
BatchEntry _batch[MAX_BATCH];
// Browser terminal command: filled by async_tcp under _mux and executed by
// tick() on the loop task. Separate from the allowlisted config batch.
volatile CliState _cli_state = CLI_IDLE;
char _cli_reqid[24] = {0};
char _cli_command[160] = {0};
char _cli_reply[160] = {0};
// LAN-mode session (single slot; new login evicts the old session)
char _session_token[33] = {0};
uint32_t _session_last_seen = 0;
@@ -240,6 +268,7 @@ private:
void detachRoutes();
uint32_t handlerRefCount() const;
void drainBatch(uint32_t now);
void drainCliCommand();
void finalizeTeardown();
bool checkAuth(AsyncWebServerRequest* req);
static void collectBody(AsyncWebServerRequest* req, uint8_t* data, size_t len,
@@ -252,6 +281,8 @@ private:
void handleConfigGet(AsyncWebServerRequest* req);
void handleConfigPost(AsyncWebServerRequest* req);
void handleConfigResult(AsyncWebServerRequest* req);
void handleCliPost(AsyncWebServerRequest* req);
void handleCliResult(AsyncWebServerRequest* req);
void handleStats(AsyncWebServerRequest* req);
void handleScan(AsyncWebServerRequest* req);
void handlePresets(AsyncWebServerRequest* req);
+7
View File
@@ -7,6 +7,7 @@
#include <WiFi.h>
#include <helpers/WiFiOtaSeederPolicy.h>
#include <helpers/WiFiOtaSeederStatus.h>
#include <helpers/ota/FolderMotaStore.h>
#include <helpers/ota/MotaSourceSerial.h>
#include <helpers/ota/OtaContext.h>
@@ -121,6 +122,12 @@ bool WiFiOtaSeeder::isAttached() {
return tcp_folder_attached;
}
bool WiFiOtaSeeder::appendStatus(char* reply, size_t capacity) {
return WiFiOtaSeederStatus::append(
reply, capacity, listener_active, tcp_folder_attached,
OTA_SEEDER_TCP_PORT);
}
} // namespace ota
} // namespace mesh
+2
View File
@@ -3,6 +3,7 @@
#if defined(ESP32_PLATFORM) && defined(ENABLE_OTA) && \
(defined(WIFI_OTA_SEEDER) || defined(WIFI_SSID))
#include <stddef.h>
#include <stdint.h>
#ifndef OTA_SEEDER_TCP_PORT
@@ -18,6 +19,7 @@ public:
static void stop();
static bool isListening();
static bool isAttached();
static bool appendStatus(char* reply, size_t capacity);
static uint16_t port() { return OTA_SEEDER_TCP_PORT; }
};