Merge branch 'main' of git.commander1024.de:Commander1024/homeassistant-config

This commit is contained in:
2026-11-13 11:38:16 +01:00
3 changed files with 622 additions and 38 deletions
+119
View File
@@ -0,0 +1,119 @@
#pragma once
#include <cmath>
#include <cstdint>
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<int>(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<uint32_t>(3600 - previous.seconds);
const float before_delta = delta * (static_cast<float>(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<uint32_t>(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] = {};
};
+194 -36
View File
@@ -12,6 +12,10 @@ esphome:
project: project:
name: monitor.energymonitor name: monitor.energymonitor
version: "1.0" version: "1.0"
includes:
# ESPHome emits angle-bracket includes before globals; the local entry copies the header.
- <energy_day_history.h>
- energy_day_history.h
on_boot: on_boot:
then: then:
- light.turn_on: display_backlight - light.turn_on: display_backlight
@@ -102,6 +106,13 @@ api:
id: api_server id: api_server
encryption: encryption:
key: !secret apikey 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: ota:
platform: esphome platform: esphome
@@ -173,6 +184,12 @@ font:
glyphsets: glyphsets:
- GF_Latin_Kernel - GF_Latin_Kernel
glyphs: ["äöüÄÖÜß"] glyphs: ["äöüÄÖÜß"]
- file: "fonts/Roboto-Regular.ttf"
id: font_chart
size: 10
glyphsets:
- GF_Latin_Kernel
glyphs: ["äöüÄÖÜß"]
- file: "fonts/materialdesignicons-webfont.ttf" - file: "fonts/materialdesignicons-webfont.ttf"
id: font_icon id: font_icon
size: 24 size: 24
@@ -201,7 +218,19 @@ globals:
- id: page_one_gauge_view - id: page_one_gauge_view
type: bool type: bool
restore_value: true 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<bool, 3>
restore_value: false
initial_value: 'std::array<bool, 3>{}'
- id: energy_daily_sample_day
type: std::array<uint32_t, 3>
restore_value: false
initial_value: 'std::array<uint32_t, 3>{}'
- id: clock_digital_view - id: clock_digital_view
type: bool type: bool
restore_value: true restore_value: true
@@ -314,14 +343,48 @@ sensor:
id: solar_energy_daily id: solar_energy_daily
entity_id: sensor.energy_solar_daily entity_id: sensor.energy_solar_daily
internal: true internal: true
on_value:
- script.execute:
id: record_daily_energy_received
channel: 2
value: !lambda return x;
- platform: homeassistant - platform: homeassistant
id: grid_import_energy_daily id: grid_import_energy_daily
entity_id: sensor.energy_import_daily entity_id: sensor.energy_import_daily
internal: true internal: true
on_value:
- script.execute:
id: record_daily_energy_received
channel: 0
value: !lambda return x;
- platform: homeassistant - platform: homeassistant
id: grid_export_energy_daily id: grid_export_energy_daily
entity_id: sensor.energy_export_daily entity_id: sensor.energy_export_daily
internal: true 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 - platform: homeassistant
id: hallway_fragrance_power id: hallway_fragrance_power
entity_id: sensor.flur_raumduft_power entity_id: sensor.flur_raumduft_power
@@ -455,7 +518,42 @@ interval:
id(climate_history_next) = (climate_slot + 1) % 361; id(climate_history_next) = (climate_slot + 1) % 361;
if (id(climate_history_count) < 361) id(climate_history_count)++; 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: 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 - id: refresh_display
then: then:
# The partial-buffer driver draws multiple strips; freeze time for the entire frame. # The partial-buffer driver draws multiple strips; freeze time for the entire frame.
@@ -603,46 +701,106 @@ display:
}; };
if (id(page_index) == 0 && !id(page_one_gauge_view)) { if (id(page_index) == 0 && !id(page_one_gauge_view)) {
draw_page_title("Netzleistung"); draw_page_title("Energie · Heute");
if (id(grid_power).has_state()) { const Color import_color(143, 190, 223);
const Color grid_power_color = id(grid_power).state >= 0 const Color export_color(150, 110, 217);
? Color(143, 190, 223) // #8FBEDF: positive grid power const Color solar_color(255, 170, 40);
: Color(150, 110, 217); // #966ED9: negative grid power const Color grid_color(30, 38, 48);
it.printf(308, 32, id(font_value), grid_power_color, TextAlign::TOP_RIGHT, const Color missing_color(85, 95, 110);
"%+.0f W", id(grid_power).state); 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 { } else {
it.printf(308, 42, id(font_value), Color::WHITE, TextAlign::TOP_RIGHT, it.print(x + 48, 63, id(font_internet_value), missing_color,
"-- W"); 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()) { for (int hour = 0; today && hour <= now.hour; hour++) {
it.printf(12, 96, id(font_small), Color::WHITE, "Bezug: %.2f kWh", const int x = left + hour * step + 2;
id(grid_import_energy_daily).state); const int solar_height = lroundf(history.value(2, hour) * pixels_per_kwh);
} else { int import_height = lroundf(history.value(0, hour) * pixels_per_kwh);
it.printf(12, 96, id(font_small), Color::WHITE, "Bezug: -- 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 (id(grid_export_energy_daily).has_state()) { if (import_height > 0) {
it.printf(12, 116, id(font_small), Color::WHITE, "Einspeisung: %.2f kWh", const int y = zero - solar_height - import_height;
id(grid_export_energy_daily).state); it.filled_rectangle(x, y, bar_width, import_height, Color(56, 91, 118));
} else { it.line(x, y, x + bar_width - 1, y, import_color);
it.printf(12, 116, id(font_small), Color::WHITE, "Einspeisung: -- kWh");
} }
if (export_height > 0) {
it.printf(12, 138, id(font_small), Color::WHITE, "Balkonkraftwerk"); it.filled_rectangle(x, zero + 1, bar_width, export_height, Color(80, 57, 113));
// Daily solar energy is aligned to the left of the current solar-power reading. it.line(x, zero + export_height, x + bar_width - 1, zero + export_height, export_color);
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()) { const uint32_t expected = hour < now.hour ? 3600 : now.minute * 60 + now.second;
it.printf(308, 158, id(font_value), Color(255, 170, 40), TextAlign::TOP_RIGHT, if (!history.has_data(0, hour) || !history.has_data(1, hour) || !history.has_data(2, hour)
"%.0f W", id(balcony_solar_power).state); || history.coverage_seconds(0, hour) < expected || history.coverage_seconds(1, hour) < expected
} else { || history.coverage_seconds(2, hour) < expected) {
it.printf(308, 168, id(font_value), Color(255, 170, 40), TextAlign::TOP_RIGHT, it.line(x + 2, zero - 2, x + bar_width - 3, zero - 2, missing_color);
"-- W"); }
}
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));
}
}
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) { } else if (id(page_index) == 0) {
draw_page_title("Energie"); draw_page_title("Energie");
@@ -1104,8 +1262,8 @@ display:
"Weiter >"); "Weiter >");
if (id(page_index) == 0) { if (id(page_index) == 0) {
it.printf(160, 239, id(font_small), Color::WHITE, TextAlign::BOTTOM_CENTER, it.printf(160, 239, id(font_small), Color::WHITE, TextAlign::BOTTOM_CENTER,
"%s · %d / 2", id(page_one_gauge_view) ? "Tacho" : "Werte", "%s · %d / 2", id(page_one_gauge_view) ? "Tacho" : "Tag",
id(page_one_gauge_view) ? 2 : 1); id(page_one_gauge_view) ? 1 : 2);
} else if (id(page_index) == 1) { } else if (id(page_index) == 1) {
it.printf(160, 239, id(font_small), Color::WHITE, TextAlign::BOTTOM_CENTER, it.printf(160, 239, id(font_small), Color::WHITE, TextAlign::BOTTOM_CENTER,
"Geräte · %d / 2", id(device_usage_view) + 1); "Geräte · %d / 2", id(device_usage_view) + 1);
+307
View File
@@ -0,0 +1,307 @@
#include "../energy_day_history.h"
#include <cmath>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <type_traits>
static_assert(std::is_trivially_copyable<EnergyDayHistory>::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<float>::quiet_NaN(),
std::numeric_limits<float>::infinity(),
-std::numeric_limits<float>::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<int>::min(), std::numeric_limits<int>::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";
}