From b483a917f68ce3857f0a30417370c80f9347232b Mon Sep 17 00:00:00 2001 From: mikecarper Date: Fri, 16 Oct 2026 16:54:08 -0700 Subject: [PATCH] Keep monochrome Companion LED timing working across rollover --- .github/workflows/run-unit-tests.yml | 1 + examples/companion_radio/ui-new/UITask.cpp | 13 +- examples/companion_radio/ui-new/UITask.h | 4 +- examples/companion_radio/ui-orig/UITask.cpp | 17 +- examples/companion_radio/ui-tiny/UITask.cpp | 13 +- examples/companion_radio/ui-tiny/UITask.h | 4 +- test/fixtures/mono_led_rollover.cpp | 197 ++++++++++++++++++++ test/test_mono_led_rollover.py | 114 +++++++++++ 8 files changed, 339 insertions(+), 24 deletions(-) create mode 100644 test/fixtures/mono_led_rollover.cpp create mode 100644 test/test_mono_led_rollover.py diff --git a/.github/workflows/run-unit-tests.yml b/.github/workflows/run-unit-tests.yml index 789f15381..3d65e7542 100644 --- a/.github/workflows/run-unit-tests.yml +++ b/.github/workflows/run-unit-tests.yml @@ -803,6 +803,7 @@ jobs: node test/test_notification_builder.js python3 -B test/test_notification_settings.py python3 -B test/test_notification_led_ownership.py -v + python3 -B test/test_mono_led_rollover.py -v python3 -B test/test_display_power.py python3 -B test/test_legacy_ui_version_bounds.py -v python3 -B test/test_ssd1306_power.py -v diff --git a/examples/companion_radio/ui-new/UITask.cpp b/examples/companion_radio/ui-new/UITask.cpp index 6ea322322..2d05211a6 100644 --- a/examples/companion_radio/ui-new/UITask.cpp +++ b/examples/companion_radio/ui-new/UITask.cpp @@ -2106,20 +2106,21 @@ void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, void UITask::userLedHandler() { if (_notification_led_owned || !(_notification_outputs & mesh::notify::Led)) return; #ifdef PIN_STATUS_LED - int cur_time = millis(); - if (cur_time > next_led_change) { + const uint32_t cur_time = millis(); + // Phase age also survives long notification-owned or disabled intervals. + if (static_cast(cur_time - last_led_change) > led_phase_millis) { if (led_state == 0) { led_state = 1; if (_msgcount > 0) { - last_led_increment = LED_ON_MSG_MILLIS; + led_phase_millis = LED_ON_MSG_MILLIS; } else { - last_led_increment = LED_ON_MILLIS; + led_phase_millis = LED_ON_MILLIS; } - next_led_change = cur_time + last_led_increment; } else { led_state = 0; - next_led_change = cur_time + LED_CYCLE_MILLIS - last_led_increment; + led_phase_millis = LED_CYCLE_MILLIS - led_phase_millis; } + last_led_change = cur_time; digitalWrite(PIN_STATUS_LED, led_state == LED_STATE_ON); } #endif diff --git a/examples/companion_radio/ui-new/UITask.h b/examples/companion_radio/ui-new/UITask.h index 42b51e80a..e9186fca8 100644 --- a/examples/companion_radio/ui-new/UITask.h +++ b/examples/companion_radio/ui-new/UITask.h @@ -87,8 +87,8 @@ class UITask : public AbstractUITask { #endif #ifdef PIN_STATUS_LED int led_state = 0; - int next_led_change = 0; - int last_led_increment = 0; + uint32_t last_led_change = 0; + uint32_t led_phase_millis = 0; #endif #ifdef PIN_USER_BTN_ANA diff --git a/examples/companion_radio/ui-orig/UITask.cpp b/examples/companion_radio/ui-orig/UITask.cpp index 27fe91fef..0494d571e 100644 --- a/examples/companion_radio/ui-orig/UITask.cpp +++ b/examples/companion_radio/ui-orig/UITask.cpp @@ -563,23 +563,24 @@ void UITask::userLedHandler() { } #elif defined(PIN_STATUS_LED) static int state = 0; - static int next_change = 0; - static int last_increment = 0; + static uint32_t last_change = 0; + static uint32_t phase_millis = 0; - int cur_time = millis(); - if (cur_time > next_change) { + const uint32_t cur_time = millis(); + // Phase age also survives long notification-owned or disabled intervals. + if (static_cast(cur_time - last_change) > phase_millis) { if (state == 0) { state = 1; if (_msgcount > 0) { - last_increment = LED_ON_MSG_MILLIS; + phase_millis = LED_ON_MSG_MILLIS; } else { - last_increment = LED_ON_MILLIS; + phase_millis = LED_ON_MILLIS; } - next_change = cur_time + last_increment; } else { state = 0; - next_change = cur_time + LED_CYCLE_MILLIS - last_increment; + phase_millis = LED_CYCLE_MILLIS - phase_millis; } + last_change = cur_time; digitalWrite(PIN_STATUS_LED, state == LED_STATE_ON); } #endif diff --git a/examples/companion_radio/ui-tiny/UITask.cpp b/examples/companion_radio/ui-tiny/UITask.cpp index abb5b0fb1..515db50e6 100644 --- a/examples/companion_radio/ui-tiny/UITask.cpp +++ b/examples/companion_radio/ui-tiny/UITask.cpp @@ -752,20 +752,21 @@ void UITask::newMsg(uint8_t path_len, const char* from_name, const char* text, void UITask::userLedHandler() { if (_notification_led_owned || !(_notification_outputs & mesh::notify::Led)) return; #ifdef PIN_STATUS_LED - int cur_time = millis(); - if (cur_time > next_led_change) { + const uint32_t cur_time = millis(); + // Phase age also survives long notification-owned or disabled intervals. + if (static_cast(cur_time - last_led_change) > led_phase_millis) { if (led_state == 0) { led_state = 1; if (_msgcount > 0) { - last_led_increment = LED_ON_MSG_MILLIS; + led_phase_millis = LED_ON_MSG_MILLIS; } else { - last_led_increment = LED_ON_MILLIS; + led_phase_millis = LED_ON_MILLIS; } - next_led_change = cur_time + last_led_increment; } else { led_state = 0; - next_led_change = cur_time + LED_CYCLE_MILLIS - last_led_increment; + led_phase_millis = LED_CYCLE_MILLIS - led_phase_millis; } + last_led_change = cur_time; digitalWrite(PIN_STATUS_LED, led_state == LED_STATE_ON); } #endif diff --git a/examples/companion_radio/ui-tiny/UITask.h b/examples/companion_radio/ui-tiny/UITask.h index fa37e7c15..25d0fd08e 100644 --- a/examples/companion_radio/ui-tiny/UITask.h +++ b/examples/companion_radio/ui-tiny/UITask.h @@ -51,8 +51,8 @@ class UITask : public AbstractUITask { uint16_t _cached_batt_mv; #ifdef PIN_STATUS_LED int led_state = 0; - int next_led_change = 0; - int last_led_increment = 0; + uint32_t last_led_change = 0; + uint32_t led_phase_millis = 0; #endif #ifdef PIN_USER_BTN_ANA diff --git a/test/fixtures/mono_led_rollover.cpp b/test/fixtures/mono_led_rollover.cpp new file mode 100644 index 000000000..8335c5110 --- /dev/null +++ b/test/fixtures/mono_led_rollover.cpp @@ -0,0 +1,197 @@ +// Full actual handlers/field initializers are injected. RGB is not configured. +// Arduino clock and output writes are the only hardware boundaries mocked. +#include +#include +#include +#include +#include + +@CONSTANTS@ + +static uint32_t clock_ms = 0; +uint32_t millis() { return clock_ms; } +static unsigned writes = 0; +static const char* active_case = "startup"; +static unsigned checks = 0; +#define CHECK(value) do { \ + ++checks; \ + if (!(value)) { \ + std::fprintf(stderr, "FAIL %s: %s (line %d)\n", active_case, #value, __LINE__); \ + std::exit(1); \ + } \ +} while (0) + +#ifdef PIN_STATUS_LED +static unsigned last_level = 9; +void digitalWrite(unsigned pin, unsigned level) { + CHECK(pin == PIN_STATUS_LED); + CHECK(level <= 1); + ++writes; + last_level = level; +} +#endif + +class UITask { +public: + @DEFAULTS@ + @FIELDS@ + @SETTERS@ + int _msgcount = 0; + void userLedHandler(); +}; + +@HANDLER@ + +#ifdef PIN_STATUS_LED +static void at(UITask& ui, uint32_t now, unsigned count, bool on) { + clock_ms = now; + ui.userLedHandler(); + CHECK(writes == count); + if (count) CHECK(last_level == unsigned(on ? LED_STATE_ON : !LED_STATE_ON)); +} + +static void cadence(UITask& ui, uint32_t start, uint32_t pulse) { + at(ui, start, 1, true); + at(ui, start, 1, true); + at(ui, start + pulse, 1, true); + at(ui, start + pulse + 1, 2, false); + at(ui, start + pulse + 1, 2, false); + at(ui, start + LED_CYCLE_MILLIS + 1, 2, false); + at(ui, start + LED_CYCLE_MILLIS + 2, 3, true); +} + +static void suppressed(UITask& ui, bool owner, bool initial_on) { + constexpr uint32_t start = 100; + constexpr uint32_t inactive = 26u * 24u * 60u * 60u * 1000u; + at(ui, start, 1, true); + if (!initial_on) at(ui, start + LED_ON_MILLIS + 1, 2, false); + const unsigned before = writes; + const uint32_t suppressed_at = clock_ms; + if (owner) ui.setNotificationLedOwnership(true); + else ui.setNotificationOutputs(uint8_t(31 & ~mesh::notify::Led)); + at(ui, suppressed_at + 1, before, initial_on); + at(ui, suppressed_at + inactive, before, initial_on); + if (owner) ui.setNotificationLedOwnership(false); + else ui.setNotificationOutputs(31); + at(ui, suppressed_at + inactive, before + 1, !initial_on); + at(ui, suppressed_at + inactive, before + 1, !initial_on); + const uint32_t phase = initial_on ? LED_CYCLE_MILLIS - LED_ON_MILLIS : LED_ON_MILLIS; + at(ui, suppressed_at + inactive + phase, before + 1, !initial_on); + at(ui, suppressed_at + inactive + phase + 1, before + 2, initial_on); +} +#endif + +// A new process per case preserves real ui-orig function-static initialization. +int main(int argc, char** argv) { + CHECK(argc == 2); + active_case = argv[1]; + UITask ui; + const char* name = argv[1]; +#ifdef PIN_STATUS_LED + if (!std::strcmp(name, "zero")) { + at(ui, 0, 0, false); + cadence(ui, 1, LED_ON_MILLIS); + } else if (!std::strcmp(name, "upper")) { + cadence(ui, 0x80000000u, LED_ON_MILLIS); + } else if (!std::strcmp(name, "max")) { + cadence(ui, UINT32_MAX, LED_ON_MILLIS); + } else if (!std::strcmp(name, "normal")) { + cadence(ui, 100, LED_ON_MILLIS); + } else if (!std::strcmp(name, "unread")) { + ui._msgcount = 1; + cadence(ui, 100, LED_ON_MSG_MILLIS); + } else if (!std::strcmp(name, "signed")) { + cadence(ui, 0x7fffffffu - 10, LED_ON_MILLIS); + } else if (!std::strcmp(name, "wrap")) { + cadence(ui, UINT32_MAX - 10, LED_ON_MILLIS); + } else if (!std::strcmp(name, "off-wrap")) { + cadence(ui, UINT32_MAX - 100, LED_ON_MILLIS); + } else if (!std::strcmp(name, "zero-stamp")) { + at(ui, uint32_t(0u - LED_ON_MILLIS - 1u), 1, true); + at(ui, UINT32_MAX, 1, true); + at(ui, 0, 2, false); + at(ui, 0, 2, false); + at(ui, LED_CYCLE_MILLIS - LED_ON_MILLIS, 2, false); + at(ui, LED_CYCLE_MILLIS - LED_ON_MILLIS + 1, 3, true); + } else if (!std::strcmp(name, "message-on")) { + ui._msgcount = 2; + at(ui, 100, 1, true); + ui._msgcount = 0; + at(ui, 120, 1, true); + at(ui, 300, 1, true); + at(ui, 301, 2, false); + at(ui, 4101, 2, false); + at(ui, 4102, 3, true); + at(ui, 4122, 3, true); + at(ui, 4123, 4, false); + } else if (!std::strcmp(name, "message-off")) { + at(ui, 100, 1, true); + at(ui, 121, 2, false); + ui._msgcount = 1; + at(ui, 130, 2, false); + at(ui, 4101, 2, false); + at(ui, 4102, 3, true); + at(ui, 4302, 3, true); + at(ui, 4303, 4, false); + } else if (!std::strcmp(name, "owner-fresh") || !std::strcmp(name, "mask-fresh")) { + const bool owner = !std::strcmp(name, "owner-fresh"); + if (owner) ui.setNotificationLedOwnership(true); + else ui.setNotificationOutputs(uint8_t(31 & ~mesh::notify::Led)); + at(ui, 0, 0, false); + at(ui, 0x80000000u, 0, false); + if (owner) ui.setNotificationLedOwnership(false); + else ui.setNotificationOutputs(31); + cadence(ui, 0x80000000u, LED_ON_MILLIS); + } else if (!std::strcmp(name, "owner-on-long")) { + suppressed(ui, true, true); + } else if (!std::strcmp(name, "owner-off-long")) { + suppressed(ui, true, false); + } else if (!std::strcmp(name, "mask-on-long")) { + suppressed(ui, false, true); + } else if (!std::strcmp(name, "mask-off-long")) { + suppressed(ui, false, false); + } else if (!std::strcmp(name, "suppressed-short")) { + at(ui, 100, 1, true); + ui.setNotificationLedOwnership(true); + at(ui, 105, 1, true); + ui.setNotificationLedOwnership(false); + at(ui, 110, 1, true); + at(ui, 120, 1, true); + at(ui, 121, 2, false); + } else if (!std::strcmp(name, "delayed-one-phase")) { + at(ui, 100, 1, true); + at(ui, 100100, 2, false); + at(ui, 100100, 2, false); + at(ui, 104080, 2, false); + at(ui, 104081, 3, true); + } else if (!std::strcmp(name, "both-vetoes")) { + ui.setNotificationLedOwnership(true); + ui.setNotificationOutputs(0); + at(ui, 100, 0, false); + ui.setNotificationLedOwnership(false); + at(ui, 200, 0, false); + ui.setNotificationOutputs(31); + at(ui, 200, 1, true); + } else { + std::fprintf(stderr, "unknown case: %s\n", name); + return 2; + } +#else + CHECK(std::strcmp(name, "no-led") == 0); + const uint32_t stamps[] = {0u, 1u, 0x7fffffffu, 0x80000000u, UINT32_MAX}; + for (uint32_t stamp : stamps) { + clock_ms = stamp; + ui.userLedHandler(); + CHECK(writes == 0); + ui.setNotificationLedOwnership(true); + ui.userLedHandler(); + CHECK(writes == 0); + ui.setNotificationLedOwnership(false); + ui.setNotificationOutputs(0); + ui.userLedHandler(); + CHECK(writes == 0); + ui.setNotificationOutputs(31); + } +#endif + std::printf("PASS %s: %u checks\n", name, checks); +} diff --git a/test/test_mono_led_rollover.py b/test/test_mono_led_rollover.py new file mode 100644 index 000000000..bb204140b --- /dev/null +++ b/test/test_mono_led_rollover.py @@ -0,0 +1,114 @@ +"""Exercise real monochrome LED timers, exact field defaults, and ownership gates. + +The complete production handler is compiled for original/new/tiny UIs. RGB and +backlight are not configured. uint32_t millis and GPIO writes are host fakes; +this is not electrical, scheduler-latency, or hardware power-consumption proof. +""" +from pathlib import Path +import os +import re +import shutil +import subprocess +import tempfile +import unittest + +from test_replay_reset_integration import extract_braced + +ROOT = Path(__file__).resolve().parents[1] +FIXTURE = ROOT / 'test/fixtures/mono_led_rollover.cpp' +UIS = ('ui-orig', 'ui-new', 'ui-tiny') +CASES = ('zero', 'upper', 'max', 'normal', 'unread', 'signed', 'wrap', 'off-wrap', + 'zero-stamp', 'message-on', 'message-off', 'owner-fresh', 'mask-fresh', + 'owner-on-long', 'owner-off-long', 'mask-on-long', 'mask-off-long', + 'suppressed-short', 'delayed-one-phase', 'both-vetoes') + + +def harness(ui, mutation=None): + prefix = ROOT / 'examples/companion_radio' / ui + source = (prefix / 'UITask.cpp').read_text(encoding='ascii') + header = (prefix / 'UITask.h').read_text(encoding='ascii') + abstract = (ROOT / 'examples/companion_radio/AbstractUITask.h').read_text(encoding='ascii') + handler = extract_braced(source, 'void UITask::userLedHandler()') + first_constant = source.index('#define LED_ON_MILLIS') + constants = source[source.rfind('#', 0, first_constant): + source.index('#endif', first_constant) + len('#endif')] + fields = '' + if ui != 'ui-orig': + first_field = header.index(' int led_state = 0;') + fields = header[header.rfind('#ifdef PIN_STATUS_LED', 0, first_field): + header.index('#endif', first_field) + len('#endif')] + defaults = '\n'.join(re.findall(r'^ (?:bool _notification_led_owned|uint8_t _notification_outputs) = .*;', + abstract, re.MULTILINE)) + setters = '\n'.join(extract_braced(abstract, signature) for signature in ( + 'void setNotificationLedOwnership(', 'void setNotificationOutputs(')) + if mutation == 'no-owner-guard': + guard = 'if (_notification_led_owned || !(_notification_outputs & mesh::notify::Led)) return;' + if handler.count(guard) != 1: + raise AssertionError('the actual ownership/output guard must be present') + handler = handler.replace(guard, '', 1) + elif mutation == 'non-strict-edge': + # Only mutate the monochrome branch, leaving the unrelated RGB text alone. + first = handler.index('#elif defined(PIN_STATUS_LED)') if ui == 'ui-orig' else 0 + before, mono = handler[:first], handler[first:] + mono, count = re.subn(r'(\)\s*)>(\s*(?:led_)?phase_millis\))', r'\1>=\2', mono, count=1) + if count != 1: + raise AssertionError('monochrome phase timer must retain its strict edge') + handler = before + mono + code = FIXTURE.read_text(encoding='ascii') + for token, value in {'CONSTANTS': constants, 'FIELDS': fields, 'DEFAULTS': defaults, + 'SETTERS': setters, 'HANDLER': handler}.items(): + code = code.replace('@' + token + '@', value) + return code + + +class MonoLedRolloverTest(unittest.TestCase): + def test_actual_monochrome_handlers_preserve_cadence_and_ownership(self): + self.run_variants() + + def test_missing_ownership_guard_fails_semantic_check(self): + self.run_variants('no-owner-guard', ('owner-fresh',), 'FAIL owner-fresh: writes == count') + + def test_early_edge_regression_is_rejected(self): + self.run_variants('non-strict-edge', ('zero',), 'FAIL zero: writes == count') + + def run_variants(self, mutation=None, cases=CASES, expected_failure=None): + compiler = shutil.which('g++') or shutil.which('clang++') + if compiler is None: + self.skipTest('a host C++17 compiler is required') + sanitize = [] if os.name == 'nt' else [ + '-fsanitize=address,undefined', '-fno-sanitize-recover=all', '-fno-pie', '-no-pie'] + with tempfile.TemporaryDirectory(prefix='mono-led-rollover-') as directory: + work = Path(directory) + for ui in UIS: + source = work / (ui + '.cpp') + source.write_text(harness(ui, mutation), encoding='ascii') + variants = (0, 1) if mutation else (0, 1, None) + for polarity in variants: + with self.subTest(ui=ui, polarity=polarity): + name = ui + '-' + ('none' if polarity is None else str(polarity)) + binary = work / (name + ('.exe' if os.name == 'nt' else '')) + macros = (['-DPIN_STATUS_LED=24', '-DLED_STATE_ON=' + str(polarity)] + if polarity is not None else []) + built = subprocess.run([ + compiler, '-std=c++17', '-O1', '-g', '-Wall', '-Wextra', '-Werror', + '-Wno-misleading-indentation', *sanitize, *macros, + '-I' + str(ROOT / 'src'), str(source), '-o', str(binary), + ], capture_output=True, text=True, timeout=60) + self.assertEqual(built.returncode, 0, built.stdout + built.stderr) + # ui-orig really uses function statics: never reset them in a fake. + for case in cases if polarity is not None else ('no-led',): + with self.subTest(case=case): + tested = subprocess.run([str(binary), case], capture_output=True, + text=True, timeout=10) + if expected_failure: + self.assertEqual(tested.returncode, 1, tested.stdout + tested.stderr) + self.assertIn(expected_failure, tested.stderr) + self.assertNotIn('AddressSanitizer:', tested.stderr) + self.assertNotIn('runtime error:', tested.stderr) + else: + self.assertEqual(tested.returncode, 0, tested.stdout + tested.stderr) + self.assertRegex(tested.stdout, r'PASS ' + case + r': \d+ checks') + + +if __name__ == '__main__': + unittest.main()