From aac3efac2b15afcc5ec34f8fa19a5c2c9a8bc2df Mon Sep 17 00:00:00 2001 From: Commander1024 Date: Fri, 13 Nov 2026 11:33:13 +0100 Subject: [PATCH] Add daily energy history tracking --- esphome/energy_day_history.h | 119 +++++++++ esphome/energymonitor.yaml | 234 ++++++++++++++--- esphome/tests/energy_day_history_test.cpp | 307 ++++++++++++++++++++++ 3 files changed, 622 insertions(+), 38 deletions(-) create mode 100644 esphome/energy_day_history.h create mode 100644 esphome/tests/energy_day_history_test.cpp diff --git a/esphome/energy_day_history.h b/esphome/energy_day_history.h new file mode 100644 index 0000000..8ee968f --- /dev/null +++ b/esphome/energy_day_history.h @@ -0,0 +1,119 @@ +#pragma once + +#include +#include + +class EnergyDayHistory { + public: + void observe(int channel, float cumulative_kwh, uint32_t day_key, int hour, + int seconds_into_hour, uint32_t timestamp) { + if (!valid_channel(channel) || !valid_day(day_key) || hour < 0 || hour >= 24 || + seconds_into_hour < 0 || seconds_into_hour >= 3600) + return; + + if (day_key != day_) { + day_ = day_key; + for (int c = 0; c < 3; ++c) { + for (int h = 0; h < 24; ++h) { + values_[c][h] = 0.0f; + coverage_[c][h] = 0; + } + } + } + + Sample &sample = samples_[channel]; + if (!std::isfinite(cumulative_kwh) || cumulative_kwh < 0.0f) { + invalidate(channel); + return; + } + + const Sample previous = sample; + sample.valid = true; + sample.total = cumulative_kwh; + sample.day = day_key; + sample.hour = hour; + sample.seconds = seconds_into_hour; + sample.timestamp = timestamp; + + if (!previous.valid || timestamp <= previous.timestamp || + cumulative_kwh < previous.total) + return; + const uint32_t elapsed = timestamp - previous.timestamp; + if (elapsed > 300) + return; + + const int end_seconds = previous.seconds + static_cast(elapsed); + const bool crossed_hour = end_seconds >= 3600; + // Local seconds must agree with elapsed time, even across a DST transition. + if (seconds_into_hour != end_seconds % 3600 || + (!crossed_hour && (previous.day != day_key || previous.hour != hour))) + return; + + const float delta = cumulative_kwh - previous.total; + if (!crossed_hour) { + add(channel, hour, delta, elapsed); + return; + } + + const uint32_t before = static_cast(3600 - previous.seconds); + const float before_delta = delta * (static_cast(before) / elapsed); + // The previous day's part is deliberately discarded after the daily reset. + if (previous.day == day_) + add(channel, previous.hour, before_delta, before); + if (elapsed > before) + add(channel, hour, delta - before_delta, elapsed - before); + } + + void invalidate(int channel) { + if (valid_channel(channel)) + samples_[channel].valid = false; + } + + uint32_t day() const { return day_; } + + // Repeated DST hours share a slot, so coverage can exceed 3600 seconds. + uint32_t coverage_seconds(int channel, int hour) const { + return valid_channel(channel) && hour >= 0 && hour < 24 ? coverage_[channel][hour] : 0; + } + + bool has_data(int channel, int hour) const { + return coverage_seconds(channel, hour) != 0; + } + + float value(int channel, int hour) const { + return has_data(channel, hour) ? values_[channel][hour] : 0.0f; + } + + private: + struct Sample { + bool valid = false; + float total = 0.0f; + uint32_t day = 0; + int hour = 0; + int seconds = 0; + uint32_t timestamp = 0; + }; + + static bool valid_channel(int channel) { return channel >= 0 && channel < 3; } + + static bool valid_day(uint32_t key) { + const uint32_t year = key / 10000; + const uint32_t month = key / 100 % 100; + const uint32_t day = key % 100; + if (year == 0 || year > 9999 || month == 0 || month > 12 || day == 0) + return false; + const int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + const bool leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + return day <= static_cast(days[month - 1] + (month == 2 && leap ? 1 : 0)); + } + + void add(int channel, int hour, float delta, uint32_t seconds) { + values_[channel][hour] += delta; + coverage_[channel][hour] += seconds; + } + + uint32_t day_ = 0; + float values_[3][24] = {}; + uint32_t coverage_[3][24] = {}; + Sample samples_[3] = {}; +}; diff --git a/esphome/energymonitor.yaml b/esphome/energymonitor.yaml index 9562c7e..a96899a 100644 --- a/esphome/energymonitor.yaml +++ b/esphome/energymonitor.yaml @@ -12,6 +12,10 @@ esphome: project: name: monitor.energymonitor version: "1.0" + includes: + # ESPHome emits angle-bracket includes before globals; the local entry copies the header. + - + - energy_day_history.h on_boot: then: - light.turn_on: display_backlight @@ -102,6 +106,13 @@ api: id: api_server encryption: key: !secret apikey + # Ignore log-only clients; each HA connection must deliver fresh counter states. + on_client_connected: + - lambda: |- + if (client_info.rfind("Home Assistant", 0) == 0) id(reset_energy_subscriptions).execute(); + on_client_disconnected: + - lambda: |- + if (client_info.rfind("Home Assistant", 0) == 0) id(reset_energy_subscriptions).execute(); ota: platform: esphome @@ -173,6 +184,12 @@ font: glyphsets: - GF_Latin_Kernel glyphs: ["äöüÄÖÜß"] + - file: "fonts/Roboto-Regular.ttf" + id: font_chart + size: 10 + glyphsets: + - GF_Latin_Kernel + glyphs: ["äöüÄÖÜß"] - file: "fonts/materialdesignicons-webfont.ttf" id: font_icon size: 24 @@ -201,7 +218,19 @@ globals: - id: page_one_gauge_view type: bool restore_value: true - initial_value: 'false' + initial_value: 'true' + - id: energy_day_history + type: EnergyDayHistory + restore_value: true + initial_value: 'EnergyDayHistory{}' + - id: energy_sources_ready + type: std::array + restore_value: false + initial_value: 'std::array{}' + - id: energy_daily_sample_day + type: std::array + restore_value: false + initial_value: 'std::array{}' - id: clock_digital_view type: bool restore_value: true @@ -312,14 +341,48 @@ sensor: id: solar_energy_daily entity_id: sensor.energy_solar_daily internal: true + on_value: + - script.execute: + id: record_daily_energy_received + channel: 2 + value: !lambda return x; - platform: homeassistant id: grid_import_energy_daily entity_id: sensor.energy_import_daily internal: true + on_value: + - script.execute: + id: record_daily_energy_received + channel: 0 + value: !lambda return x; - platform: homeassistant id: grid_export_energy_daily entity_id: sensor.energy_export_daily internal: true + on_value: + - script.execute: + id: record_daily_energy_received + channel: 1 + value: !lambda return x; + # Lifetime kWh counters avoid races with the daily meters' midnight resets. + - platform: homeassistant + id: grid_import_energy_total + entity_id: sensor.energy_import_sum + internal: true + on_value: + - lambda: id(energy_sources_ready)[0] = std::isfinite(x) && x >= 0.0f; + - platform: homeassistant + id: grid_export_energy_total + entity_id: sensor.energy_export_sum + internal: true + on_value: + - lambda: id(energy_sources_ready)[1] = std::isfinite(x) && x >= 0.0f; + - platform: homeassistant + id: solar_energy_total + entity_id: sensor.balkonkraftwerk_energy + internal: true + on_value: + - lambda: id(energy_sources_ready)[2] = std::isfinite(x) && x >= 0.0f; - platform: homeassistant id: hallway_fragrance_power entity_id: sensor.flur_raumduft_power @@ -453,7 +516,42 @@ interval: id(climate_history_next) = (climate_slot + 1) % 361; if (id(climate_history_count) < 361) id(climate_history_count)++; + // Record energy independently of the selected page or backlight state. + const auto energy_now = id(sntp_time).now(); + if (energy_now.is_valid()) { + const uint32_t day = energy_now.year * 10000 + energy_now.month * 100 + energy_now.day_of_month; + sensor::Sensor *counters[] = {id(grid_import_energy_total), + id(grid_export_energy_total), id(solar_energy_total)}; + for (int channel = 0; channel < 3; channel++) { + // A fresh sample received before SNTP sync belongs to the first valid day. + if (id(energy_daily_sample_day)[channel] == UINT32_MAX) id(energy_daily_sample_day)[channel] = day; + const float total = connected && id(energy_sources_ready)[channel] && counters[channel]->has_state() + ? counters[channel]->state : NAN; + id(energy_day_history).observe(channel, total, day, energy_now.hour, + energy_now.minute * 60 + energy_now.second, energy_now.timestamp); + } + } + script: + - id: reset_energy_subscriptions + then: + - lambda: |- + for (int channel = 0; channel < 3; channel++) { + id(energy_sources_ready)[channel] = false; + id(energy_daily_sample_day)[channel] = 0; + id(energy_day_history).invalidate(channel); + } + - id: record_daily_energy_received + parameters: + channel: int + value: float + then: + - lambda: |- + const auto sample_time = id(sntp_time).now(); + id(energy_daily_sample_day)[channel] = !std::isfinite(value) || value < 0.0f ? 0 + : sample_time.is_valid() + ? sample_time.year * 10000 + sample_time.month * 100 + sample_time.day_of_month + : UINT32_MAX; - id: refresh_display then: # The partial-buffer driver draws multiple strips; freeze time for the entire frame. @@ -601,46 +699,106 @@ display: }; if (id(page_index) == 0 && !id(page_one_gauge_view)) { - draw_page_title("Netzleistung"); - if (id(grid_power).has_state()) { - const Color grid_power_color = id(grid_power).state >= 0 - ? Color(143, 190, 223) // #8FBEDF: positive grid power - : Color(150, 110, 217); // #966ED9: negative grid power - it.printf(308, 32, id(font_value), grid_power_color, TextAlign::TOP_RIGHT, - "%+.0f W", id(grid_power).state); - } else { - it.printf(308, 42, id(font_value), Color::WHITE, TextAlign::TOP_RIGHT, - "-- W"); + draw_page_title("Energie · Heute"); + const Color import_color(143, 190, 223); + const Color export_color(150, 110, 217); + const Color solar_color(255, 170, 40); + const Color grid_color(30, 38, 48); + const Color missing_color(85, 95, 110); + const bool connected = id(api_server).is_connected_with_state_subscription(); + const uint32_t day = now.is_valid() + ? now.year * 10000 + now.month * 100 + now.day_of_month : 0; + const char *labels[] = {"Bezug", "Einspeisung", "Solar"}; + const Color colors[] = {import_color, export_color, solar_color}; + sensor::Sensor *daily[] = {id(grid_import_energy_daily), + id(grid_export_energy_daily), id(solar_energy_daily)}; + + // The same three accents identify the totals and their hourly bars. + for (int channel = 0; channel < 3; channel++) { + const int x = 10 + channel * 102; + it.filled_rectangle(x, 39, 96, 64, Color(14, 20, 28)); + it.filled_rectangle(x, 39, 96, 2, colors[channel]); + it.print(x + 48, 46, id(font_device), colors[channel], TextAlign::TOP_CENTER, + labels[channel]); + if (connected && day != 0 && id(energy_daily_sample_day)[channel] == day + && daily[channel]->has_state() && std::isfinite(daily[channel]->state) + && daily[channel]->state >= 0.0f) { + it.printf(x + 48, 63, id(font_internet_value), Color::WHITE, + TextAlign::TOP_CENTER, "%.2f", daily[channel]->state); + } else { + it.print(x + 48, 63, id(font_internet_value), missing_color, + TextAlign::TOP_CENTER, "--"); + } + it.print(x + 48, 89, id(font_chart), colors[channel], TextAlign::TOP_CENTER, "kWh"); } + it.print(12, 108, id(font_device), Color::WHITE, "Stunden · kWh"); + it.print(308, 108, id(font_chart), missing_color, TextAlign::TOP_RIGHT, "lokal · Teildaten grau"); + const int left = 40, right = 304, top = 129, bottom = 193, step = 11, bar_width = 8; + const auto &history = id(energy_day_history); + const bool today = day != 0 && history.day() == day; + float positive_peak = 0.0f, negative_peak = 0.0f; + bool any_data = false; + for (int hour = 0; today && hour < 24; hour++) { + positive_peak = fmaxf(positive_peak, history.value(0, hour) + history.value(2, hour)); + negative_peak = fmaxf(negative_peak, history.value(1, hour)); + any_data |= history.has_data(0, hour) || history.has_data(1, hour) || history.has_data(2, hour); + } + // One kWh has the same height above and below zero; reserve space for export. + const float positive_max = gauge_maximum(positive_peak, 0.1f); + const float negative_max = gauge_maximum(negative_peak, positive_max / 3.0f); + const float pixels_per_kwh = (bottom - top) / (positive_max + negative_max); + const int zero = top + lroundf(positive_max * pixels_per_kwh); + for (int hour = 0; hour <= 24; hour += 6) { + const int x = left + hour * step; + it.line(x, top, x, bottom, grid_color); + it.printf(x, 199, id(font_chart), missing_color, + hour == 0 ? TextAlign::TOP_LEFT : hour == 24 ? TextAlign::TOP_RIGHT : TextAlign::TOP_CENTER, + "%02d", hour); + } + it.line(left, top, right, top, grid_color); + it.line(left, bottom, right, bottom, grid_color); + it.line(left, zero, right, zero, Color(75, 85, 100)); + it.printf(left - 5, top, id(font_chart), missing_color, TextAlign::CENTER_RIGHT, "%.2g", positive_max); + it.print(left - 5, zero, id(font_chart), Color::WHITE, TextAlign::CENTER_RIGHT, "0"); + it.printf(left - 5, bottom, id(font_chart), missing_color, TextAlign::CENTER_RIGHT, "-%.2g", negative_max); - if (id(grid_import_energy_daily).has_state()) { - it.printf(12, 96, id(font_small), Color::WHITE, "Bezug: %.2f kWh", - id(grid_import_energy_daily).state); - } else { - it.printf(12, 96, id(font_small), Color::WHITE, "Bezug: -- kWh"); + for (int hour = 0; today && hour <= now.hour; hour++) { + const int x = left + hour * step + 2; + const int solar_height = lroundf(history.value(2, hour) * pixels_per_kwh); + int import_height = lroundf(history.value(0, hour) * pixels_per_kwh); + if (solar_height + import_height > zero - top) import_height = zero - top - solar_height; + int export_height = lroundf(history.value(1, hour) * pixels_per_kwh); + if (export_height > bottom - zero) export_height = bottom - zero; + if (solar_height > 0) { + it.filled_rectangle(x, zero - solar_height, bar_width, solar_height, Color(165, 100, 22)); + it.line(x, zero - solar_height, x + bar_width - 1, zero - solar_height, solar_color); + } + if (import_height > 0) { + const int y = zero - solar_height - import_height; + it.filled_rectangle(x, y, bar_width, import_height, Color(56, 91, 118)); + it.line(x, y, x + bar_width - 1, y, import_color); + } + if (export_height > 0) { + it.filled_rectangle(x, zero + 1, bar_width, export_height, Color(80, 57, 113)); + it.line(x, zero + export_height, x + bar_width - 1, zero + export_height, export_color); + } + const uint32_t expected = hour < now.hour ? 3600 : now.minute * 60 + now.second; + if (!history.has_data(0, hour) || !history.has_data(1, hour) || !history.has_data(2, hour) + || history.coverage_seconds(0, hour) < expected || history.coverage_seconds(1, hour) < expected + || history.coverage_seconds(2, hour) < expected) { + it.line(x + 2, zero - 2, x + bar_width - 3, zero - 2, missing_color); + } } - if (id(grid_export_energy_daily).has_state()) { - it.printf(12, 116, id(font_small), Color::WHITE, "Einspeisung: %.2f kWh", - id(grid_export_energy_daily).state); - } else { - it.printf(12, 116, id(font_small), Color::WHITE, "Einspeisung: -- kWh"); + if (now.is_valid()) { + const int cursor_x = left + now.hour * step + (now.minute * 60 + now.second) * step / 3600; + for (int y = top; y < bottom; y += 5) { + it.line(cursor_x, y, cursor_x, y + 2, Color(110, 135, 155)); + } } - - it.printf(12, 138, id(font_small), Color::WHITE, "Balkonkraftwerk"); - // Daily solar energy is aligned to the left of the current solar-power reading. - if (id(solar_energy_daily).has_state()) { - it.printf(12, 180, id(font_small), Color(255, 170, 40), "Solar: %.2f kWh", - id(solar_energy_daily).state); - } else { - it.printf(12, 180, id(font_small), Color(255, 170, 40), "Solar: -- kWh"); - } - if (id(balcony_solar_power).has_state()) { - it.printf(308, 158, id(font_value), Color(255, 170, 40), TextAlign::TOP_RIGHT, - "%.0f W", id(balcony_solar_power).state); - } else { - it.printf(308, 168, id(font_value), Color(255, 170, 40), TextAlign::TOP_RIGHT, - "-- W"); + if (!any_data) { + it.print(172, 148, id(font_device), Color::WHITE, TextAlign::TOP_CENTER, + now.is_valid() ? "Stunden werden aufgezeichnet" : "Warte auf Zeitsynchronisation"); } } else if (id(page_index) == 0) { draw_page_title("Energie"); @@ -1102,8 +1260,8 @@ display: "Weiter >"); if (id(page_index) == 0) { it.printf(160, 239, id(font_small), Color::WHITE, TextAlign::BOTTOM_CENTER, - "%s · %d / 2", id(page_one_gauge_view) ? "Tacho" : "Werte", - id(page_one_gauge_view) ? 2 : 1); + "%s · %d / 2", id(page_one_gauge_view) ? "Tacho" : "Tag", + id(page_one_gauge_view) ? 1 : 2); } else if (id(page_index) == 1) { it.printf(160, 239, id(font_small), Color::WHITE, TextAlign::BOTTOM_CENTER, "Geräte · %d / 2", id(device_usage_view) + 1); diff --git a/esphome/tests/energy_day_history_test.cpp b/esphome/tests/energy_day_history_test.cpp new file mode 100644 index 0000000..34c9358 --- /dev/null +++ b/esphome/tests/energy_day_history_test.cpp @@ -0,0 +1,307 @@ +#include "../energy_day_history.h" + +#include +#include +#include +#include +#include + +static_assert(std::is_trivially_copyable::value, + "ESPHome restore_value requires trivially copyable state"); + +#define CHECK(condition) \ + do { \ + if (!(condition)) { \ + std::cerr << __FILE__ << ':' << __LINE__ << ": " #condition "\n"; \ + std::exit(EXIT_FAILURE); \ + } \ + } while (false) + +static bool near(float actual, float expected) { + return std::fabs(actual - expected) < 0.0001f; +} + +static void first_zero_and_ordinary() { + EnergyDayHistory h; + CHECK(h.day() == 0); + for (int c = 0; c < 3; ++c) { + for (int hour = 0; hour < 24; ++hour) { + CHECK(!h.has_data(c, hour)); + CHECK(h.value(c, hour) == 0.0f); + CHECK(h.coverage_seconds(c, hour) == 0); + } + h.observe(c, 1000.0f, 20261113, 8, 100, 1000); + CHECK(h.day() == 20261113); + CHECK(!h.has_data(c, 8)); // Lifetime totals are never bars. + CHECK(h.coverage_seconds(c, 8) == 0); + h.observe(c, 1000.0f, 20261113, 8, 110, 1010); + CHECK(h.has_data(c, 8)); + CHECK(h.value(c, 8) == 0.0f); + CHECK(h.coverage_seconds(c, 8) == 10); + h.observe(c, 1000.25f, 20261113, 8, 120, 1020); + h.observe(c, 1000.75f, 20261113, 8, 130, 1030); + CHECK(near(h.value(c, 8), 0.75f)); + CHECK(h.coverage_seconds(c, 8) == 30); + CHECK(!h.has_data(c, 7)); + CHECK(!h.has_data(c, 9)); + } +} + +static void hour_boundaries() { + EnergyDayHistory h; + h.observe(0, 10.0f, 20261113, 8, 3595, 1000); + h.observe(0, 10.4f, 20261113, 9, 15, 1020); + CHECK(near(h.value(0, 8), 0.1f)); + CHECK(near(h.value(0, 9), 0.3f)); + CHECK(h.coverage_seconds(0, 8) == 5); + CHECK(h.coverage_seconds(0, 9) == 15); + + h.observe(1, 5.0f, 20261113, 8, 3590, 1000); + h.observe(1, 5.2f, 20261113, 9, 0, 1010); + CHECK(h.has_data(1, 8)); + CHECK(near(h.value(1, 8), 0.2f)); + CHECK(!h.has_data(1, 9)); // No time in hour 9 has been observed yet. + CHECK(h.coverage_seconds(1, 8) == 10); + CHECK(h.coverage_seconds(1, 9) == 0); + h.observe(1, 5.2f, 20261113, 9, 10, 1020); + CHECK(h.has_data(1, 9)); + CHECK(h.value(1, 9) == 0.0f); + CHECK(h.coverage_seconds(1, 9) == 10); + + h.observe(2, 4.0f, 20261113, 8, 3595, 1000); + h.observe(2, 4.0f, 20261113, 9, 5, 1010); + CHECK(h.has_data(2, 8) && h.has_data(2, 9)); + CHECK(h.value(2, 8) == 0.0f && h.value(2, 9) == 0.0f); + CHECK(h.coverage_seconds(2, 8) == 5 && h.coverage_seconds(2, 9) == 5); +} + +static void midnight() { + EnergyDayHistory h; + h.observe(0, 10.0f, 20261231, 23, 3580, 1000); + h.observe(0, 10.1f, 20261231, 23, 3590, 1010); + h.observe(1, 20.0f, 20261231, 23, 3595, 1015); + h.observe(2, 30.0f, 20261231, 23, 3590, 1010); + h.observe(0, 10.5f, 20270101, 0, 10, 1030); + CHECK(h.day() == 20270101); + CHECK(h.coverage_seconds(0, 0) == 10); + for (int c = 0; c < 3; ++c) + CHECK(h.coverage_seconds(c, 23) == 0); + CHECK(near(h.value(0, 0), 0.2f)); + CHECK(!h.has_data(0, 23)); + // Baselines for the other channels survive the shared histogram reset. + h.observe(1, 20.6f, 20270101, 0, 15, 1035); + CHECK(near(h.value(1, 0), 0.45f)); + CHECK(h.coverage_seconds(1, 0) == 15); + CHECK(!h.has_data(1, 23)); + h.observe(2, 30.0f, 20270101, 0, 0, 1020); + CHECK(!h.has_data(2, 0)); + CHECK(h.coverage_seconds(2, 0) == 0); + h.observe(2, 30.0f, 20270101, 0, 10, 1030); + CHECK(h.has_data(2, 0)); + CHECK(h.value(2, 0) == 0.0f); + CHECK(h.coverage_seconds(2, 0) == 10); +} + +static void restored_copy() { + EnergyDayHistory original; + original.observe(0, 100.0f, 20261113, 10, 100, 1000); + original.observe(0, 100.5f, 20261113, 10, 110, 1010); + EnergyDayHistory restored = original; + restored.observe(0, 100.75f, 20261113, 10, 120, 1020); + CHECK(near(restored.value(0, 10), 0.75f)); + CHECK(near(original.value(0, 10), 0.5f)); + CHECK(restored.coverage_seconds(0, 10) == 20); + CHECK(original.coverage_seconds(0, 10) == 10); + + original.observe(1, 200.0f, 20261113, 23, 3590, 2000); + restored = original; + restored.observe(1, 200.4f, 20261114, 0, 10, 2020); + CHECK(near(restored.value(1, 0), 0.2f)); + CHECK(!restored.has_data(0, 10)); + CHECK(restored.coverage_seconds(0, 10) == 0); + CHECK(restored.coverage_seconds(1, 0) == 10); +} + +static void disconnected_and_invalid_totals() { + const float bad[] = {std::numeric_limits::quiet_NaN(), + std::numeric_limits::infinity(), + -std::numeric_limits::infinity(), -1.0f}; + for (float total : bad) { + EnergyDayHistory h; + h.observe(0, 10.0f, 20261113, 8, 100, 1000); + h.observe(1, 20.0f, 20261113, 8, 100, 1000); + h.observe(0, total, 20261113, 8, 110, 1010); + h.observe(0, 12.0f, 20261113, 8, 120, 1020); + CHECK(!h.has_data(0, 8)); + CHECK(h.coverage_seconds(0, 8) == 0); + h.observe(0, 12.25f, 20261113, 8, 130, 1030); + CHECK(near(h.value(0, 8), 0.25f)); + h.observe(1, 20.5f, 20261113, 8, 130, 1030); + CHECK(near(h.value(1, 8), 0.5f)); + h.observe(0, total, 20261113, 8, 140, 1040); + CHECK(near(h.value(0, 8), 0.25f)); // Existing data is preserved. + CHECK(h.coverage_seconds(0, 8) == 10); + CHECK(h.coverage_seconds(1, 8) == 30); + } +} + +static void gaps_and_counter_reset() { + EnergyDayHistory h; + h.observe(0, 10.0f, 20261113, 8, 3400, 1000); + h.observe(0, 11.0f, 20261113, 9, 101, 1301); + CHECK(!h.has_data(0, 8) && !h.has_data(0, 9)); + CHECK(h.coverage_seconds(0, 8) == 0 && h.coverage_seconds(0, 9) == 0); + h.observe(0, 11.25f, 20261113, 9, 111, 1311); + CHECK(near(h.value(0, 9), 0.25f)); + h.observe(0, 0.0f, 20261113, 9, 121, 1321); + CHECK(near(h.value(0, 9), 0.25f)); + CHECK(h.coverage_seconds(0, 9) == 10); + h.observe(0, 0.5f, 20261113, 9, 131, 1331); + CHECK(near(h.value(0, 9), 0.75f)); + CHECK(h.coverage_seconds(0, 9) == 20); + + h.observe(1, 5.0f, 20261113, 8, 100, 1000); + h.observe(1, 5.5f, 20261113, 8, 400, 1300); + CHECK(near(h.value(1, 8), 0.5f)); // Exactly 300 seconds is valid. + CHECK(h.coverage_seconds(1, 8) == 300); + h.observe(2, 5.0f, 20261113, 23, 3590, 1000); + h.observe(2, 9.0f, 20261114, 0, 291, 1301); + CHECK(h.day() == 20261114); + CHECK(!h.has_data(2, 0) && !h.has_data(2, 23)); + CHECK(h.coverage_seconds(1, 8) == 0); + CHECK(h.coverage_seconds(2, 0) == 0 && h.coverage_seconds(2, 23) == 0); +} + +static void clock_rewind() { + for (uint32_t timestamp : {1000u, 990u}) { + EnergyDayHistory h; + h.observe(0, 10.0f, 20261113, 8, 100, 1000); + h.observe(0, 11.0f, 20261113, 8, 90, timestamp); + CHECK(!h.has_data(0, 8)); + CHECK(h.coverage_seconds(0, 8) == 0); + h.observe(0, 11.25f, 20261113, 8, 100, timestamp + 10); + CHECK(near(h.value(0, 8), 0.25f)); + CHECK(h.coverage_seconds(0, 8) == 10); + } + EnergyDayHistory h; + h.observe(0, 10.0f, 20261113, 8, 100, 1000); + h.observe(0, 11.0f, 20261113, 8, 90, 1010); // Inconsistent local clock. + CHECK(!h.has_data(0, 8)); + CHECK(h.coverage_seconds(0, 8) == 0); + h.observe(0, 11.25f, 20261113, 8, 100, 1020); + CHECK(near(h.value(0, 8), 0.25f)); + CHECK(h.coverage_seconds(0, 8) == 10); +} + +static void dst() { + EnergyDayHistory fallback; + fallback.observe(0, 10.0f, 20261025, 2, 3580, 1000); + fallback.observe(0, 10.1f, 20261025, 2, 3590, 1010); + fallback.observe(0, 10.5f, 20261025, 2, 10, 1030); + CHECK(near(fallback.value(0, 2), 0.5f)); + CHECK(fallback.coverage_seconds(0, 2) == 30); + CHECK(!fallback.has_data(0, 1) && !fallback.has_data(0, 3)); + + EnergyDayHistory spring; + spring.observe(0, 10.0f, 20260329, 1, 3595, 1000); + spring.observe(0, 10.4f, 20260329, 3, 15, 1020); + CHECK(near(spring.value(0, 1), 0.1f)); + CHECK(!spring.has_data(0, 2)); + CHECK(near(spring.value(0, 3), 0.3f)); + CHECK(spring.coverage_seconds(0, 1) == 5); + CHECK(spring.coverage_seconds(0, 2) == 0); + CHECK(spring.coverage_seconds(0, 3) == 15); + + // A fully observed repeated hour contains two actual hours, not a capped 3600s. + EnergyDayHistory repeated; + for (int elapsed = 0; elapsed <= 7200; elapsed += 300) { + repeated.observe(0, 10.0f, 20261025, elapsed < 7200 ? 2 : 3, + elapsed % 3600, 1000 + elapsed); + if (elapsed == 3600) + CHECK(repeated.coverage_seconds(0, 2) == 3600); + } + CHECK(repeated.coverage_seconds(0, 2) == 7200); + CHECK(repeated.coverage_seconds(0, 3) == 0); +} + +static void invalid_inputs() { + EnergyDayHistory h; + for (int c : {-1, 3, 100}) { + h.observe(c, 10.0f, 20261113, 8, 100, 1000); + CHECK(!h.has_data(c, 8) && h.value(c, 8) == 0.0f); + CHECK(h.coverage_seconds(c, 8) == 0); + } + const uint32_t bad_days[] = {0, 20260001, 20261301, 20261100, 20261131, + 20260229, 19000229, 100000101}; + for (uint32_t day : bad_days) + h.observe(0, 10.0f, day, 8, 100, 1000); + for (int hour : {-1, 24, 100}) { + h.observe(0, 10.0f, 20261113, hour, 100, 1000); + CHECK(!h.has_data(0, hour) && h.value(0, hour) == 0.0f); + CHECK(h.coverage_seconds(0, hour) == 0); + } + for (int seconds : {-1, 3600, 10000}) + h.observe(0, 10.0f, 20261113, 8, seconds, 1000); + CHECK(h.day() == 0); + h.observe(0, 10.0f, 20000229, 8, 100, 1000); + CHECK(h.day() == 20000229); + CHECK(!h.has_data(0, 8)); + // Bad clock samples must not change the established baseline or day. + h.observe(0, 100.0f, 20261131, 8, 105, 1005); + h.observe(0, 100.0f, 20261113, 24, 105, 1005); + h.observe(0, 100.0f, 20261113, 8, -1, 1005); + CHECK(h.day() == 20000229); + h.observe(0, 10.25f, 20000229, 8, 110, 1010); + CHECK(near(h.value(0, 8), 0.25f)); + CHECK(h.coverage_seconds(0, 8) == 10); +} + +static void explicit_invalidation() { + EnergyDayHistory h; + h.invalidate(0); + CHECK(h.day() == 0); + CHECK(h.coverage_seconds(0, 8) == 0); + for (int c = 0; c < 3; ++c) { + h.observe(c, 10.0f, 20261113, 8, 100, 1000); + h.observe(c, 10.25f, 20261113, 8, 110, 1010); + } + h.invalidate(0); + h.invalidate(0); // Repeated invalidations are harmless. + CHECK(h.day() == 20261113); + CHECK(h.has_data(0, 8)); + CHECK(near(h.value(0, 8), 0.25f)); + CHECK(h.coverage_seconds(0, 8) == 10); + h.observe(0, 20.0f, 20261113, 8, 120, 1020); + CHECK(near(h.value(0, 8), 0.25f)); // First fresh receipt only rebaselines. + CHECK(h.coverage_seconds(0, 8) == 10); + h.observe(0, 20.5f, 20261113, 8, 130, 1030); + CHECK(near(h.value(0, 8), 0.75f)); + CHECK(h.coverage_seconds(0, 8) == 20); + + for (int c : {-1, 3, std::numeric_limits::min(), std::numeric_limits::max()}) { + h.invalidate(c); + CHECK(h.coverage_seconds(c, 8) == 0); + } + for (int c = 1; c < 3; ++c) { + h.observe(c, 10.5f, 20261113, 8, 120, 1020); + CHECK(near(h.value(c, 8), 0.5f)); // Other channel baselines are untouched. + CHECK(h.coverage_seconds(c, 8) == 20); + } + h.observe(0, 20.5f, 20261113, 8, 140, 1040); + CHECK(near(h.value(0, 8), 0.75f)); + CHECK(h.coverage_seconds(0, 8) == 30); +} + +int main() { + first_zero_and_ordinary(); + hour_boundaries(); + midnight(); + restored_copy(); + disconnected_and_invalid_totals(); + gaps_and_counter_reset(); + clock_rewind(); + dst(); + invalid_inputs(); + explicit_invalidation(); + std::cout << "All 10 energy day history test groups passed.\n"; +}