Add persistent battery ADC calibration across boards
Add meter-reference calibration with saved ADC corrections, checked persistence and rollback. Preserve existing board coefficients and nRF52 voltage policy, and merge the Mini Repeater feature gates. Validation: 69 focused tests, hosted documentation checks, and four firmware builds passed. Mini Repeater retains calibration and its existing filesystem with 376 flash bytes free; earlier Mini Sensor size failures remain documented.
This commit is contained in:
1 parent
94a3b7e568
commit
ab6412e73c
108 files changed
+1303
-83
No files matched your search
@@ -38,6 +38,8 @@ python3 test/test_companion_identity_startup.py # real saved/missing/unreadable
|
||||
python3 test/test_startup_screen.py # early display ordering and cooperative entropy progress
|
||||
python3 -B test/test_common_prefs_legacy_rxgain.py -v # compact stock gain, appended tails and truncation
|
||||
python3 -B test/test_battery_forwarding.py -v # battery relay thresholds, hysteresis, calibration and checked settings records
|
||||
python3 -B test/test_battery_calibration.py -v # meter references, ADC correction, reset and invalid-reading rejection
|
||||
python3 -B test/test_battery_calibration_store.py -v # saved calibration, corruption and write-failure recovery across filesystems
|
||||
python3 test/test_companion_settings_persistence_contract.py # Atomic settings and appended Bluetooth fields
|
||||
python3 test/test_webconfig_ui.py # Web controls, reboot handling and generated-page consistency
|
||||
python3 test/test_webconfig_ui_runtime.py # Real Chromium, including independent stealth toggle
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
"""Exercise production battery calibration parsing, scaling and command behavior."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from test_replay_reset_integration import extract_braced
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
HARNESS = r'''
|
||||
#include <helpers/BatteryCalibration.h>
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <initializer_list>
|
||||
|
||||
using namespace mesh::power;
|
||||
struct Board {
|
||||
float multiplier = 1.0f;
|
||||
uint16_t millivolts = 4000;
|
||||
unsigned reads = 0;
|
||||
float getAdcMultiplier() const { return multiplier; }
|
||||
uint16_t getBattMilliVolts() { ++reads; return millivolts; }
|
||||
};
|
||||
|
||||
int main() {
|
||||
assert(validRelativeBatteryMultiplier(0));
|
||||
assert(validRelativeBatteryMultiplier(0.5f));
|
||||
assert(validRelativeBatteryMultiplier(1.5f));
|
||||
assert(!validRelativeBatteryMultiplier(0.499f));
|
||||
assert(!validRelativeBatteryMultiplier(1.501f));
|
||||
assert(!validRelativeBatteryMultiplier(NAN));
|
||||
assert(!validRelativeBatteryMultiplier(INFINITY));
|
||||
assert(scaleBatteryMillivolts(4000, 1.05f) == 4200);
|
||||
assert(scaleBatteryMillivolts(1001, 0.5f) == 501);
|
||||
assert(scaleBatteryMillivolts(0, 1.5f) == 0);
|
||||
assert(scaleBatteryMillivolts(60000, 1.5f) == UINT16_MAX);
|
||||
assert(scaleBatteryMillivolts(4000, NAN) == 4000);
|
||||
assert(scaleBatteryMillivolts(4000, 0) == 4000);
|
||||
|
||||
uint16_t parsed = 123;
|
||||
assert(parseBatteryReferenceMillivolts("4.18", parsed) && parsed == 4180);
|
||||
assert(parseBatteryReferenceMillivolts("13.200", parsed) && parsed == 13200);
|
||||
assert(parseBatteryReferenceMillivolts("65.535\t ", parsed) && parsed == 65535);
|
||||
assert(parseBatteryReferenceMillivolts("0.001", parsed) && parsed == 1);
|
||||
for (const char* bad : {"", "0", "0.000", "-4.2", "+4.2", "nan", "inf",
|
||||
"4e0", "4.2V", "4.2 extra", "4.", "4.2000", "65.536", "999999999999"}) {
|
||||
parsed = 123;
|
||||
assert(!parseBatteryReferenceMillivolts(bad, parsed) && parsed == 123);
|
||||
}
|
||||
|
||||
Board board;
|
||||
char reply[160] = {};
|
||||
bool save_ok = true;
|
||||
unsigned saves = 0;
|
||||
float saved = -1;
|
||||
auto setter = [&](float value, char* error, size_t capacity) {
|
||||
++saves;
|
||||
if (!save_ok) {
|
||||
snprintf(error, capacity, "Error: simulated save failure");
|
||||
return false;
|
||||
}
|
||||
saved = value;
|
||||
board.multiplier = value == 0 ? 1 : value;
|
||||
return true;
|
||||
};
|
||||
auto run = [&](const char* command) {
|
||||
strcpy(reply, "untouched");
|
||||
return handleBatteryCalibrationCommand(board, command, reply, sizeof(reply), setter);
|
||||
};
|
||||
assert(!run("battery calibrateX 4.18") && saves == 0);
|
||||
assert(strcmp(reply, "untouched") == 0);
|
||||
assert(run("battery calibrate 4.18") && saves == 1);
|
||||
assert(fabs(saved - 1.045f) < 0.00001f);
|
||||
assert(strstr(reply, "4.180 V") && strstr(reply, "(saved)"));
|
||||
// Repeat calibration composes with the effective existing multiplier.
|
||||
board.millivolts = 4180;
|
||||
assert(run("battery calibrate 4.18") && saves == 2);
|
||||
assert(fabs(saved - 1.045f) < 0.00001f);
|
||||
// Works with an existing absolute board coefficient too.
|
||||
board.multiplier = 5.42f;
|
||||
board.millivolts = 4000;
|
||||
assert(run("battery calibrate 4.18") && saves == 3);
|
||||
assert(fabs(saved - 5.6639f) < 0.0001f);
|
||||
// Pack voltages are not limited to single-cell lithium values.
|
||||
board.multiplier = 1;
|
||||
board.millivolts = 13000;
|
||||
assert(run("battery calibrate 13.2") && saves == 4);
|
||||
assert(fabs(saved - 13200.0f / 13000.0f) < 0.00001f);
|
||||
const unsigned before = saves;
|
||||
for (const char* command : {"battery calibrate", "battery calibrate 0",
|
||||
"battery calibrate 4.2junk", "battery calibrate resetjunk",
|
||||
"battery calibrate nan", "battery calibrate 4.2", "battery calibrate 65"}) {
|
||||
assert(run(command) && strncmp(reply, "Error:", 6) == 0 && saves == before);
|
||||
}
|
||||
board.millivolts = 0;
|
||||
assert(run("battery calibrate 13.2") && saves == before);
|
||||
board.millivolts = UINT16_MAX;
|
||||
assert(run("battery calibrate 13.2") && saves == before);
|
||||
// Reset is allowed even while the voltage is unavailable.
|
||||
assert(run("battery calibrate reset") && saves == before + 1 && saved == 0);
|
||||
board.millivolts = 4000;
|
||||
save_ok = false;
|
||||
const float previous = board.multiplier;
|
||||
assert(run("battery calibrate 4.18"));
|
||||
assert(strcmp(reply, "Error: simulated save failure") == 0);
|
||||
assert(board.multiplier == previous);
|
||||
board.multiplier = 0;
|
||||
const unsigned unsupported_saves = saves, unsupported_reads = board.reads;
|
||||
assert(run("battery calibrate 4.18") && strstr(reply, "unsupported"));
|
||||
assert(run("battery calibrate reset") && strstr(reply, "unsupported"));
|
||||
assert(saves == unsupported_saves && board.reads == unsupported_reads);
|
||||
board.multiplier = NAN;
|
||||
assert(run("battery calibrate 4.18") && saves == unsupported_saves);
|
||||
// Replies obey a prefixed Companion console's smaller buffer.
|
||||
board.multiplier = 1;
|
||||
char tiny[12];
|
||||
memset(tiny, 'x', sizeof(tiny));
|
||||
assert(handleBatteryCalibrationCommand(board, "battery calibrate", tiny, 8, setter));
|
||||
assert(tiny[7] == 0 && tiny[8] == 'x');
|
||||
}
|
||||
'''
|
||||
|
||||
BOARD_HARNESS = r'''
|
||||
#include <MeshCore.h>
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
struct ADCBoard : mesh::MainBoard {
|
||||
uint16_t raw = 4000;
|
||||
bool supportsBatteryCalibration() const override { return true; }
|
||||
uint16_t getBattMilliVolts() override { return calibrateBatteryMillivolts(raw); }
|
||||
const char* getManufacturerName() const override { return "test ADC"; }
|
||||
void reboot() override {}
|
||||
uint8_t getStartupReason() const override { return 0; }
|
||||
};
|
||||
struct UnsupportedBoard : ADCBoard {
|
||||
bool supportsBatteryCalibration() const override { return false; }
|
||||
};
|
||||
int main() {
|
||||
ADCBoard board;
|
||||
assert(board.getAdcMultiplier() == 1 && board.getBattMilliVolts() == 4000);
|
||||
assert(board.setAdcMultiplier(1.05f) && board.getBattMilliVolts() == 4200);
|
||||
for (float invalid : {NAN, INFINITY, -INFINITY, -1.0f, 0.49f, 1.51f}) {
|
||||
assert(!board.setAdcMultiplier(invalid));
|
||||
assert(board.getBattMilliVolts() == 4200);
|
||||
}
|
||||
assert(board.setAdcMultiplier(0) && board.getBattMilliVolts() == 4000);
|
||||
assert(board.setAdcMultiplier(1.5f));
|
||||
board.raw = 60000;
|
||||
assert(board.getBattMilliVolts() == UINT16_MAX);
|
||||
board.raw = 0;
|
||||
assert(board.getBattMilliVolts() == 0);
|
||||
UnsupportedBoard unsupported;
|
||||
assert(unsupported.getAdcMultiplier() == 0);
|
||||
assert(!unsupported.setAdcMultiplier(1.05f));
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class BatteryCalibrationTests(unittest.TestCase):
|
||||
def exercise(self, harness):
|
||||
with tempfile.TemporaryDirectory(prefix="battery-calibration-") as folder:
|
||||
source, binary = Path(folder) / "main.cpp", Path(folder) / "check"
|
||||
source.write_text("#include <initializer_list>\n" + harness)
|
||||
build = subprocess.run([
|
||||
os.environ.get("CXX", "g++"), "-std=c++17", "-O1", "-g",
|
||||
"-Wall", "-Wextra", "-Werror", "-Wno-unused-parameter",
|
||||
"-fsanitize=address,undefined",
|
||||
"-fno-sanitize-recover=all", "-fno-pie", "-no-pie", "-I",
|
||||
str(ROOT / "src"), str(source), "-o", str(binary)
|
||||
], capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(build.returncode, 0, build.stdout + build.stderr)
|
||||
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=30)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
def test_production_calibration_commands(self):
|
||||
self.exercise(HARNESS)
|
||||
|
||||
def test_actual_board_calibration(self):
|
||||
self.exercise(BOARD_HARNESS)
|
||||
|
||||
def test_nrf52_boot_policy_takes_priority_without_double_scaling(self):
|
||||
source = (ROOT / "src/helpers/NRF52Board.cpp").read_text()
|
||||
methods = "\n".join(extract_braced(source, signature) for signature in (
|
||||
"uint16_t NRF52Board::calibrateBatteryMillivolts(",
|
||||
"float NRF52Board::getAdcMultiplier("))
|
||||
self.exercise(r'''
|
||||
#define NRF52_POWER_MANAGEMENT 1
|
||||
#include <MeshCore.h>
|
||||
#include <helpers/NRF52VoltageRules.h>
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
namespace mesh { namespace power {
|
||||
bool policy_ready = false;
|
||||
bool voltagePolicySupported() { return policy_ready; }
|
||||
uint16_t configuredAdcPermille() { return 1050; }
|
||||
}}
|
||||
class NRF52Board : public mesh::MainBoard {
|
||||
public:
|
||||
bool supportsBatteryCalibration() const override { return true; }
|
||||
uint16_t calibrateBatteryMillivolts(uint16_t) const;
|
||||
float getAdcMultiplier() const override;
|
||||
uint16_t getBattMilliVolts() override { return calibrateBatteryMillivolts(4000); }
|
||||
const char* getManufacturerName() const override { return "fixture"; }
|
||||
uint8_t getStartupReason() const override { return 0; }
|
||||
void reboot() override {}
|
||||
};
|
||||
''' + methods + r'''
|
||||
int main() {
|
||||
NRF52Board board;
|
||||
// Early startup has not loaded the boot policy yet.
|
||||
assert(board.getBattMilliVolts() == 4000 && board.getAdcMultiplier() == 1);
|
||||
// A board without boot policy uses the common calibration normally.
|
||||
assert(board.setAdcMultiplier(1.2f) && board.getBattMilliVolts() == 4800);
|
||||
mesh::power::policy_ready = true;
|
||||
// A loaded policy is authoritative, rather than stacking two corrections.
|
||||
assert(board.getBattMilliVolts() == 4200);
|
||||
assert(fabs(board.getAdcMultiplier() - 1.05f) < 0.00001f);
|
||||
assert(board.calibrateBatteryMillivolts(0) == 0);
|
||||
assert(board.calibrateBatteryMillivolts(65000) == UINT16_MAX);
|
||||
}
|
||||
''')
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,168 @@
|
||||
"""Exercise the production calibration store and rollback across filesystems."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
HARNESS = r'''
|
||||
#include <helpers/BatteryCalibrationStore.h>
|
||||
#include <helpers/BatteryCalibration.h>
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
#define ATOMIC_FILE_WRITER_IMPLEMENTATION
|
||||
#include <helpers/AtomicFileWriter.h>
|
||||
#endif
|
||||
#include "store_under_test.cpp"
|
||||
|
||||
struct Board : mesh::MainBoard {
|
||||
bool capable = true;
|
||||
uint16_t raw = 4000;
|
||||
bool supportsBatteryCalibration() const override { return capable; }
|
||||
uint16_t getBattMilliVolts() override { return calibrateBatteryMillivolts(raw); }
|
||||
const char* getManufacturerName() const override { return "fixture"; }
|
||||
uint8_t getStartupReason() const override { return 0; }
|
||||
void reboot() override {}
|
||||
void sleep(uint32_t) override {}
|
||||
};
|
||||
int main() {
|
||||
using namespace mesh::power;
|
||||
MemoryFS fs;
|
||||
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
|
||||
fs.rename_replaces = true;
|
||||
#endif
|
||||
Board board;
|
||||
assert(beginBatteryCalibrationStore(board, &fs));
|
||||
assert(fs.files.empty() && board.getAdcMultiplier() == 1);
|
||||
char reply[160];
|
||||
auto run = [&](const char* command) {
|
||||
strcpy(reply, "untouched");
|
||||
return handleStoredBatteryCalibrationCommand(board, command, reply, sizeof(reply));
|
||||
};
|
||||
assert(run("get adc.multiplier") && !strcmp(reply, "> 1.000"));
|
||||
assert(!run("get adc.multiplierXYZ") && !strcmp(reply, "untouched"));
|
||||
assert(run("battery calibrate 4.18") && strstr(reply, "(saved)"));
|
||||
assert(fabs(board.getAdcMultiplier() - 1.045f) < 0.00001f);
|
||||
assert(board.getBattMilliVolts() == 4180);
|
||||
const auto good = fs.files.at("/battery_cal");
|
||||
assert(good.size() == 12);
|
||||
Board rebooted;
|
||||
assert(beginBatteryCalibrationStore(rebooted, &fs));
|
||||
assert(fabs(rebooted.getAdcMultiplier() - 1.045f) < 0.00001f);
|
||||
fs.fail_write = true;
|
||||
assert(run("set adc.multiplier 1.1") && strstr(reply, "save unconfirmed"));
|
||||
assert(fabs(board.getAdcMultiplier() - 1.045f) < 0.00001f);
|
||||
assert(fs.files.at("/battery_cal") == good);
|
||||
fs.fail_write = false;
|
||||
// Publication can succeed before verification fails. Report uncertainty
|
||||
// and restore runtime without claiming the old disk image survived.
|
||||
fs.fail_after_publication = true;
|
||||
assert(run("set adc.multiplier 1.1") && strstr(reply, "save unconfirmed"));
|
||||
assert(fabs(board.getAdcMultiplier() - 1.045f) < 0.00001f);
|
||||
assert(fs.files.at("/battery_cal") != good);
|
||||
fs.fail_after_publication = false;
|
||||
fs.fail_read_open = false;
|
||||
Board published;
|
||||
assert(beginBatteryCalibrationStore(published, &fs));
|
||||
assert(fabs(published.getAdcMultiplier() - 1.1f) < 0.00001f);
|
||||
fs.files["/battery_cal"] = good;
|
||||
for (const char* command : {"set adc.multiplier nan", "set adc.multiplier 1junk",
|
||||
"set adc.multiplier -1", "set adc.multiplier 1.6",
|
||||
"get adc.multiplier junk", "battery calibrate 0"}) {
|
||||
assert(run(command) && !strncmp(reply, "Error:", 6));
|
||||
assert(fs.files.at("/battery_cal") == good);
|
||||
}
|
||||
// Complete but corrupted records, truncations and invalid factors cannot
|
||||
// change the factory conversion on a new instance.
|
||||
for (size_t bit = 0; bit < good.size() * 8; ++bit) {
|
||||
fs.files["/battery_cal"] = good;
|
||||
fs.files["/battery_cal"][bit / 8] ^= uint8_t(1U << (bit % 8));
|
||||
Board fresh;
|
||||
assert(!beginBatteryCalibrationStore(fresh, &fs));
|
||||
assert(fresh.getAdcMultiplier() == 1);
|
||||
}
|
||||
fs.files["/battery_cal"] = good;
|
||||
fs.files["/battery_cal"].pop_back();
|
||||
Board truncated;
|
||||
assert(!beginBatteryCalibrationStore(truncated, &fs));
|
||||
assert(truncated.getAdcMultiplier() == 1);
|
||||
fs.files["/battery_cal"] = good;
|
||||
assert(run("battery calibrate reset") && strstr(reply, "(saved)"));
|
||||
assert(board.getAdcMultiplier() == 1);
|
||||
Board reset;
|
||||
assert(beginBatteryCalibrationStore(reset, &fs) && reset.getAdcMultiplier() == 1);
|
||||
board.capable = false;
|
||||
assert(run("get adc.multiplier") && strstr(reply, "unsupported"));
|
||||
assert(run("battery calibrate 4.18") && strstr(reply, "unsupported"));
|
||||
assert(run("set adc.multiplier 1.1") && strstr(reply, "unsupported"));
|
||||
board.capable = true;
|
||||
#if defined(ESP32_PLATFORM) || defined(RP2040_PLATFORM)
|
||||
// Recover the old record if a reset interrupted the two-rename publication.
|
||||
fs.files["/battery_cal.bak"] = good;
|
||||
fs.files.erase("/battery_cal");
|
||||
Board recovered;
|
||||
assert(beginBatteryCalibrationStore(recovered, &fs));
|
||||
assert(recovered.getBattMilliVolts() == 4180);
|
||||
#endif
|
||||
char bounded[4] = {'X', 'X', 'X', 'Z'};
|
||||
assert(handleStoredBatteryCalibrationCommand(board, "get adc.multiplier", bounded, 3));
|
||||
assert(bounded[2] == 0 && bounded[3] == 'Z');
|
||||
// A failed mount or volatile fallback must not claim reboot persistence.
|
||||
assert(!beginBatteryCalibrationStore(board, nullptr));
|
||||
const float before_missing_fs = board.getAdcMultiplier();
|
||||
assert(run("battery calibrate 4.18") && strstr(reply, "save unconfirmed"));
|
||||
assert(board.getAdcMultiplier() == before_missing_fs);
|
||||
}
|
||||
'''
|
||||
|
||||
|
||||
class BatteryCalibrationStoreTests(unittest.TestCase):
|
||||
def test_roundtrip_corruption_write_failure_reset_and_backup_recovery(self):
|
||||
with tempfile.TemporaryDirectory(prefix="battery-calibration-store-") as temp:
|
||||
work = Path(temp)
|
||||
(work / "helpers").mkdir()
|
||||
mock = ROOT / "test/fixtures/radio_profiles/mocks/helpers/IdentityStore.h"
|
||||
mock_text = mock.read_text(encoding="ascii")
|
||||
mock_text = mock_text.replace(" bool fail_read_open = false;",
|
||||
" bool fail_read_open = false;\n bool fail_after_publication = false;")
|
||||
mock_text = mock_text.replace(" files[to] = files[from]; files.erase(from); return true;",
|
||||
" files[to] = files[from]; files.erase(from);\n"
|
||||
" if (fail_after_publication && !strcmp(to, \"/battery_cal\")) fail_read_open = true;\n"
|
||||
" return true;")
|
||||
(work / "helpers/IdentityStore.h").write_text(mock_text, encoding="ascii")
|
||||
# Redirect only the hardware boundary include. The transaction and
|
||||
# calibration implementation bodies remain production code.
|
||||
transaction = (ROOT / "src/helpers/ContactFileTransaction.h").read_text(encoding="ascii")
|
||||
transaction = transaction.replace('#include "IdentityStore.h"', '#include <helpers/IdentityStore.h>')
|
||||
transaction = transaction.replace('#include "PersistentStoreFormat.h"', '#include <helpers/PersistentStoreFormat.h>')
|
||||
(work / "helpers/ContactFileTransaction.h").write_text(transaction, encoding="ascii")
|
||||
store = (ROOT / "src/helpers/BatteryCalibrationStore.cpp").read_text(encoding="ascii")
|
||||
for header in ("BatteryCalibrationStore.h", "BatteryCalibration.h", "CheckedSettingsFile.h",
|
||||
"CLICommandUtils.h", "PersistentStoreFormat.h", "AtomicFileWriter.h",
|
||||
"ContactFileTransaction.h", "NRF52VoltagePolicy.h"):
|
||||
store = store.replace(f'#include "{header}"', f'#include <helpers/{header}>')
|
||||
(work / "store_under_test.cpp").write_text(store, encoding="ascii")
|
||||
(work / "test.cpp").write_text(HARNESS, encoding="ascii")
|
||||
for platform in ("ESP32_PLATFORM", "RP2040_PLATFORM", "NRF52_PLATFORM", "STM32_PLATFORM"):
|
||||
with self.subTest(platform=platform):
|
||||
binary = work / platform
|
||||
built = subprocess.run([
|
||||
os.environ.get("CXX", "g++"), "-std=c++17", "-O1", "-Wall", "-Wextra", "-Werror",
|
||||
"-Wno-sign-compare", "-Wno-unused-parameter", "-fsanitize=address,undefined", "-fno-sanitize-recover=all",
|
||||
"-fno-pie", "-no-pie", "-D" + platform,
|
||||
"-I" + str(work), "-I" + str(ROOT / "src"),
|
||||
str(work / "test.cpp"), "-o", str(binary),
|
||||
], capture_output=True, text=True, timeout=60)
|
||||
self.assertEqual(built.returncode, 0, built.stdout + built.stderr)
|
||||
result = subprocess.run([str(binary)], capture_output=True, text=True, timeout=20)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -101,6 +101,7 @@ struct Board {
|
||||
float multiplier = 1.0f;
|
||||
bool adcSupported = true;
|
||||
uint16_t getBattMilliVolts() { ++reads; return uint16_t(float(mv) * multiplier); }
|
||||
float getAdcMultiplier() const { return adcSupported ? multiplier : 0.0f; }
|
||||
bool setAdcMultiplier(float value) {
|
||||
if (!adcSupported) return false;
|
||||
multiplier = value == 0.0f ? 1.0f : value;
|
||||
@@ -288,6 +289,75 @@ void CommonCLI::dispatchVoltage(char* command, char* reply) {
|
||||
assert(strcmp(reply, "fallthrough") == 0 && board.reads == 5);
|
||||
''', prefix=prefix, flags=("-DNRF52_PLATFORM", "-DNRF52_POWER_MANAGEMENT"))
|
||||
|
||||
def test_actual_adc_get_set_fall_back_when_nrf52_voltage_policy_is_unavailable(self):
|
||||
source = (ROOT / "src/helpers/CommonCLI.cpp").read_text(encoding="ascii")
|
||||
setter = extract_braced(source, "void CommonCLI::handleSetCmd(")
|
||||
getter = extract_braced(source, "void CommonCLI::handleGetCmd(")
|
||||
def policy_route(method):
|
||||
start = method.index(" const bool adc_multiplier_command =")
|
||||
return method[start:method.index("#endif", start)]
|
||||
set_branch = extract_braced(setter, 'if (memcmp(config, "adc.multiplier ", 15) == 0)')
|
||||
get_branch = extract_braced(getter, 'if (configKeyEquals(config, "adc.multiplier"))')
|
||||
prefix = self.runtime_prefix(r'''
|
||||
struct Prefs { float adc_multiplier = 0.0f; } prefs;
|
||||
Prefs* _prefs = &prefs;
|
||||
unsigned prefsSaves = 0;
|
||||
bool trySavePrefs() { ++prefsSaves; return true; }
|
||||
bool applyAndSaveAdcMultiplier(float multiplier, char* reply, size_t capacity);
|
||||
void dispatchSet(char* command, char* reply);
|
||||
void dispatchGet(char* command, char* reply);
|
||||
''')
|
||||
prefix += r'''
|
||||
#include <math.h>
|
||||
#include <helpers/CLICommandUtils.h>
|
||||
namespace mesh { namespace power {
|
||||
static bool policyAvailable = false;
|
||||
static unsigned policyCalls = 0;
|
||||
static bool voltagePolicySupported() { return policyAvailable; }
|
||||
static bool handleVoltagePolicyCommand(const char*, char* reply, size_t capacity) {
|
||||
++policyCalls;
|
||||
snprintf(reply, capacity, "%s", policyAvailable ? "> policy" : "Error: voltage policy unsupported");
|
||||
return true;
|
||||
}
|
||||
}}
|
||||
'''
|
||||
prefix += extract_braced(source, "static bool configKeyEquals(") + "\n"
|
||||
prefix += extract_braced(source, "bool CommonCLI::applyAndSaveAdcMultiplier(") + "\n"
|
||||
prefix += "void CommonCLI::dispatchSet(char* command, char* reply) {\n"
|
||||
prefix += "const char* config = command + 4;\n" + policy_route(setter) + set_branch + "\n}\n"
|
||||
prefix += "void CommonCLI::dispatchGet(char* command, char* reply) {\n"
|
||||
prefix += "const char* config = command + 4;\n" + policy_route(getter) + get_branch + "\n}\n"
|
||||
self.exercise(r'''
|
||||
Board board;
|
||||
CommonCLI cli(board);
|
||||
char reply[160];
|
||||
char get[] = "get adc.multiplier";
|
||||
cli.dispatchGet(get, reply);
|
||||
assert(!strcmp(reply, "> 1.000") && mesh::power::policyCalls == 0);
|
||||
char set[] = "set adc.multiplier 1.2";
|
||||
cli.dispatchSet(set, reply);
|
||||
assert(!strncmp(reply, "OK", 2) && cli.prefsSaves == 1);
|
||||
assert(board.multiplier == 1.2f && cli.prefs.adc_multiplier == 1.2f);
|
||||
assert(mesh::power::policyCalls == 0);
|
||||
cli.dispatchGet(get, reply);
|
||||
assert(!strcmp(reply, "> 1.200") && mesh::power::policyCalls == 0);
|
||||
char profile[] = "set battery.profile lifepo4";
|
||||
cli.dispatchSet(profile, reply);
|
||||
assert(strstr(reply, "voltage policy unsupported") && mesh::power::policyCalls == 1);
|
||||
char full[] = "get battery.full";
|
||||
cli.dispatchGet(full, reply);
|
||||
assert(strstr(reply, "voltage policy unsupported") && mesh::power::policyCalls == 2);
|
||||
board.adcSupported = false;
|
||||
cli.dispatchGet(get, reply);
|
||||
assert(!strcmp(reply, "Error: unsupported") && mesh::power::policyCalls == 2);
|
||||
cli.dispatchSet(set, reply);
|
||||
assert(!strcmp(reply, "Error: unsupported") && mesh::power::policyCalls == 2);
|
||||
board.adcSupported = true;
|
||||
mesh::power::policyAvailable = true;
|
||||
cli.dispatchGet(get, reply);
|
||||
assert(!strcmp(reply, "> policy") && mesh::power::policyCalls == 3);
|
||||
''', prefix=prefix, flags=("-DNRF52_PLATFORM", "-DNRF52_POWER_MANAGEMENT"))
|
||||
|
||||
def test_actual_set_command_adc_branch_resamples_success_and_skips_rejected_changes(self):
|
||||
source = (ROOT / "src/helpers/CommonCLI.cpp").read_text(encoding="ascii")
|
||||
setter = extract_braced(source, "void CommonCLI::handleSetCmd(")
|
||||
@@ -298,10 +368,13 @@ void CommonCLI::dispatchVoltage(char* command, char* reply) {
|
||||
struct Prefs { float adc_multiplier = 0.0f; } prefs;
|
||||
Prefs* _prefs = &prefs;
|
||||
unsigned prefsSaves = 0;
|
||||
void savePrefs() { ++prefsSaves; }
|
||||
bool prefsSaveOk = true;
|
||||
bool trySavePrefs() { ++prefsSaves; return prefsSaveOk; }
|
||||
bool applyAndSaveAdcMultiplier(float multiplier, char* reply, size_t capacity);
|
||||
void dispatchAdc(char* command, char* reply);
|
||||
''')
|
||||
prefix += "\nnamespace mesh { namespace cli {\n" + parser + "\n}}\n"
|
||||
prefix += "\n#include <math.h>\nnamespace mesh { namespace cli {\n" + parser + "\n}}\n"
|
||||
prefix += extract_braced(source, "bool CommonCLI::applyAndSaveAdcMultiplier(") + "\n"
|
||||
prefix += "void CommonCLI::dispatchAdc(char* command, char* reply) {\n"
|
||||
prefix += "const char* config = &command[4];\n" + branch + "\n}\n"
|
||||
self.exercise(r'''
|
||||
@@ -329,10 +402,17 @@ void CommonCLI::dispatchVoltage(char* command, char* reply) {
|
||||
assert(strcmp(reply, "Error: unsupported") == 0 && cli.prefsSaves == 1 && board.reads == 2);
|
||||
assert(cli.prefs.adc_multiplier == 1.2f && cli.batteryAllowsForward(false));
|
||||
board.adcSupported = true;
|
||||
cli.prefsSaveOk = false;
|
||||
char failed[] = "set adc.multiplier 1.0";
|
||||
cli.dispatchAdc(failed, reply);
|
||||
assert(strstr(reply, "save unconfirmed") && cli.prefsSaves == 2 && board.reads == 2);
|
||||
assert(cli.prefs.adc_multiplier == 1.2f && board.multiplier == 1.2f);
|
||||
assert(cli.batteryAllowsForward(false));
|
||||
cli.prefsSaveOk = true;
|
||||
char reset[] = "set adc.multiplier 0";
|
||||
cli.dispatchAdc(reset, reply);
|
||||
assert(strcmp(reply, "OK - using default board multiplier") == 0);
|
||||
assert(cli.prefsSaves == 2 && board.reads == 3 && cli._battery_forward_state.percentage == 41);
|
||||
assert(cli.prefsSaves == 3 && board.reads == 3 && cli._battery_forward_state.percentage == 41);
|
||||
assert(!cli.batteryAllowsForward(false));
|
||||
''', prefix=prefix, flags=("-DESP32_PLATFORM",))
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ inline uint32_t analogReadMilliVolts(int) { return 830; }
|
||||
BASE_BOARD = r'''
|
||||
#pragma once
|
||||
#include <Arduino.h>
|
||||
#include <math.h>
|
||||
#include <helpers/LedPolicy.h>
|
||||
class ESP32Board {
|
||||
protected:
|
||||
@@ -48,6 +49,7 @@ public:
|
||||
virtual uint16_t getBattMilliVolts() { return 0; }
|
||||
virtual bool isExternalPowered() { return false; }
|
||||
virtual bool isUsbHostConnected() { return false; }
|
||||
virtual bool supportsBatteryCalibration() const { return false; }
|
||||
virtual bool setAdcMultiplier(float) { return false; }
|
||||
virtual float getAdcMultiplier() const { return 0; }
|
||||
virtual const char* getManufacturerName() const { return "test"; }
|
||||
|
||||
@@ -139,6 +139,7 @@ class RAK3x72BatteryScaleTest(unittest.TestCase):
|
||||
#include <cassert>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <helpers/BatteryCalibration.h>
|
||||
#define PIN_VBAT_READ 7
|
||||
#define ADC_MULTIPLIER @SCALE@
|
||||
static unsigned reads, resolutions;
|
||||
@@ -151,7 +152,12 @@ int analogRead(int pin) {
|
||||
remaining -= value;
|
||||
return value;
|
||||
}
|
||||
class Board { public: @BODY@ };
|
||||
class Board {
|
||||
uint16_t calibrateBatteryMillivolts(uint16_t raw) const {
|
||||
return mesh::power::scaleBatteryMillivolts(raw, 1.0f);
|
||||
}
|
||||
public: @BODY@
|
||||
};
|
||||
static_assert(ADC_MULTIPLIER == 8650, "revisit the fixed-point scale if calibration changes");
|
||||
static_assert(uint64_t(8) * 4095 * 8650 <= std::numeric_limits<uint32_t>::max(),
|
||||
"battery accumulation product must not overflow");
|
||||
@@ -172,7 +178,8 @@ int main() {
|
||||
cpp.write_text(source)
|
||||
binary = root / "battery"
|
||||
subprocess.run(["g++", "-std=c++17", "-Wall", "-Wextra", "-Werror",
|
||||
*SANITIZER_FLAGS, str(cpp), "-o", str(binary)], check=True)
|
||||
*SANITIZER_FLAGS, "-I", str(ROOT / "src"),
|
||||
str(cpp), "-o", str(binary)], check=True)
|
||||
subprocess.run([str(binary)], check=True)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user