Add configurable battery and USB display behavior
Persist separate display modes and timeouts in seconds for battery and USB power, expose four controls in WebConfig and CLI, and apply one shared policy across display-equipped roles. Detect R8 external power from a USB host or calibrated battery voltage above 4.21 V, with cached sampling and hysteresis. Add policy, persistence, browser, and R8 power-detection regression coverage.
This commit is contained in:
1 parent
d83153e935
commit
a814a00ce7
39 files changed
+3187
-2488
No files matched your search
@@ -0,0 +1,193 @@
|
||||
"""Exercise the shared display policy and real settings/CLI code on the host."""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
FS_STUB = r'''
|
||||
#pragma once
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <cstring>
|
||||
#include <cstdint>
|
||||
struct FakeFS;
|
||||
struct File {
|
||||
FakeFS* fs = nullptr;
|
||||
std::string name;
|
||||
explicit operator bool() const { return fs != nullptr; }
|
||||
size_t size() const;
|
||||
size_t read(uint8_t*, size_t);
|
||||
size_t write(const uint8_t*, size_t);
|
||||
void close() {}
|
||||
};
|
||||
struct FakeFS {
|
||||
std::map<std::string, std::vector<uint8_t>> files;
|
||||
bool fail_write = false, fail_publish = false;
|
||||
bool exists(const char* name) { return files.count(name); }
|
||||
bool remove(const char* name) { files.erase(name); return true; }
|
||||
bool rename(const char* from, const char* to) {
|
||||
if (fail_publish && std::string(from) == "/display_prefs.tmp") return false;
|
||||
if (!exists(from) || exists(to)) return false;
|
||||
files[to] = files[from]; files.erase(from); return true;
|
||||
}
|
||||
File open(const char* name, const char* mode, bool = false) {
|
||||
if (*mode == 'w') files[name].clear();
|
||||
if (!exists(name)) return {};
|
||||
return File{this, name};
|
||||
}
|
||||
};
|
||||
inline size_t File::size() const { return fs->files[name].size(); }
|
||||
inline size_t File::read(uint8_t* out, size_t count) {
|
||||
const auto& bytes = fs->files[name];
|
||||
count = count < bytes.size() ? count : bytes.size();
|
||||
memcpy(out, bytes.data(), count); return count;
|
||||
}
|
||||
inline size_t File::write(const uint8_t* in, size_t count) {
|
||||
if (fs->fail_write) return 0;
|
||||
fs->files[name].assign(in, in + count); return count;
|
||||
}
|
||||
#define FILESYSTEM FakeFS
|
||||
'''
|
||||
|
||||
TEST = r'''
|
||||
#include <cassert>
|
||||
#include <helpers/ui/DisplayPowerSettings.h>
|
||||
using namespace mesh::ui;
|
||||
void policyTests() {
|
||||
for (unsigned mode = 0; mode <= 5; ++mode) {
|
||||
DisplayPowerPrefs prefs;
|
||||
prefs.battery.mode = DisplayMode(mode);
|
||||
DisplayPowerPolicy p;
|
||||
p.update(prefs, false, false, false, 0);
|
||||
assert(p.on() == (mode == 1 || mode == 5));
|
||||
p.update(prefs, false, false, false, 4000);
|
||||
assert(p.on() == (mode == 1));
|
||||
bool button = mode == 1 || mode == 2 || mode == 4 || mode == 5;
|
||||
assert(p.wake(DisplayWake::Button, 5000) == button);
|
||||
assert(p.on() == button);
|
||||
p.update(prefs, false, false, false, 20000);
|
||||
assert(p.on() == (mode == 1));
|
||||
assert(p.wake(DisplayWake::Message, 21000) == (mode == 1 || mode == 5));
|
||||
p.update(prefs, false, true, false, 22000);
|
||||
assert(p.on() == (mode == 1));
|
||||
assert(p.wake(DisplayWake::Message, 23000) == (mode == 1));
|
||||
assert(p.wake(DisplayWake::Button, 24000) == button);
|
||||
p.update(prefs, false, true, false, 40000);
|
||||
p.update(prefs, false, false, true, 41000);
|
||||
assert(p.on() == (mode == 1 || mode == 3 || mode == 4 || mode == 5));
|
||||
p.update(prefs, false, false, true, 100000);
|
||||
assert(p.on() == (mode == 1 || mode == 3 || mode == 4 || mode == 5));
|
||||
p.update(prefs, false, true, false, 100001);
|
||||
assert(p.on() == (mode == 1));
|
||||
}
|
||||
DisplayPowerPrefs prefs;
|
||||
prefs.usb.mode = DisplayMode::On;
|
||||
DisplayPowerPolicy p;
|
||||
p.update(prefs, false, false, false, 100);
|
||||
p.wake(DisplayWake::Button, 200);
|
||||
p.update(prefs, true, false, false, 300);
|
||||
assert(p.on());
|
||||
p.update(prefs, false, false, false, 400);
|
||||
assert(!p.on()); // USB wake does not leak into the battery profile.
|
||||
p.wake(DisplayWake::Button, 500);
|
||||
prefs.battery.seconds = 1;
|
||||
p.update(prefs, false, false, false, 600);
|
||||
assert(p.on());
|
||||
p.update(prefs, false, false, false, 1600);
|
||||
assert(!p.on());
|
||||
p.wake(DisplayWake::Button, UINT32_MAX - 500);
|
||||
p.update(prefs, false, false, false, 498);
|
||||
assert(p.on());
|
||||
p.update(prefs, false, false, false, 499);
|
||||
assert(!p.on());
|
||||
p.wake(DisplayWake::Button, 1000);
|
||||
prefs.battery.mode = DisplayMode::Off;
|
||||
p.update(prefs, false, false, true, 1001);
|
||||
assert(!p.on()); // Off wins over a pending button wake and pairing.
|
||||
}
|
||||
void commandTests() {
|
||||
FakeFS fs;
|
||||
assert(!loadDisplayPowerSettings(&fs, true));
|
||||
assert(displayPowerPrefs().battery.mode == DisplayMode::ButtonPairing);
|
||||
char reply[160];
|
||||
auto run = [&](const char* text, const char* expected) {
|
||||
assert(handleDisplayPowerCommand(text, reply, sizeof(reply)));
|
||||
assert(std::string(reply) == expected);
|
||||
};
|
||||
run("set display.mode automatic", "OK");
|
||||
run("set display.timeout 27", "OK");
|
||||
run("set display.usb.mode on", "OK");
|
||||
run("set display.usb.timeout 123", "OK");
|
||||
assert(loadDisplayPowerSettings(&fs, true));
|
||||
run("get display.mode", "> automatic");
|
||||
run("get display.timeout", "> 27");
|
||||
run("get display.usb.mode", "> on");
|
||||
run("get display.usb.timeout", "> 123");
|
||||
const auto saved = fs.files["/display_prefs"];
|
||||
for (const char* value : {"", "0", "-1", "+2", "1.5", "15seconds", "3601", "9999999999999999999999"}) {
|
||||
const std::string command = std::string("set display.timeout ") + value;
|
||||
run(command.c_str(), "Error: timeout must be 1-3600 seconds");
|
||||
assert(fs.files["/display_prefs"] == saved);
|
||||
}
|
||||
run("set display.mode typo", "Error: use off|on|button|pairing|button-pairing|automatic");
|
||||
assert(!handleDisplayPowerCommand("set display.model off", reply, sizeof(reply)));
|
||||
fs.fail_write = true;
|
||||
run("set display.mode off", "Error: display settings save failed");
|
||||
assert(displayPowerPrefs().battery.mode == DisplayMode::Automatic);
|
||||
assert(fs.files["/display_prefs"] == saved);
|
||||
fs.fail_write = false; fs.fail_publish = true;
|
||||
run("set display.mode off", "Error: display settings save failed");
|
||||
assert(loadDisplayPowerSettings(&fs, true));
|
||||
run("get display.mode", "> automatic");
|
||||
fs.fail_publish = false;
|
||||
fs.files["/display_prefs.bak"] = saved;
|
||||
fs.files["/display_prefs"][4] ^= 0x80;
|
||||
assert(loadDisplayPowerSettings(&fs, true));
|
||||
run("get display.timeout", "> 27");
|
||||
assert(loadDisplayPowerSettings(&fs, false));
|
||||
run("set display.mode pairing", "Error: BLE pairing display unsupported");
|
||||
run("set display.usb.mode button-pairing", "Error: BLE pairing display unsupported");
|
||||
FakeFS legacy;
|
||||
assert(!loadDisplayPowerSettings(&legacy, false));
|
||||
migrateLegacyDisplayTimeout(0);
|
||||
assert(loadDisplayPowerSettings(&legacy, false));
|
||||
run("get display.mode", "> on");
|
||||
run("get display.usb.mode", "> on");
|
||||
migrateLegacyDisplayTimeout(42);
|
||||
assert(loadDisplayPowerSettings(&legacy, false));
|
||||
run("get display.mode", "> automatic");
|
||||
run("get display.timeout", "> 42");
|
||||
run("get display.usb.timeout", "> 42");
|
||||
}
|
||||
int main() { policyTests(); commandTests(); }
|
||||
'''
|
||||
|
||||
|
||||
class DisplayPowerTest(unittest.TestCase):
|
||||
def test_policy_and_persistent_commands(self):
|
||||
compiler = shutil.which("g++") or shutil.which("clang++")
|
||||
self.assertIsNotNone(compiler, "host C++ compiler required")
|
||||
with tempfile.TemporaryDirectory(prefix="mesh-display-test-") as name:
|
||||
work = Path(name)
|
||||
(work / "helpers").mkdir()
|
||||
(work / "helpers/IdentityStore.h").write_text(FS_STUB)
|
||||
(work / "test.cpp").write_text(TEST)
|
||||
executable = work / "display-test.exe"
|
||||
result = subprocess.run([
|
||||
compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror",
|
||||
"-DDISPLAY_CLASS=SSD1306Display", "-I" + str(work),
|
||||
"-I" + str(ROOT / "src"), str(work / "test.cpp"),
|
||||
str(ROOT / "src/helpers/ui/DisplayPowerSettings.cpp"),
|
||||
"-o", str(executable),
|
||||
], capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
result = subprocess.run([str(executable)], capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Run the real R8 board's power detector with simulated USB, ADC and time."""
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
ARDUINO = r'''
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#define PIN_VEXT_EN 40
|
||||
#define PIN_VEXT_EN_ACTIVE 0
|
||||
#define PIN_VBAT_READ 1
|
||||
#define P_LORA_DIO_1 14
|
||||
#define P_LORA_NSS 8
|
||||
#define P_LORA_TX_LED 46
|
||||
#define P_LORA_PA_POWER 7
|
||||
#define HIGH 1
|
||||
#define LOW 0
|
||||
#define BD_STARTUP_RX_PACKET 1
|
||||
inline uint32_t test_now = 0;
|
||||
inline uint32_t millis() { return test_now; }
|
||||
inline void digitalWrite(int, int) {}
|
||||
inline void analogReadResolution(int) {}
|
||||
inline uint32_t analogReadMilliVolts(int) { return 830; }
|
||||
'''
|
||||
|
||||
BASE_BOARD = r'''
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
class ESP32Board {
|
||||
protected:
|
||||
uint8_t startup_reason = 0;
|
||||
public:
|
||||
void begin() {}
|
||||
virtual ~ESP32Board() = default;
|
||||
virtual void onBeforeTransmit() {}
|
||||
virtual void onAfterTransmit() {}
|
||||
virtual void powerOff() {}
|
||||
virtual bool setLoRaFemLnaEnabled(bool) { return false; }
|
||||
virtual bool canControlLoRaFemLna() const { return false; }
|
||||
virtual bool isLoRaFemLnaEnabled() const { return false; }
|
||||
virtual uint16_t getBattMilliVolts() { return 0; }
|
||||
virtual bool isExternalPowered() { return false; }
|
||||
virtual bool isUsbHostConnected() { return false; }
|
||||
virtual bool setAdcMultiplier(float) { return false; }
|
||||
virtual float getAdcMultiplier() const { return 0; }
|
||||
virtual const char* getManufacturerName() const { return "test"; }
|
||||
};
|
||||
'''
|
||||
|
||||
TEST = r'''
|
||||
#include <cassert>
|
||||
#include "HeltecV4R8Board.h"
|
||||
#include <helpers/ui/DisplayPowerPolicy.h>
|
||||
void LoRaFEMControl::init() {}
|
||||
void LoRaFEMControl::setSleepModeEnable() {}
|
||||
void LoRaFEMControl::setTxModeEnable() {}
|
||||
void LoRaFEMControl::setRxModeEnable() {}
|
||||
void LoRaFEMControl::setLNAEnable(bool enabled) { lna_enabled = enabled; }
|
||||
|
||||
class TestBoard : public HeltecV4R8Board {
|
||||
public:
|
||||
bool host = false;
|
||||
uint16_t voltage = 3700;
|
||||
unsigned reads = 0;
|
||||
bool isUsbHostConnected() override { return host; }
|
||||
uint16_t getBattMilliVolts() override { ++reads; return voltage; }
|
||||
};
|
||||
|
||||
int main() {
|
||||
TestBoard board;
|
||||
assert(!board.isExternalPowered());
|
||||
assert(board.reads == 1); // Sample immediately, including at millis() == 0.
|
||||
board.voltage = 4230;
|
||||
test_now = 4999;
|
||||
assert(!board.isExternalPowered());
|
||||
assert(board.reads == 1); // Frequent UI polling must not repeatedly use ADC.
|
||||
test_now = 5000;
|
||||
assert(board.isExternalPowered());
|
||||
assert(board.reads == 2);
|
||||
board.voltage = 4205;
|
||||
test_now = 10000;
|
||||
assert(board.isExternalPowered()); // Noise inside the margin retains state.
|
||||
board.voltage = 4200;
|
||||
test_now = 15000;
|
||||
assert(!board.isExternalPowered());
|
||||
board.voltage = 4210;
|
||||
test_now = 20000;
|
||||
assert(!board.isExternalPowered()); // Exactly 4.21 V is not above threshold.
|
||||
board.voltage = 4211;
|
||||
test_now = 25000;
|
||||
assert(board.isExternalPowered());
|
||||
board.voltage = 0;
|
||||
test_now = 30000;
|
||||
assert(!board.isExternalPowered()); // An absent/invalid low reading clears it.
|
||||
|
||||
// Host detection overrides a cached negative voltage result immediately,
|
||||
// including an empty battery; removing the host must not latch external power.
|
||||
const unsigned reads = board.reads;
|
||||
board.host = true;
|
||||
assert(board.isExternalPowered());
|
||||
assert(board.reads == reads);
|
||||
board.host = false;
|
||||
assert(!board.isExternalPowered());
|
||||
|
||||
// A long host connection must not preserve stale high battery voltage.
|
||||
board.voltage = 4250;
|
||||
test_now = 35000;
|
||||
assert(board.isExternalPowered());
|
||||
board.host = true;
|
||||
board.voltage = 3700;
|
||||
test_now = 50000;
|
||||
assert(board.isExternalPowered());
|
||||
board.host = false;
|
||||
assert(!board.isExternalPowered());
|
||||
|
||||
TestBoard wrapped;
|
||||
test_now = UINT32_MAX - 1000;
|
||||
assert(!wrapped.isExternalPowered());
|
||||
wrapped.voltage = 4230;
|
||||
test_now = 3998;
|
||||
assert(!wrapped.isExternalPowered());
|
||||
test_now = 3999;
|
||||
assert(wrapped.isExternalPowered()); // Five-second sampling survives wrap.
|
||||
|
||||
// Both sources select the actual USB display profile, returning to battery
|
||||
// when neither source is detected. No additional display setting is needed.
|
||||
mesh::ui::DisplayPowerPrefs prefs;
|
||||
prefs.battery.mode = mesh::ui::DisplayMode::Off;
|
||||
prefs.usb.mode = mesh::ui::DisplayMode::On;
|
||||
mesh::ui::DisplayPowerPolicy display;
|
||||
TestBoard source;
|
||||
test_now = 0;
|
||||
const auto update = [&]() {
|
||||
display.update(prefs, source.isExternalPowered() || source.isUsbHostConnected(),
|
||||
false, false, test_now);
|
||||
};
|
||||
update(); assert(!display.on());
|
||||
source.host = true;
|
||||
update(); assert(display.on());
|
||||
source.host = false;
|
||||
update(); assert(!display.on());
|
||||
source.voltage = 4230;
|
||||
test_now = 5000;
|
||||
update(); assert(display.on());
|
||||
source.voltage = 4100;
|
||||
test_now = 10000;
|
||||
update(); assert(!display.on());
|
||||
|
||||
// The estimate uses the real calibrated ADC path, including user calibration.
|
||||
HeltecV4R8Board calibrated;
|
||||
calibrated.setAdcMultiplier(5.1f);
|
||||
assert(calibrated.isExternalPowered()); // 830 mV * 5.1 = 4233 mV.
|
||||
calibrated.setAdcMultiplier(5.0f);
|
||||
test_now += 5000;
|
||||
assert(!calibrated.isExternalPowered()); // Same raw sample becomes 4150 mV.
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class R8ExternalPowerTest(unittest.TestCase):
|
||||
def test_host_voltage_and_display_profile(self):
|
||||
compiler = shutil.which("g++") or shutil.which("clang++")
|
||||
self.assertIsNotNone(compiler, "host C++ compiler required")
|
||||
with tempfile.TemporaryDirectory(prefix="mesh-r8-power-") as directory:
|
||||
work = Path(directory)
|
||||
files = {
|
||||
"Arduino.h": ARDUINO,
|
||||
"helpers/ESP32Board.h": BASE_BOARD,
|
||||
"helpers/RefCountedDigitalPin.h": """#pragma once
|
||||
class RefCountedDigitalPin {
|
||||
public:
|
||||
RefCountedDigitalPin(int, int) {}
|
||||
void begin() {}
|
||||
void claim() {}
|
||||
void release() {}
|
||||
};
|
||||
""",
|
||||
"driver/rtc_io.h": """#pragma once
|
||||
using gpio_num_t = int;
|
||||
using esp_reset_reason_t = int;
|
||||
constexpr int ESP_RST_DEEPSLEEP = 1;
|
||||
inline int esp_reset_reason() { return 0; }
|
||||
inline long esp_sleep_get_ext1_wakeup_status() { return 0; }
|
||||
inline void rtc_gpio_hold_dis(int) {}
|
||||
inline void rtc_gpio_hold_en(int) {}
|
||||
inline void rtc_gpio_deinit(int) {}
|
||||
""",
|
||||
"test.cpp": TEST,
|
||||
}
|
||||
for path, content in files.items():
|
||||
target = work / path
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_text(content)
|
||||
executable = work / "r8-power.exe"
|
||||
variant = ROOT / "variants/heltec_v4_r8"
|
||||
result = subprocess.run([
|
||||
compiler, "-std=c++17", "-Wall", "-Wextra", "-Werror",
|
||||
"-I" + str(work), "-I" + str(variant), "-I" + str(ROOT / "src"),
|
||||
str(work / "test.cpp"), str(variant / "HeltecV4R8Board.cpp"),
|
||||
"-o", str(executable),
|
||||
], capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
result = subprocess.run([str(executable)], capture_output=True, text=True, timeout=10)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -152,6 +152,8 @@ int main() {
|
||||
g_mock_pin_levels[7]=HIGH;
|
||||
user_btn.begin(); user_btn.enableQuadrupleClick();
|
||||
Display display;
|
||||
display.servicePower(false);
|
||||
display.wake(mesh::ui::DisplayWake::Button);
|
||||
UITask task(display);
|
||||
HomeScreen home(&task);
|
||||
Screen group;
|
||||
@@ -393,6 +395,7 @@ class MessageNavigationTest(unittest.TestCase):
|
||||
"-I" + str(ROOT / "src"), "-I" + str(ROOT / "test/mocks"),
|
||||
"-fsanitize=address,undefined", "-fno-pie", "-no-pie",
|
||||
"-x", "c++", "-", str(ROOT / "src/helpers/ui/MomentaryButton.cpp"),
|
||||
str(ROOT / "src/helpers/ui/DisplayDriver.cpp"),
|
||||
"-o", str(binary),
|
||||
], input=preamble + implementation + SCENARIOS, text=True, capture_output=True)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
|
||||
@@ -47,6 +47,43 @@ def embedded_page():
|
||||
|
||||
|
||||
class WebConfigUiRuntimeTest(unittest.TestCase):
|
||||
def test_four_display_controls_and_pairing_capability(self):
|
||||
status, config = self.setup_values()
|
||||
config["display"] = {
|
||||
"mode": "button", "timeout": 23,
|
||||
"usb_mode": "on", "usb_timeout": 55, "pairing": False,
|
||||
}
|
||||
prelude = r'''<script>
|
||||
window.fetch=function(path){
|
||||
var value=path==="/api/status"?%s:%s;
|
||||
return Promise.resolve({ok:true,status:200,json:function(){return Promise.resolve(value)}});
|
||||
};
|
||||
window.addEventListener("load",function(){
|
||||
setTimeout(function(){enterApp()},50);
|
||||
setTimeout(function(){
|
||||
var card=document.getElementById("display-settings"), body=document.body;
|
||||
body.setAttribute("data-test-display-visible",!card.classList.contains("hide"));
|
||||
body.setAttribute("data-test-display-count",card.querySelectorAll("[data-k]").length);
|
||||
body.setAttribute("data-test-battery-timeout",card.querySelector('[data-k="display.timeout"]').value);
|
||||
body.setAttribute("data-test-usb-timeout",card.querySelector('[data-k="display.usb.timeout"]').value);
|
||||
body.setAttribute("data-test-usb-disabled",card.querySelector('[data-k="display.usb.timeout"]').disabled);
|
||||
body.setAttribute("data-test-pairing-disabled",card.querySelector('option[value="pairing"]').disabled);
|
||||
var mode=card.querySelector('[data-k="display.mode"]');
|
||||
mode.value="off";mode.dispatchEvent(new Event("input",{bubbles:true}));
|
||||
body.setAttribute("data-test-battery-disabled",card.querySelector('[data-k="display.timeout"]').disabled);
|
||||
body.setAttribute("data-test-dirty-display",st.dirty["display.mode"]);
|
||||
},650);
|
||||
});
|
||||
</script>''' % (json.dumps(status), json.dumps(config))
|
||||
dom = self.run_page(prelude)
|
||||
for attribute, value in (
|
||||
("display-visible", "true"), ("display-count", "4"),
|
||||
("battery-timeout", "23"), ("usb-timeout", "55"),
|
||||
("usb-disabled", "true"), ("pairing-disabled", "true"),
|
||||
("battery-disabled", "true"), ("dirty-display", "off"),
|
||||
):
|
||||
self.assertIn('data-test-%s="%s"' % (attribute, value), dom)
|
||||
|
||||
def setup_values(self):
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
try:
|
||||
|
||||
Reference in new issue
Block a user