mirror of
https://github.com/Akkudoktor-EOS/EOS.git
synced 2026-11-25 23:16:18 +01:00
feat(measurement): add typed energy, quality and capacity APIs (#1326)
* feat: adapt configuration for multi optimization algorithms Decouple configuration from optimization algorithm parameters. Add to_[algorithm]_param() methods to the configuration that derive optimization algorithm specific parameters from the configuration. Add x-scope tags to the configuration options that describe for which specific algorithms the configuration option is for. The whole device settings are restructured. There are now general settings for the device classes with the afore mentioned to_[algorithm]_param() methods. The general device settings got their own directory `devices/settings`. By this the parameter class also does not have to be a pydantic model which can be used for future optimization/ simulations speed up. Also the parameter class for a device is now part of the device module. This better decouples and also is the natural place for parameters of a device. Besides this feature there are also fixes and improvements: * feat: extend home appliance time window settings and simulation Home appliance can now be configured for multiple runs with per-cycle allowed time windows. The number of remaining cycles to plan is determined at runtime by reading the ``cycles_completed_measurement_key`` from the measurement store. * feat: specialiced CycleTimeWindowSequence for time window sequences Sequence of time windows associated to cycles. This model specializes ``ValueTimeWindowSequence`` so that the ``value`` field of each ``ValueTimeWindow`` encodes the **cycle index** (0-based integer) the window belongs to. Typical use: an appliance that must run ``n`` times per day, each run constrained to a distinct time window. Assign ``value=0`` to windows for the first cycle, ``value=1`` for the second, and so on. Multiple windows may share the same cycle index (their allowed regions are unioned). Windows with ``value=None`` are silently ignored by all cycle-aware methods. * fix: Make test_configmigrate also regard the _ANY_SENTENIEL in key values * chore: Make devices configurations a map instead of a list This makes config paths stable regardless of declaration order and lets each device settings class build its own config path from ``self.device_id`` without needing an external index. Tests are adapted likewise. Devices configurations are automatically migrated from lists to maps. * chore: rename levelized_cost_of_storage_kwh to levelized_cost_of_storage_amt kwh This better fits in the naming scheme and also makes clear the costs are money. Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com> * fix: runtime config update ignored by config file Runtime settings were handed back to pydantic-settings as init settings, which rank below the config file and the environment. Any key already present in EOS.config.json or in the environment silently discarded the update, so a bulk PUT /v1/config returned 200 without applying anything, while the granular PUT /v1/config/{path} endpoint kept working. Add a dedicated runtime settings source ranked directly below the command line arguments and record granular updates there as well, so both endpoints share one store that survives re-evaluation of the settings sources. Environment variables keep precedence over the config file for all keys that were not set at runtime. Also repairs revert_settings() and update(), which passed their data through the same init settings. Closes #1303 * fix: env vars ignored on first config build ConfigEOS.__init__ passed self as first positional argument to _setup, which forwards it to pydantic_settings.BaseSettings.__init__. Its first positional parameter is _case_sensitive, so the environment source matched the upper case variable names against the lower case field names and returned nothing. Environment settings only took effect after the next configuration setup. * docs: changelog for config priority fixes * fix(config): preserve device identities and storage costs during migration * fix(measurement): restore JSON records into the existing singleton * fix(devices): preserve charge-rate typing and public import compatibility * feat(measurement): integrate typed energy quality and capacity APIs Port the locally backed-up measurement extensions to main async storage and PR #1256 device maps. Preserve runtime capacity estimates across #1305 bulk updates. Confirm JSON singleton restore defect on unchanged main and add regression. No production configuration or measurements included. Co-authored-by: Andreas <drbacke@gmx.de> * docs(measurement): describe household settings and consolidate regression coverage * docs(measurement): regenerate configuration and API contracts * test(measurement): isolate capacity database state between tests * ruff format fix * test(measurement): assert restored timestamps before timezone conversion * docs(measurement): align API version with refreshed prerequisites * fix(config): satisfy typed device conversion and migration contracts * docs(config): refresh validated configuration prerequisite schemas * fix(measurement): enforce typed capacity and sample validation * style(measurement): normalize imports for CI * docs(measurement): refresh typed measurement API schemas --------- Signed-off-by: Bobby Noelte <b0661n0e17e@gmail.com> Co-authored-by: Bobby Noelte <b0661n0e17e@gmail.com> Co-authored-by: r0b2g1t <r0b2g1t@users.noreply.github.com>
This commit is contained in:
co-authored by
Andreas
Bobby Noelte
r0b2g1t
parent
8224c64654
commit
1a18935667
@@ -80,6 +80,7 @@ from akkudoktoreos.server.rest.error import (
|
||||
create_error_page,
|
||||
register_problem_handlers,
|
||||
)
|
||||
from akkudoktoreos.server.rest.measurement import router as measurement_router
|
||||
from akkudoktoreos.server.rest.starteosdash import supervise_eosdash
|
||||
from akkudoktoreos.server.retentionmanager import RetentionManager
|
||||
from akkudoktoreos.server.server import (
|
||||
@@ -261,6 +262,8 @@ The genetic optimization API fields were renamed from German to English. For bac
|
||||
# Application generic exception handling
|
||||
# ----------------------
|
||||
|
||||
app.include_router(measurement_router)
|
||||
|
||||
register_problem_handlers(app)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Typed samples and derived energy within the existing measurement API."""
|
||||
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Body, HTTPException, Query
|
||||
from pydantic import AwareDatetime
|
||||
|
||||
from akkudoktoreos.core.coreabc import get_config, get_measurement
|
||||
from akkudoktoreos.core.databaseabc import DatabaseTimestamp
|
||||
from akkudoktoreos.measurement.batterycapacity import (
|
||||
BatteryCapacityEstimate,
|
||||
BatteryCapacityRequest,
|
||||
)
|
||||
from akkudoktoreos.measurement.energy import EnergyInterval
|
||||
from akkudoktoreos.measurement.quality import MeasurementSample, SampleQuality
|
||||
from akkudoktoreos.utils.datetimeutil import to_datetime
|
||||
|
||||
router = APIRouter(prefix="/v1/measurement", tags=["measurement"])
|
||||
|
||||
|
||||
@router.post("/battery-capacity/{battery_id}", response_model=BatteryCapacityEstimate)
|
||||
async def post_battery_capacity(
|
||||
battery_id: str, request: BatteryCapacityRequest
|
||||
) -> BatteryCapacityEstimate:
|
||||
"""Estimate capacity from independent SoC anchors and configured DC power.
|
||||
|
||||
store_estimate writes the separate capacity_estimate config field in memory.
|
||||
Persistence follows the regular EOS configuration save mechanism.
|
||||
The active capacity_wh and raw measurements are never changed here.
|
||||
"""
|
||||
try:
|
||||
estimate = await get_measurement().estimate_battery_capacity(battery_id, request)
|
||||
if request.store_estimate:
|
||||
batteries = [
|
||||
b
|
||||
for b in (get_config().devices.batteries or {}).values()
|
||||
if b.device_id == battery_id
|
||||
]
|
||||
if len(batteries) != 1:
|
||||
raise ValueError("Battery configuration changed during estimation; retry.")
|
||||
get_config().set_nested_value(
|
||||
f"devices/batteries/{battery_id}/capacity_estimate", estimate
|
||||
)
|
||||
return estimate
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
|
||||
|
||||
@router.put("/samples")
|
||||
async def put_samples(
|
||||
samples: Annotated[list[MeasurementSample], Body(max_length=10000)],
|
||||
) -> dict[str, int]:
|
||||
"""Upsert raw values and their quality; legacy value/series payloads remain valid."""
|
||||
try:
|
||||
await get_measurement().import_samples(samples)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
return {"updated": len(samples)}
|
||||
|
||||
|
||||
@router.get("/samples", response_model=list[MeasurementSample])
|
||||
async def get_samples(
|
||||
key: str, start: AwareDatetime, end: AwareDatetime
|
||||
) -> list[MeasurementSample]:
|
||||
"""Read raw samples including quality, in a bounded half-open range."""
|
||||
measurement = get_measurement()
|
||||
try:
|
||||
measurement._energy_channel(key)
|
||||
if not 0 < end.timestamp() - start.timestamp() <= 31 * 86400:
|
||||
raise ValueError("Require a positive range of at most 31 days.")
|
||||
result = []
|
||||
async for record in measurement.db_iterate_records(
|
||||
DatabaseTimestamp.from_datetime(to_datetime(start)),
|
||||
DatabaseTimestamp.from_datetime(to_datetime(end)),
|
||||
):
|
||||
if key in record.configured_data and record.date_time is not None:
|
||||
result.append(
|
||||
MeasurementSample(
|
||||
date_time=record.date_time,
|
||||
key=key,
|
||||
value=record.configured_data[key],
|
||||
quality=record.sample_quality.get(key, SampleQuality()),
|
||||
)
|
||||
)
|
||||
if len(result) > 10000:
|
||||
raise ValueError("More than 10000 samples; request a shorter range.")
|
||||
return result
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
|
||||
|
||||
@router.get("/energy", response_model=list[EnergyInterval])
|
||||
async def get_energy(
|
||||
key: str,
|
||||
start: AwareDatetime,
|
||||
end: AwareDatetime,
|
||||
interval_seconds: Annotated[int, Query(gt=0)] = 900,
|
||||
) -> list[EnergyInterval]:
|
||||
"""Energy in Wh, with temporal coverage and quality; no missing-to-zero filling."""
|
||||
try:
|
||||
return await get_measurement().energy_intervals(key, start, end, interval_seconds)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
|
||||
|
||||
@router.get("/household", response_model=dict[str, list[EnergyInterval]])
|
||||
async def get_household(
|
||||
start: AwareDatetime, end: AwareDatetime, interval_seconds: Annotated[int, Query(gt=0)] = 900
|
||||
) -> dict[str, list[EnergyInterval]]:
|
||||
"""Site, household without EV, and base without separately measured devices."""
|
||||
try:
|
||||
return await get_measurement().household_intervals(start, end, interval_seconds)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
Reference in New Issue
Block a user