Merge remote-tracking branch 'origin/keymindCascade' into keymindCascade
This commit is contained in:
commit
ff51126508
6 files changed
+298
-9
No files matched your search
@@ -4542,17 +4542,17 @@ void MyMesh::setTempRadioTiming(uint32_t duration_seconds) {
|
||||
}
|
||||
|
||||
bool MyMesh::applyRadioParams(float freq, float bw, uint8_t sf, uint8_t cr, uint16_t preamble, bool temporary) {
|
||||
const bool apply_rxps = _prefs.rx_powersaving_enabled && radio_driver.supportsRxPowerSaving();
|
||||
uint32_t rx_us = _prefs.rx_ps_rx_us;
|
||||
uint32_t sleep_us = _prefs.rx_ps_sleep_us;
|
||||
if (_prefs.rx_powersaving_enabled && _prefs.rx_ps_level != 0) {
|
||||
if (apply_rxps && _prefs.rx_ps_level != 0) {
|
||||
uint32_t preamble = _prefs.rx_ps_preamble
|
||||
? _prefs.rx_ps_preamble : rxPowerSavingPreambleForParams(sf, bw);
|
||||
if (!CommonCLI::calculateRxPowerSavingLevel(
|
||||
_prefs.rx_ps_level, sf, bw, preamble, &rx_us, &sleep_us)) return false;
|
||||
}
|
||||
uint32_t timings[2] = {rx_us, sleep_us};
|
||||
const uint32_t* applied_timings = _prefs.rx_powersaving_enabled
|
||||
&& radio_driver.supportsRxPowerSaving() ? timings : NULL;
|
||||
const uint32_t* applied_timings = apply_rxps ? timings : NULL;
|
||||
if (_cli.radioProfiles().applyPrimary(freq, bw, sf, cr, temporary, preamble,
|
||||
applied_timings) != mesh::RadioParamApplyResult::APPLIED) {
|
||||
MESH_DEBUG_PRINTLN("Radio schedule: radio busy or parameter apply failed");
|
||||
|
||||
@@ -2457,15 +2457,15 @@ void MyMesh::servicePendingPrimaryRadioSettings(bool tx_gap) {
|
||||
uint32_t rx_us = _prefs.rx_ps_rx_us;
|
||||
uint32_t sleep_us = _prefs.rx_ps_sleep_us;
|
||||
bool timing_ok = true;
|
||||
if (_prefs.rx_powersaving_enabled && _prefs.rx_ps_level != 0) {
|
||||
const bool apply_rxps = _prefs.rx_powersaving_enabled && radio_driver.supportsRxPowerSaving();
|
||||
if (apply_rxps && _prefs.rx_ps_level != 0) {
|
||||
uint32_t preamble = _prefs.rx_ps_preamble ? _prefs.rx_ps_preamble
|
||||
: rxPowerSavingPreambleForParams(pending_sf, pending_bw);
|
||||
timing_ok = CommonCLI::calculateRxPowerSavingLevel(
|
||||
_prefs.rx_ps_level, pending_sf, pending_bw, preamble, &rx_us, &sleep_us);
|
||||
}
|
||||
uint32_t timings[2] = {rx_us, sleep_us};
|
||||
const uint32_t* applied_timings = _prefs.rx_powersaving_enabled
|
||||
&& radio_driver.supportsRxPowerSaving() ? timings : NULL;
|
||||
const uint32_t* applied_timings = apply_rxps ? timings : NULL;
|
||||
if (timing_ok && _cli.radioProfiles().applyPrimary(
|
||||
pending_freq, pending_bw, pending_sf, pending_cr, true, pending_preamble, applied_timings) == mesh::RadioParamApplyResult::APPLIED) {
|
||||
set_radio_at = 0;
|
||||
|
||||
@@ -1142,15 +1142,15 @@ void SensorMesh::servicePendingPrimaryRadioSettings(bool tx_gap) {
|
||||
uint32_t rx_us = _prefs.rx_ps_rx_us;
|
||||
uint32_t sleep_us = _prefs.rx_ps_sleep_us;
|
||||
bool timing_ok = true;
|
||||
if (_prefs.rx_powersaving_enabled && _prefs.rx_ps_level != 0) {
|
||||
const bool apply_rxps = _prefs.rx_powersaving_enabled && radio_driver.supportsRxPowerSaving();
|
||||
if (apply_rxps && _prefs.rx_ps_level != 0) {
|
||||
uint32_t preamble = _prefs.rx_ps_preamble ? _prefs.rx_ps_preamble
|
||||
: rxPowerSavingPreambleForParams(pending_sf, pending_bw);
|
||||
timing_ok = CommonCLI::calculateRxPowerSavingLevel(
|
||||
_prefs.rx_ps_level, pending_sf, pending_bw, preamble, &rx_us, &sleep_us);
|
||||
}
|
||||
uint32_t timings[2] = {rx_us, sleep_us};
|
||||
const uint32_t* applied_timings = _prefs.rx_powersaving_enabled
|
||||
&& radio_driver.supportsRxPowerSaving() ? timings : NULL;
|
||||
const uint32_t* applied_timings = apply_rxps ? timings : NULL;
|
||||
if (timing_ok && _cli.radioProfiles().applyPrimary(
|
||||
pending_freq, pending_bw, pending_sf, pending_cr, true, pending_preamble, applied_timings) == mesh::RadioParamApplyResult::APPLIED) {
|
||||
set_radio_at = 0;
|
||||
|
||||
@@ -1154,6 +1154,9 @@ bool WebConfigServer::prepareStationOwner() {
|
||||
}
|
||||
|
||||
void WebConfigServer::createServer() {
|
||||
// Delayed saved-network joins reach here without startLanMode(). Publish
|
||||
// the committed admin credential before HTTP handlers can accept logins.
|
||||
initializeManagementPassword();
|
||||
if (_host == NULL) {
|
||||
_host = new AsyncWebServer(80);
|
||||
_server = _host;
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Retained RXPS preferences must not block radios without RX duty cycling."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from test_repeater_radio_timing_integration import method
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
HARNESS = r'''
|
||||
#include <cassert>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <initializer_list>
|
||||
#include <helpers/radiolib/RXPowerSaving.h>
|
||||
#define MESH_DEBUG_PRINTLN(...) ((void)0)
|
||||
#define WRAPPER_CLASS RadioDriver
|
||||
struct RadioDriver {
|
||||
static constexpr bool SupportsRxPowerSaving = RXPS_SUPPORTED;
|
||||
bool supportsRxPowerSaving() const { return SupportsRxPowerSaving; }
|
||||
} radio_driver;
|
||||
namespace mesh { enum class RadioParamApplyResult { APPLIED, BUSY, FAILED }; }
|
||||
struct CommonCLI {
|
||||
unsigned calls=0;
|
||||
bool got_timings=false, last_temporary=false;
|
||||
uint32_t rx_us=0, sleep_us=0;
|
||||
float applied_freq=910.525f;
|
||||
static bool calculateRxPowerSavingLevel(uint32_t,uint8_t,float,uint32_t,uint32_t*,uint32_t*);
|
||||
CommonCLI& radioProfiles() { return *this; }
|
||||
bool primaryRadioApplyReady(bool) { return true; }
|
||||
mesh::RadioParamApplyResult applyPrimary(float freq,float bw,uint8_t sf,uint8_t cr,
|
||||
bool temporary,uint16_t preamble,const uint32_t* timings) {
|
||||
assert(freq==910.539978f && bw==62.5f && sf==7 && cr==5 && preamble==32);
|
||||
assert(!timings || radio_driver.supportsRxPowerSaving());
|
||||
++calls;applied_freq=freq;last_temporary=temporary;got_timings=timings;
|
||||
if(timings) { rx_us=timings[0];sleep_us=timings[1]; }
|
||||
return mesh::RadioParamApplyResult::APPLIED;
|
||||
}
|
||||
};
|
||||
@CALCULATE@
|
||||
static constexpr uint32_t now_ms=3000;
|
||||
uint32_t nextRadioApplyRetryDelay(uint8_t& failures) { ++failures;return 1000; }
|
||||
struct Prefs {
|
||||
bool rx_powersaving_enabled=true;
|
||||
uint8_t rx_ps_level=8;
|
||||
uint16_t rx_ps_preamble=16;
|
||||
uint32_t rx_ps_rx_us=65625,rx_ps_sleep_us=60000;
|
||||
};
|
||||
struct Role {
|
||||
Prefs _prefs;
|
||||
CommonCLI _cli;
|
||||
uint32_t set_radio_at=2000,revert_radio_at=86402000,radio_apply_retry_at=0;
|
||||
uint8_t radio_apply_failures=0,active_cr=5,active_sf=7,pending_sf=7,pending_cr=5;
|
||||
uint16_t pending_preamble=32;
|
||||
float pending_freq=910.539978f,pending_bw=62.5f,active_bw=62.5f;
|
||||
bool temp_radio_applied=false,saved_radio_apply_pending=false;
|
||||
struct Manager { unsigned getOutboundTotal() const { return 0; } } manager;
|
||||
Manager* _mgr=&manager;
|
||||
bool hasOutbound() const { return false; }
|
||||
bool millisHasNowPassed(uint32_t at) const { return int32_t(now_ms-at)>=0; }
|
||||
uint32_t futureMillis(uint32_t delay) const { return now_ms+delay; }
|
||||
bool applySavedRadioParams() { assert(false);return false; }
|
||||
@METHOD@
|
||||
bool apply(bool temporary) { @APPLY@ }
|
||||
};
|
||||
int main() {
|
||||
uint32_t expected_rx=0,expected_sleep=0;
|
||||
bool supported=radio_driver.supportsRxPowerSaving();
|
||||
bool calculated=CommonCLI::calculateRxPowerSavingLevel(2,7,62.5f,
|
||||
rxPowerSavingPreambleForParams(7,62.5f),&expected_rx,&expected_sleep);
|
||||
assert(calculated==supported); // The actual calculator rejects unsupported hardware.
|
||||
for(bool temporary:{false,true}) for(bool enabled:{false,true})
|
||||
for(uint8_t level:{0,2,8,11}) for(uint16_t preamble:{0,16,32}) {
|
||||
Role node;
|
||||
node._prefs.rx_powersaving_enabled=enabled;
|
||||
node._prefs.rx_ps_level=level;
|
||||
node._prefs.rx_ps_preamble=preamble;
|
||||
const bool expected_ok=!supported || !enabled || level<=10;
|
||||
if(supported && enabled && level>0 && level<=10) {
|
||||
assert(CommonCLI::calculateRxPowerSavingLevel(level,7,62.5f,
|
||||
preamble ? preamble : rxPowerSavingPreambleForParams(7,62.5f),
|
||||
&expected_rx,&expected_sleep));
|
||||
}
|
||||
assert(node.apply(temporary)==expected_ok);
|
||||
assert(node._cli.calls==(expected_ok ? 1U : 0U));
|
||||
if(expected_ok) {
|
||||
assert(node._cli.applied_freq==910.539978f);
|
||||
assert(node._cli.got_timings==(supported && enabled));
|
||||
if(supported && enabled) {
|
||||
assert(node._cli.rx_us==(level==0 ? 65625 : expected_rx));
|
||||
assert(node._cli.sleep_us==(level==0 ? 60000 : expected_sleep));
|
||||
}
|
||||
}
|
||||
assert(node._prefs.rx_powersaving_enabled==enabled && node._prefs.rx_ps_level==level);
|
||||
assert(node._prefs.rx_ps_preamble==preamble);
|
||||
assert(node._prefs.rx_ps_rx_us==65625 && node._prefs.rx_ps_sleep_us==60000);
|
||||
assert(node.revert_radio_at==86402000); // Preserve the accepted 24-hour lease.
|
||||
@STATE@
|
||||
}
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class InfrastructureRxpsApplyTest(unittest.TestCase):
|
||||
def test_unsupported_rxps_does_not_block_primary_or_temporary_apply(self):
|
||||
calculate = method((ROOT / 'src/helpers/CommonCLI.cpp').read_text(),
|
||||
'bool CommonCLI::calculateRxPowerSavingLevel(')
|
||||
for role, filename, cls in (
|
||||
('simple_repeater', 'MyMesh.cpp', 'MyMesh'),
|
||||
('simple_room_server', 'MyMesh.cpp', 'MyMesh'),
|
||||
('simple_sensor', 'SensorMesh.cpp', 'SensorMesh')):
|
||||
source = (ROOT / 'examples' / role / filename).read_text()
|
||||
if role == 'simple_repeater':
|
||||
production = method(source, f'bool {cls}::applyRadioParams(')
|
||||
apply = 'return applyRadioParams(910.539978f,62.5f,7,5,32,temporary);'
|
||||
state = 'if(expected_ok) assert(node._cli.last_temporary==temporary);'
|
||||
else:
|
||||
production = method(source, f'void {cls}::servicePendingPrimaryRadioSettings(')
|
||||
apply = '(void)temporary;servicePendingPrimaryRadioSettings(false);return temp_radio_applied;'
|
||||
state = '''
|
||||
assert(node.temp_radio_applied==expected_ok);
|
||||
assert(node.set_radio_at==(expected_ok ? 0U : 2000U));
|
||||
assert(node.saved_radio_apply_pending==!expected_ok);
|
||||
assert(node.radio_apply_retry_at==(expected_ok ? 0U : 4000U));
|
||||
if(expected_ok) assert(node._cli.last_temporary);
|
||||
'''
|
||||
production = production.replace(cls + '::', '')
|
||||
code = HARNESS.replace('@CALCULATE@', calculate).replace('@METHOD@', production)
|
||||
code = code.replace('@APPLY@', apply).replace('@STATE@', state)
|
||||
for supported in (False, True):
|
||||
with self.subTest(role=role, supported=supported):
|
||||
self.run_cpp(code, supported)
|
||||
# Prove this fixture catches the original early rejection, rather
|
||||
# than merely compiling a driver that always accepts the tuple.
|
||||
mutated = code.replace('if (apply_rxps && _prefs.rx_ps_level != 0)',
|
||||
'if (_prefs.rx_powersaving_enabled && _prefs.rx_ps_level != 0)')
|
||||
self.assertNotEqual(mutated, code)
|
||||
with self.subTest(role=role, negative_control=True):
|
||||
self.run_cpp(mutated, False, succeeds=False)
|
||||
|
||||
def run_cpp(self, code, supported, succeeds=True):
|
||||
with tempfile.TemporaryDirectory(prefix='meshcore-rxps-apply-') as folder:
|
||||
cpp, binary = Path(folder) / 'test.cpp', Path(folder) / 'test'
|
||||
cpp.write_text(code)
|
||||
built = subprocess.run([
|
||||
'g++', '-std=c++17', '-Wall', '-Wextra', '-Werror',
|
||||
'-fsanitize=address,undefined', '-fno-sanitize-recover=all',
|
||||
'-fno-pie', '-no-pie', f'-DRXPS_SUPPORTED={int(supported)}',
|
||||
'-I', str(ROOT / 'src'), str(cpp), '-o', str(binary)],
|
||||
capture_output=True, text=True)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
ran = subprocess.run([str(binary)], capture_output=True, text=True)
|
||||
if succeeds:
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
else:
|
||||
self.assertNotEqual(ran.returncode, 0, 'negative control unexpectedly passed')
|
||||
self.assertIn('Assertion', ran.stderr)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -5,6 +5,7 @@ import unittest
|
||||
|
||||
from test_replay_reset_integration import extract_braced
|
||||
import test_wifi_ota_start as wifi_start
|
||||
import test_webconfig_login_throttle as login_tests
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
@@ -107,6 +108,129 @@ class WebConfigStationOwnershipTest(unittest.TestCase):
|
||||
self.compile_and_run(self.station_fixture(), "-DWITH_MQTT_BRIDGE=1",
|
||||
"-DTEST_LEGACY_COMPANION=1")
|
||||
|
||||
def delayed_login_fixture(self, without_initialization=False):
|
||||
source = (ROOT / "src/helpers/esp32/WebConfigServer.cpp").read_text()
|
||||
fixture = self.station_fixture().split("int main() {", 1)[0]
|
||||
auth = (ROOT / "test/fixtures/webconfig_login_handler.cpp").read_text()
|
||||
transport = "\n".join(extract_braced(auth, signature) + ";" for signature in (
|
||||
"struct Client", "struct AsyncWebServerResponse", "struct AsyncWebServerRequest"))
|
||||
transport = r'''
|
||||
#include <map>
|
||||
#include <ArduinoJson.h>
|
||||
#include <helpers/WebConfigLoginThrottle.h>
|
||||
struct NodeSnapshot { char admin_password[16] = {}; };
|
||||
struct AsyncWebServer {
|
||||
bool credential_ready_at_begin = false;
|
||||
explicit AsyncWebServer(int port) { assert(port == 80); }
|
||||
void begin() {
|
||||
mesh::esp32::managementPassword::Snapshot current;
|
||||
credential_ready_at_begin = mesh::esp32::managementPassword::snapshot(current);
|
||||
}
|
||||
};
|
||||
struct DefaultHeaders {
|
||||
static DefaultHeaders& Instance() { static DefaultHeaders value; return value; }
|
||||
void addHeader(const char*, const char*) {}
|
||||
};
|
||||
static uint32_t random_word = 123;
|
||||
uint32_t esp_random() { return ++random_word; }
|
||||
''' + transport
|
||||
fixture = fixture.replace("class WebConfigServer {", transport + "\nclass WebConfigServer {")
|
||||
fixture = fixture.replace(" struct Callbacks { bool supportsRoomService() const { return false; } };", r'''
|
||||
struct Callbacks {
|
||||
NodeSnapshot node = {"saved-secret"}; unsigned snapshots = 0;
|
||||
bool supportsRoomService() const { return false; }
|
||||
void getNodeSnapshot(NodeSnapshot& out) { ++snapshots; out = node; }
|
||||
};
|
||||
static AsyncWebServer* _host;
|
||||
AsyncWebServer* _server = nullptr;
|
||||
char _session_token[33] = {};
|
||||
uint32_t _session_last_seen = 0, _session_generation = 0, _ap_auth_generation = 0;
|
||||
WebConfigLoginThrottle::Tracker _login_throttle;
|
||||
void initializeManagementPassword();
|
||||
void handleLogin(AsyncWebServerRequest*);
|
||||
void noteNetworkActivity() {}
|
||||
void registerRoutes() {}
|
||||
''')
|
||||
fixture = fixture.replace(" int status() const { return state; }",
|
||||
" int status() const { return state; }\n int softAPIP() const { return 4; }")
|
||||
fixture = fixture.replace(" void createServer() { ++server_starts; }", " void createServer();")
|
||||
create = extract_braced(source, "void WebConfigServer::createServer(")
|
||||
if without_initialization:
|
||||
self.assertIn(" initializeManagementPassword();", create)
|
||||
create = create.replace(" initializeManagementPassword();\n", "", 1)
|
||||
# A counter observes the complete production server-start body without
|
||||
# replacing its credential, route attachment, or HTTP begin ordering.
|
||||
create = create.replace("{\n", "{\n ++server_starts;\n", 1)
|
||||
fixture += "\nAsyncWebServer* WebConfigServer::_host = nullptr;\n" + create + "\n"
|
||||
fixture += "\n".join(extract_braced(source, signature) for signature in (
|
||||
"void WebConfigServer::initializeManagementPassword(",
|
||||
"static bool fixedTimeEquals(", "void WebConfigServer::handleLogin("))
|
||||
return fixture + r'''
|
||||
static int browserLogin(WebConfigServer& portal, const char* password) {
|
||||
AsyncWebServerRequest request;
|
||||
request.socket.remote = 0x0304A8C0;
|
||||
request.body = std::string("{\"password\":\"") + password + "\"}";
|
||||
request._tempObject = request.body.data();
|
||||
portal.handleLogin(&request);
|
||||
if (request.status == 503) assert(request.reply == "{\"error\":\"credentials unavailable\"}");
|
||||
return request.status;
|
||||
}
|
||||
int main() {
|
||||
namespace password = mesh::esp32::managementPassword;
|
||||
password::Snapshot initial;
|
||||
assert(!password::snapshot(initial));
|
||||
const uint8_t key[32] = {};
|
||||
char reply[160] = {};
|
||||
WebConfigServer::Callbacks repeater;
|
||||
WebConfigServer portal(&repeater, nullptr, true, key, "test", "test", "repeater", "G3", true);
|
||||
portal.updateWiFiOwnership(true);
|
||||
assert(portal.startAutoMode(reply));
|
||||
assert(portal._mode == WebConfigServer::MODE_CONNECTING && portal.server_starts == 0);
|
||||
assert(!password::snapshot(initial)); // No earlier AP/immediate-LAN path initializes it.
|
||||
WiFi.state = WL_CONNECTED;
|
||||
portal.tick(++clock_ms);
|
||||
assert(portal._mode == WebConfigServer::MODE_LAN && portal.server_starts == 1);
|
||||
assert(browserLogin(portal, "wrong-secret") == 401);
|
||||
assert(browserLogin(portal, "saved-secret") == 200);
|
||||
assert(portal._server->credential_ready_at_begin);
|
||||
assert(repeater.snapshots == 1); // HTTP authentication never reads mutable prefs.
|
||||
|
||||
// A Room listener may wait for another station owner. Its start must retain
|
||||
// a newer committed credential rather than publish a candidate RAM snapshot.
|
||||
assert(password::publish("committed-key"));
|
||||
password::Snapshot committed; assert(password::snapshot(committed));
|
||||
WebConfigServer::Callbacks room;
|
||||
strcpy(room.node.admin_password, "temporary-RAM");
|
||||
WiFi.state = WL_DISCONNECTED;
|
||||
WebConfigServer waiting(&room, nullptr, false, key, "test", "test", "room", "G3", true);
|
||||
waiting.updateWiFiOwnership(false);
|
||||
assert(waiting.startAutoMode(reply));
|
||||
assert(waiting._mode == WebConfigServer::MODE_CONNECTING && waiting.server_starts == 0);
|
||||
WiFi.state = WL_CONNECTED;
|
||||
waiting.tick(++clock_ms);
|
||||
assert(waiting._mode == WebConfigServer::MODE_LAN && waiting.server_starts == 1);
|
||||
assert(browserLogin(waiting, "temporary-RAM") == 401);
|
||||
assert(browserLogin(waiting, "committed-key") == 200);
|
||||
assert(waiting._server->credential_ready_at_begin);
|
||||
password::Snapshot after; assert(password::snapshot(after));
|
||||
assert(after.generation == committed.generation && !strcmp(after.password, committed.password));
|
||||
assert(room.snapshots == 0);
|
||||
}
|
||||
'''
|
||||
|
||||
def test_delayed_station_login_initializes_credentials_before_http_and_keeps_committed_value(self):
|
||||
json_include = login_tests.WebConfigLoginThrottleTest.json_include(self)
|
||||
for mqtt in (False, True):
|
||||
with self.subTest(mqtt=mqtt):
|
||||
prefix = "#define WITH_MQTT_BRIDGE 1\n" if mqtt else ""
|
||||
login_tests.WebConfigLoginThrottleTest.compile_run(
|
||||
self, prefix + self.delayed_login_fixture(), (json_include,))
|
||||
# Without the real createServer initializer, the delayed LAN
|
||||
# path reproduces the device's 503 credentials-unavailable error.
|
||||
login_tests.WebConfigLoginThrottleTest.compile_run(
|
||||
self, prefix + self.delayed_login_fixture(True),
|
||||
(json_include,), expect_rejection=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user