diff --git a/esphome/energymonitor.yaml b/esphome/energymonitor.yaml index 42ab0a6..cab5100 100644 --- a/esphome/energymonitor.yaml +++ b/esphome/energymonitor.yaml @@ -154,6 +154,58 @@ light: output: display_backlight_output restore_mode: ALWAYS_ON +switch: + - platform: template + id: slideshow_enabled + name: "Diashow" + icon: mdi:play-box-multiple + optimistic: true + restore_mode: ALWAYS_OFF + on_turn_on: + - script.execute: slideshow_worker + on_turn_off: + - script.stop: slideshow_worker + +number: + - platform: template + id: slideshow_interval + name: "Diashow Intervall" + icon: mdi:timer-outline + entity_category: config + unit_of_measurement: s + min_value: 5 + max_value: 300 + step: 5 + initial_value: 15 + mode: box + optimistic: true + restore_value: true + on_value: + - if: + condition: + switch.is_on: slideshow_enabled + then: + - script.execute: slideshow_worker + +select: + - platform: template + id: slideshow_scope + name: "Diashow Umfang" + icon: mdi:view-carousel + entity_category: config + options: + - "Alle Ansichten" + - "Nur Hauptseiten" + initial_option: "Alle Ansichten" + optimistic: true + restore_value: true + on_value: + - if: + condition: + switch.is_on: slideshow_enabled + then: + - script.execute: slideshow_worker + font: - file: "fonts/Roboto-Regular.ttf" id: font_small @@ -535,6 +587,74 @@ interval: } script: + - id: slideshow_worker + mode: restart + then: + - while: + condition: + switch.is_on: slideshow_enabled + then: + # Delay first so starting or reconfiguring never skips the current view. + - delay: !lambda |- + const float seconds = id(slideshow_interval).state; + return static_cast((std::isfinite(seconds) + ? fmaxf(5.0f, fminf(seconds, 300.0f)) : 15.0f) * 1000.0f); + - if: + condition: + switch.is_on: slideshow_enabled + then: + - script.execute: advance_slideshow + - id: advance_slideshow + then: + - lambda: |- + // Do not call manual navigation scripts: those intentionally stop the slideshow. + if (id(slideshow_scope).current_option() == "Nur Hauptseiten") { + id(page_index) = (id(page_index) + 1) % 5; + return; + } + switch (id(page_index)) { + case 0: + if (id(page_one_gauge_view)) { + id(page_one_gauge_view) = false; + } else { + id(page_index) = 1; + id(device_usage_view) = 0; + } + break; + case 1: + if (id(device_usage_view) == 0) { + id(device_usage_view) = 1; + } else { + id(page_index) = 2; + id(clock_digital_view) = false; + } + break; + case 2: + if (!id(clock_digital_view)) { + id(clock_digital_view) = true; + } else { + id(page_index) = 3; + id(internet_view) = 0; + } + break; + case 3: + if (id(internet_view) < 2) { + id(internet_view)++; + } else { + id(page_index) = 4; + id(climate_graph_view) = false; + } + break; + case 4: + if (!id(climate_graph_view)) { + id(climate_graph_view) = true; + break; + } + id(page_index) = 0; + id(page_one_gauge_view) = true; + break; + } + - script.execute: refresh_display - id: reset_energy_subscriptions then: - lambda: |- @@ -561,10 +681,12 @@ script: - component.update: tft - id: show_previous_page then: + - switch.turn_off: slideshow_enabled - lambda: id(page_index) = (id(page_index) + 5 - 1) % 5; - script.execute: refresh_display - id: toggle_page_mode then: + - switch.turn_off: slideshow_enabled - lambda: |- if (id(page_index) == 0) { id(page_one_gauge_view) = !id(page_one_gauge_view); @@ -580,6 +702,7 @@ script: - script.execute: refresh_display - id: show_next_page then: + - switch.turn_off: slideshow_enabled - lambda: id(page_index) = (id(page_index) + 1) % 5; - script.execute: refresh_display @@ -813,8 +936,12 @@ display: const bool grid_power_valid = id(grid_power).has_state() && std::isfinite(id(grid_power).state); const float grid_power_value = grid_power_valid ? id(grid_power).state : 0.0f; const float grid_power_magnitude = fabsf(grid_power_value); - const float grid_maximum = gauge_maximum(grid_power_magnitude, 1.0f); - int grid_gauge_percent = static_cast(grid_power_magnitude / grid_maximum * 100.0f); + const bool solar_power_valid = id(balcony_solar_power).has_state() + && std::isfinite(id(balcony_solar_power).state) && id(balcony_solar_power).state >= 0.0f; + const float solar_power_value = solar_power_valid ? id(balcony_solar_power).state : 0.0f; + // One shared scale keeps grid and solar ring lengths directly comparable. + const float maximum = gauge_maximum(fmaxf(grid_power_magnitude, solar_power_value), 1.0f); + int grid_gauge_percent = static_cast(grid_power_magnitude / maximum * 100.0f); if (grid_gauge_percent > 100) grid_gauge_percent = 100; const Color grid_gauge_color = grid_power_value >= 0.0f ? Color(143, 190, 223) // #8FBEDF @@ -822,12 +949,8 @@ display: it.filled_gauge(gauge_center_x, gauge_center_y, 140, 122, 100, gauge_background); it.filled_gauge(gauge_center_x, gauge_center_y, 140, 122, grid_gauge_percent, grid_gauge_color); - // The inner band scales independently to the current solar power. - const bool solar_power_valid = id(balcony_solar_power).has_state() - && std::isfinite(id(balcony_solar_power).state) && id(balcony_solar_power).state >= 0.0f; - const float solar_power_value = solar_power_valid ? id(balcony_solar_power).state : 0.0f; - const float solar_maximum = gauge_maximum(solar_power_value, 1.0f); - int solar_gauge_percent = static_cast(solar_power_value / solar_maximum * 100.0f); + // The inner solar band uses the same watts-per-percent as the outer grid band. + int solar_gauge_percent = static_cast(solar_power_value / maximum * 100.0f); if (solar_gauge_percent > 100) solar_gauge_percent = 100; const Color solar_gauge_color = Color(255, 170, 40); // #FFAA28 it.filled_gauge(gauge_center_x, gauge_center_y, 116, 98, 100, gauge_background); @@ -855,9 +978,8 @@ display: return std::string(text); }; it.printf(gauge_center_x, 204, id(font_device), Color::WHITE, TextAlign::TOP_CENTER, - "Max: Netz %s / Solar %s", - grid_power_valid ? format_power(grid_maximum).c_str() : "--", - solar_power_valid ? format_power(solar_maximum).c_str() : "--"); + "Gemeinsame Skala: %s", + grid_power_valid || solar_power_valid ? format_power(maximum).c_str() : "--"); } else if (id(page_index) == 1) { // Page 2 lists nine consumers at once in two columns; button B changes group. const int device_count = 18; diff --git a/esphome/tests/slideshow_test.py b/esphome/tests/slideshow_test.py new file mode 100644 index 0000000..353b2bd --- /dev/null +++ b/esphome/tests/slideshow_test.py @@ -0,0 +1,321 @@ +"""Focused slideshow regressions; run: python3 esphome/tests/slideshow_test.py. + +Requires PyYAML and g++. Only the configuration itself is read, never secrets. +The native harness executes the actual YAML lambdas, not Python translations. +""" + +from pathlib import Path +import subprocess +import tempfile +import unittest + +import yaml + + +class ConfigLoader(yaml.SafeLoader): + pass + + +ConfigLoader.add_constructor("!secret", lambda loader, node: "") +ConfigLoader.add_constructor("!lambda", lambda loader, node: loader.construct_scalar(node)) + +CONFIG = Path(__file__).resolve().parents[1] / "energymonitor.yaml" +FIELDS = ( + "page_index", "page_one_gauge_view", "device_usage_view", + "clock_digital_view", "internet_view", "climate_graph_view", +) +# State order follows FIELDS; a view's identity ignores other pages' memories. +DEFAULT = (0, 1, 0, 0, 0, 0) +VIEWS = ( + (0, 1), (0, 0), (1, 0), (1, 1), (2, 0), (2, 1), + (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), +) +SUBPAGE_FIELD = (1, 2, 3, 4, 5) +MANUAL = ("show_previous_page", "toggle_page_mode", "show_next_page") + + +def by_id(config, section, name): + return next(item for item in config[section] if item.get("id") == name) + + +def view(state): + return state[0], state[SUBPAGE_FIELD[state[0]]] + + +def state_for(current_view): + state = list(DEFAULT) + page, subpage = current_view + state[0] = page + state[SUBPAGE_FIELD[page]] = subpage + return tuple(state) + + +class SlideshowTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.config = yaml.load(CONFIG.read_text(), Loader=ConfigLoader) + cls.scripts = {item["id"]: item for item in cls.config["script"]} + cls.worker = cls.scripts["slideshow_worker"] + cls.loop = cls.worker["then"][0]["while"] + cls.interval = by_id(cls.config, "number", "slideshow_interval") + cls.scope = by_id(cls.config, "select", "slideshow_scope") + cls.switch = by_id(cls.config, "switch", "slideshow_enabled") + cls.all_views = cls.scope["initial_option"] + + temporary = tempfile.TemporaryDirectory(prefix="slideshow-test-") + cls.addClassCleanup(temporary.cleanup) + directory = Path(temporary.name) + cls.binary = directory / "slideshow" + source = directory / "slideshow.cpp" + globals_by_id = {item["id"]: item for item in cls.config["globals"]} + declarations = "\n".join( + f"{globals_by_id[name]['type']} {name} = " + f"{globals_by_id[name]['initial_value']};" + for name in FIELDS + ) + functions = [ + "void advance_slideshow() {\n" + + cls.scripts["advance_slideshow"]["then"][0]["lambda"] + "\n}", + "uint32_t slideshow_delay() {\n" + + cls.loop["then"][0]["delay"] + "\n}", + ] + for name in MANUAL: + functions.append( + f"void {name}() {{\n" + + cls.scripts[name]["then"][1]["lambda"] + "\n}" + ) + source.write_text( + "#include \n#include \n#include \n" + "#include \n#define id(name) name\n" + + declarations + + "\nstruct { float state; } slideshow_interval;\n" + + "struct { std::string option;\n" + + " const std::string ¤t_option() const { return option; }\n" + + "} slideshow_scope;\n" + + "\n".join(functions) + + r''' +void print_state() { + std::cout << page_index << ' ' << page_one_gauge_view << ' ' + << device_usage_view << ' ' << clock_digital_view << ' ' + << internet_view << ' ' << climate_graph_view << '\n'; +} +int main(int argc, char **argv) { + if (argc != 4) return 2; + const std::string action = argv[1]; + const int steps = std::stoi(argv[2]); + slideshow_scope.option = argv[3]; + if (action == "delay") { + std::string seconds; + std::cin >> seconds; + slideshow_interval.state = std::stof(seconds); + std::cout << slideshow_delay() << '\n'; + return 0; + } + if (action != "defaults") { + std::cin >> page_index >> page_one_gauge_view >> device_usage_view + >> clock_digital_view >> internet_view >> climate_graph_view; + if (!std::cin) return 3; + } + for (int i = 0; i < steps; ++i) { + if (action == "advance") advance_slideshow(); + else if (action == "show_previous_page") show_previous_page(); + else if (action == "toggle_page_mode") toggle_page_mode(); + else if (action == "show_next_page") show_next_page(); + else if (action != "defaults") return 4; + print_state(); + } +} +''' + ) + result = subprocess.run( + ["g++", "-std=c++17", "-Wall", "-Wextra", "-Werror", + str(source), "-o", str(cls.binary)], + capture_output=True, text=True, timeout=30, + ) + if result.returncode: + raise RuntimeError("Native harness compilation failed:\n" + result.stderr) + + def native(self, action, state=DEFAULT, *, steps=1, scope=None): + result = subprocess.run( + [str(self.binary), action, str(steps), + self.all_views if scope is None else scope], + input=" ".join(map(str, state)), capture_output=True, text=True, + timeout=5, + ) + self.assertEqual(result.returncode, 0, result.stderr) + return [tuple(map(int, line.split())) for line in result.stdout.splitlines()] + + def delay(self, seconds): + return self.native("delay", (seconds,))[0][0] + + def test_default_cycle_has_exactly_eleven_distinct_views(self): + initial = self.native("defaults")[0] + self.assertEqual(initial, DEFAULT) + self.assertEqual(self.all_views, "Alle Ansichten") + cycle = [initial] + self.native("advance", initial, steps=11) + self.assertEqual(tuple(map(view, cycle)), VIEWS + (VIEWS[0],)) + self.assertEqual(len(set(map(view, cycle[:-1]))), 11) + self.assertEqual(view(cycle[-1]), view(initial)) + + def test_full_cycle_from_every_view_wraps_once(self): + for offset, current in enumerate(VIEWS): + with self.subTest(start=current): + initial = state_for(current) + cycle = [initial] + self.native("advance", initial, steps=11) + expected = tuple(VIEWS[(offset + step) % 11] for step in range(12)) + self.assertEqual(tuple(map(view, cycle)), expected) + self.assertEqual(len(set(map(view, cycle[:-1]))), 11) + self.assertEqual(sum(view(state) == current for state in cycle[1:]), 1) + self.assertEqual(sum( + cycle[i][0] == 4 and cycle[i + 1][0] == 0 + for i in range(11) + ), 1) + + def test_entering_each_main_page_resets_stale_subpage(self): + # Every remembered page starts on its last subpage, not its first. + stale = (0, 0, 1, 1, 2, 1) + first_subpages = (1, 0, 0, 0, 0) + for destination in range(5): + with self.subTest(destination=destination): + initial = list(stale) + initial[0] = (destination - 1) % 5 + actual = self.native("advance", initial)[0] + expected = list(initial) + expected[0] = destination + expected[SUBPAGE_FIELD[destination]] = first_subpages[destination] + self.assertEqual(actual, tuple(expected)) + + def test_main_pages_only_wraps_five_and_preserves_all_flags(self): + for flags in (DEFAULT[1:], (0, 1, 1, 2, 1)): + for page in range(5): + with self.subTest(page=page, flags=flags): + initial = (page,) + flags + cycle = [initial] + self.native( + "advance", initial, steps=5, scope="Nur Hauptseiten" + ) + self.assertEqual([state[0] for state in cycle], + [(page + step) % 5 for step in range(6)]) + self.assertEqual(len({state[0] for state in cycle[:-1]}), 5) + self.assertTrue(all(state[1:] == flags for state in cycle)) + self.assertEqual(cycle[-1], initial) + + def test_current_subpage_continues_without_reset_on_enable(self): + # Declarative enable/worker tests below prove there is no pre-delay action; + # these native checks prove the first eventual tick continues each view. + for index, current in enumerate(VIEWS): + with self.subTest(current=current): + initial = state_for(current) + self.assertEqual(self.delay(self.interval["initial_value"]), 15000) + actual = self.native("advance", initial)[0] + self.assertEqual(view(actual), VIEWS[(index + 1) % 11]) + + def test_delay_default_bounds_and_nan_fallback(self): + for seconds, milliseconds in ( + (self.interval["initial_value"], 15000), + (-100, 5000), (0, 5000), (4.999, 5000), (5, 5000), + (42, 42000), (300, 300000), (300.001, 300000), (9999, 300000), + ("nan", 15000), ("inf", 15000), ("-inf", 15000), + ): + with self.subTest(seconds=seconds): + self.assertEqual(self.delay(seconds), milliseconds) + + def test_interval_and_scope_configuration(self): + for key, expected in { + "platform": "template", "min_value": 5, "max_value": 300, + "step": 5, "initial_value": 15, "unit_of_measurement": "s", + "optimistic": True, "restore_value": True, + }.items(): + self.assertEqual(self.interval[key], expected, key) + self.assertEqual(self.scope["options"], ["Alle Ansichten", "Nur Hauptseiten"]) + self.assertEqual(self.scope["initial_option"], "Alle Ansichten") + self.assertIs(self.scope["optimistic"], True) + self.assertIs(self.scope["restore_value"], True) + + def test_switch_is_optimistic_always_off_and_only_starts_or_stops_worker(self): + self.assertEqual(self.switch["platform"], "template") + self.assertIs(self.switch["optimistic"], True) + self.assertEqual(self.switch["restore_mode"], "ALWAYS_OFF") + self.assertEqual(self.switch["on_turn_on"], + [{"script.execute": "slideshow_worker"}]) + self.assertEqual(self.switch["on_turn_off"], + [{"script.stop": "slideshow_worker"}]) + self.assertNotIn("turn_on_action", self.switch) + self.assertNotIn("turn_off_action", self.switch) + + def test_worker_restarts_delays_first_then_guards_advance(self): + self.assertEqual(self.worker["mode"], "restart") + self.assertEqual(len(self.worker["then"]), 1) + self.assertEqual(set(self.worker["then"][0]), {"while"}) + self.assertEqual(set(self.loop), {"condition", "then"}) + self.assertEqual(self.loop["condition"], {"switch.is_on": "slideshow_enabled"}) + self.assertEqual(len(self.loop["then"]), 2) + self.assertEqual(set(self.loop["then"][0]), {"delay"}) + self.assertIsInstance(self.loop["then"][0]["delay"], str) + self.assertEqual(self.loop["then"][1], {"if": { + "condition": {"switch.is_on": "slideshow_enabled"}, + "then": [{"script.execute": "advance_slideshow"}], + }}) + + def test_number_and_select_restart_only_when_running(self): + for entity in (self.interval, self.scope): + with self.subTest(entity=entity["id"]): + self.assertEqual(entity["on_value"], [{"if": { + "condition": {"switch.is_on": "slideshow_enabled"}, + "then": [{"script.execute": "slideshow_worker"}], + }}]) + + def test_advancement_refreshes_without_manual_navigation(self): + actions = self.scripts["advance_slideshow"]["then"] + self.assertEqual(len(actions), 2) + self.assertEqual(set(actions[0]), {"lambda"}) + self.assertEqual(actions[1], {"script.execute": "refresh_display"}) + + def test_manual_scripts_stop_first_then_original_action_and_refresh(self): + for name in MANUAL: + with self.subTest(script=name): + actions = self.scripts[name]["then"] + self.assertEqual(len(actions), 3) + self.assertEqual(actions[0], {"switch.turn_off": "slideshow_enabled"}) + self.assertEqual(set(actions[1]), {"lambda"}) + self.assertEqual(actions[2], {"script.execute": "refresh_display"}) + for current in VIEWS: + initial = state_for(current) + expected = list(initial) + if name == "show_previous_page": + expected[0] = (initial[0] - 1) % 5 + elif name == "show_next_page": + expected[0] = (initial[0] + 1) % 5 + else: + field = SUBPAGE_FIELD[initial[0]] + expected[field] = (initial[field] + 1) % (3 if initial[0] == 3 else 2) + self.assertEqual(self.native(name, initial)[0], tuple(expected), current) + + def test_hardware_and_home_assistant_buttons_share_manual_scripts(self): + routes = ( + ("button_left", "Zurück", "show_previous_page", "GPIO39"), + ("button_middle", "Modus", "toggle_page_mode", "GPIO38"), + ("button_right", "Weiter", "show_next_page", "GPIO37"), + ) + for hardware_id, name, script, pin in routes: + with self.subTest(button=name): + hardware = by_id(self.config, "binary_sensor", hardware_id) + ha = next(button for button in self.config["button"] if button["name"] == name) + expected = [{"script.execute": script}] + self.assertEqual(hardware["on_press"], expected) + self.assertEqual(ha["on_press"], expected) + self.assertEqual(hardware["platform"], "gpio") + self.assertEqual(hardware["pin"]["number"], pin) + self.assertEqual(ha["platform"], "template") + + def test_no_extra_slideshow_button(self): + self.assertEqual(len(self.config["button"]), 3) + self.assertEqual({button["name"] for button in self.config["button"]}, + {"Zurück", "Modus", "Weiter"}) + hardware = [item for item in self.config["binary_sensor"] + if item["platform"] == "gpio"] + self.assertEqual({item["id"] for item in hardware}, + {"button_left", "button_middle", "button_right"}) + + +if __name__ == "__main__": + unittest.main(verbosity=2)