From bd38b3c5eff539e9eb37ba352a8d60d77c4d92dc Mon Sep 17 00:00:00 2001 From: Bobby Noelte Date: Tue, 10 Jun 2025 22:00:28 +0200 Subject: [PATCH] fix: logging, prediction update, multiple bugs (#584) * Fix logging configuration issues that made logging stop operation. Switch to Loguru logging (from Python logging). Enable console and file logging with different log levels. Add logging documentation. * Fix logging configuration and EOS configuration out of sync. Added tracking support for nested value updates of Pydantic models. This used to update the logging configuration when the EOS configurationm for logging is changed. Should keep logging config and EOS config in sync as long as all changes to the EOS logging configuration are done by set_nested_value(), which is the case for the REST API. * Fix energy management task looping endlessly after the second update when trying to update the last_update datetime. * Fix get_nested_value() to correctly take values from the dicts in a Pydantic model instance. * Fix usage of model classes instead of model instances in nested value access when evaluation the value type that is associated to each key. * Fix illegal json format in prediction documentation for PVForecastAkkudoktor provider. * Fix documentation qirks and add EOS Connect to integrations. * Support deprecated fields in configuration in documentation generation and EOSdash. * Enhance EOSdash demo to show BrightSky humidity data (that is often missing) * Update documentation reference to German EOS installation videos. Signed-off-by: Bobby Noelte --- Makefile | 5 + docs/_generated/config.md | 24 +- docs/_generated/openapi.md | 49 + docs/akkudoktoreos/architecture.md | 2 +- docs/akkudoktoreos/integration.md | 9 +- docs/akkudoktoreos/introduction.md | 2 +- docs/akkudoktoreos/logging.md | 75 + docs/akkudoktoreos/prediction.md | 8 +- docs/index.md | 1 + openapi.json | 9428 +++++++++-------- requirements.txt | 1 + scripts/generate_config_md.py | 21 +- scripts/generate_openapi.py | 3 + single_test_optimization.py | 3 - src/akkudoktoreos/config/config.py | 18 +- src/akkudoktoreos/core/cache.py | 5 +- src/akkudoktoreos/core/coreabc.py | 5 +- src/akkudoktoreos/core/dataabc.py | 4 +- src/akkudoktoreos/core/decorators.py | 4 - src/akkudoktoreos/core/ems.py | 17 +- src/akkudoktoreos/core/logabc.py | 19 +- src/akkudoktoreos/core/logging.py | 294 +- src/akkudoktoreos/core/logsettings.py | 62 +- src/akkudoktoreos/core/pydantic.py | 283 +- src/akkudoktoreos/devices/battery.py | 3 - src/akkudoktoreos/devices/devices.py | 3 - src/akkudoktoreos/devices/devicesabc.py | 4 +- src/akkudoktoreos/devices/generic.py | 3 - src/akkudoktoreos/devices/heatpump.py | 9 +- src/akkudoktoreos/devices/inverter.py | 4 +- src/akkudoktoreos/devices/settings.py | 3 - src/akkudoktoreos/measurement/measurement.py | 4 +- src/akkudoktoreos/optimization/genetic.py | 4 +- .../optimization/optimization.py | 3 - .../optimization/optimizationabc.py | 3 - src/akkudoktoreos/prediction/elecpriceabc.py | 3 - .../prediction/elecpriceakkudoktor.py | 4 +- .../prediction/elecpriceimport.py | 4 +- src/akkudoktoreos/prediction/load.py | 2 - src/akkudoktoreos/prediction/loadabc.py | 3 - .../prediction/loadakkudoktor.py | 4 +- src/akkudoktoreos/prediction/loadimport.py | 4 +- src/akkudoktoreos/prediction/predictionabc.py | 4 +- src/akkudoktoreos/prediction/pvforecast.py | 2 - src/akkudoktoreos/prediction/pvforecastabc.py | 4 +- .../prediction/pvforecastakkudoktor.py | 4 +- .../prediction/pvforecastimport.py | 4 +- src/akkudoktoreos/prediction/weatherabc.py | 3 - .../prediction/weatherbrightsky.py | 5 +- .../prediction/weatherclearoutside.py | 5 +- src/akkudoktoreos/prediction/weatherimport.py | 4 +- src/akkudoktoreos/server/dash/admin.py | 4 +- src/akkudoktoreos/server/dash/components.py | 19 +- .../server/dash/configuration.py | 12 +- src/akkudoktoreos/server/dash/demo.py | 33 +- src/akkudoktoreos/server/dash/footer.py | 3 +- src/akkudoktoreos/server/eos.py | 127 +- src/akkudoktoreos/server/eosdash.py | 3 +- src/akkudoktoreos/server/server.py | 4 +- src/akkudoktoreos/utils/datetimeutil.py | 18 +- src/akkudoktoreos/utils/docs.py | 2 + src/akkudoktoreos/utils/utils.py | 3 - src/akkudoktoreos/utils/visualize.py | 15 +- tests/conftest.py | 81 +- tests/test_config.py | 4 +- tests/test_dataabc.py | 6 +- tests/test_elecpriceakkudoktor.py | 8 +- tests/test_logging.py | 80 +- tests/test_pvforecastakkudoktor.py | 4 +- tests/test_pydantic.py | 92 +- 70 files changed, 5927 insertions(+), 5035 deletions(-) create mode 100644 docs/akkudoktoreos/logging.md diff --git a/Makefile b/Makefile index ca33346..4529c96 100644 --- a/Makefile +++ b/Makefile @@ -76,6 +76,11 @@ read-docs: docs @echo "Read the documentation in your browser" .venv/bin/python -m webbrowser build/docs/html/index.html +# Clean Python bytecode +clean-bytecode: + find . -type d -name "__pycache__" -exec rm -r {} + + find . -type f -name "*.pyc" -delete + # Clean target to remove generated documentation and documentation artefacts clean-docs: @echo "Searching and deleting all '_autosum' directories in docs..." diff --git a/docs/_generated/config.md b/docs/_generated/config.md index e265e82..b47d2f0 100644 --- a/docs/_generated/config.md +++ b/docs/_generated/config.md @@ -15,10 +15,6 @@ Properties: timezone (Optional[str]): Computed time zone string based on the specified latitude and longitude. -Validators: - validate_latitude (float): Ensures `latitude` is within the range -90 to 90. - validate_longitude (float): Ensures `longitude` is within the range -180 to 180. - :::{table} general :widths: 10 20 10 5 5 30 :align: left @@ -127,8 +123,10 @@ Validators: | Name | Environment Variable | Type | Read-Only | Default | Description | | ---- | -------------------- | ---- | --------- | ------- | ----------- | -| level | `EOS_LOGGING__LEVEL` | `Optional[str]` | `rw` | `None` | EOS default logging level. | -| root_level | | `str` | `ro` | `N/A` | Root logger logging level. | +| level | `EOS_LOGGING__LEVEL` | `Optional[str]` | `rw` | `None` | This is deprecated. Use console_level and file_level instead. | +| console_level | `EOS_LOGGING__CONSOLE_LEVEL` | `Optional[str]` | `rw` | `None` | Logging level when logging to console. | +| file_level | `EOS_LOGGING__FILE_LEVEL` | `Optional[str]` | `rw` | `None` | Logging level when logging to file. | +| file_path | | `Optional[pathlib.Path]` | `ro` | `N/A` | Computed log file path based on data output path. | ::: ### Example Input @@ -138,7 +136,9 @@ Validators: { "logging": { - "level": "INFO" + "level": null, + "console_level": "TRACE", + "file_level": "TRACE" } } ``` @@ -150,8 +150,10 @@ Validators: { "logging": { - "level": "INFO", - "root_level": "INFO" + "level": null, + "console_level": "TRACE", + "file_level": "TRACE", + "file_path": "/home/user/.local/share/net.akkudoktoreos.net/output/eos.log" } } ``` @@ -946,7 +948,9 @@ Validators: "interval": 300.0 }, "logging": { - "level": "INFO" + "level": null, + "console_level": "TRACE", + "file_level": "TRACE" }, "devices": { "batteries": [ diff --git a/docs/_generated/openapi.md b/docs/_generated/openapi.md index 8ff941f..554ad1b 100644 --- a/docs/_generated/openapi.md +++ b/docs/_generated/openapi.md @@ -464,6 +464,55 @@ Health check endpoint to verify that the EOS server is alive. --- +## GET /v1/logging/log + +**Links**: [local](http://localhost:8503/docs#/default/fastapi_logging_get_log_v1_logging_log_get), [eos](https://petstore3.swagger.io/?url=https://raw.githubusercontent.com/Akkudoktor-EOS/EOS/refs/heads/main/openapi.json#/default/fastapi_logging_get_log_v1_logging_log_get) + +Fastapi Logging Get Log + +``` +Get structured log entries from the EOS log file. + +Filters and returns log entries based on the specified query parameters. The log +file is expected to contain newline-delimited JSON entries. + +Args: + limit (int): Maximum number of entries to return. + level (Optional[str]): Filter logs by severity level (e.g., DEBUG, INFO). + contains (Optional[str]): Return only logs that include this string in the message. + regex (Optional[str]): Return logs that match this regular expression in the message. + from_time (Optional[str]): ISO 8601 timestamp to filter logs not older than this. + to_time (Optional[str]): ISO 8601 timestamp to filter logs not newer than this. + tail (bool): If True, fetch the most recent log entries (like `tail`). + +Returns: + JSONResponse: A JSON list of log entries. +``` + +**Parameters**: + +- `limit` (query, optional): Maximum number of log entries to return. + +- `level` (query, optional): Filter by log level (e.g., INFO, ERROR). + +- `contains` (query, optional): Filter logs containing this substring. + +- `regex` (query, optional): Filter logs by matching regex in message. + +- `from_time` (query, optional): Start time (ISO format) for filtering logs. + +- `to_time` (query, optional): End time (ISO format) for filtering logs. + +- `tail` (query, optional): If True, returns the most recent lines (tail mode). + +**Responses**: + +- **200**: Successful Response + +- **422**: Validation Error + +--- + ## PUT /v1/measurement/data **Links**: [local](http://localhost:8503/docs#/default/fastapi_measurement_data_put_v1_measurement_data_put), [eos](https://petstore3.swagger.io/?url=https://raw.githubusercontent.com/Akkudoktor-EOS/EOS/refs/heads/main/openapi.json#/default/fastapi_measurement_data_put_v1_measurement_data_put) diff --git a/docs/akkudoktoreos/architecture.md b/docs/akkudoktoreos/architecture.md index c4c4c63..047ac9c 100644 --- a/docs/akkudoktoreos/architecture.md +++ b/docs/akkudoktoreos/architecture.md @@ -28,7 +28,7 @@ management. Energy management is the overall process to provide planning data for scheduling the different devices in your system in an optimal way. Energy management cares for the update of predictions and the optimization of the planning based on the simulated behavior of the devices. The planning is on -the hour. Sub-hour energy management is left +the hour. ### Optimization diff --git a/docs/akkudoktoreos/integration.md b/docs/akkudoktoreos/integration.md index c2d1793..f479d23 100644 --- a/docs/akkudoktoreos/integration.md +++ b/docs/akkudoktoreos/integration.md @@ -20,8 +20,8 @@ Andreas Schmitz uses [Node-RED](https://nodered.org/) as part of his home automa ### Node-Red Resources -- [Installation Guide (German)](https://meintechblog.de/2024/09/05/andreas-schmitz-joerg-installiert-mein-energieoptimierungssystem/) - \— A detailed guide on integrating an early version of EOS with `Node-RED`. +- [Installation Guide (German)](https://www.youtube.com/playlist?list=PL8_vk9A-s7zLD865Oou6y3EeQLlNtu-Hn) + \— A detailed guide on integrating EOS with `Node-RED`. ## Home Assistant @@ -34,3 +34,8 @@ emphasizes local control and user privacy. - Duetting's [EOS Home Assistant Addon](https://github.com/Duetting/ha_eos_addon) — Additional details can be found in this [discussion thread](https://github.com/Akkudoktor-EOS/EOS/discussions/294). + +## EOS Connect + +[EOS connect](https://github.com/ohAnd/EOS_connect) uses `EOS` for energy management and optimization, +and connects to smart home platforms to monitor, forecast, and control energy flows. diff --git a/docs/akkudoktoreos/introduction.md b/docs/akkudoktoreos/introduction.md index 5d9da2e..264ab48 100644 --- a/docs/akkudoktoreos/introduction.md +++ b/docs/akkudoktoreos/introduction.md @@ -174,7 +174,7 @@ but usually find good local optima very quickly in a large solution space. ## Links -- [German Video explaining the basic concept and installation process for the early version of EOS (YouTube)](https://www.youtube.com/live/ftQULW4-1ts?si=oDdBBifCpUmiCXaY) +- [German Videos explaining the basic concept and installation process of EOS (YouTube)](https://www.youtube.com/playlist?list=PL8_vk9A-s7zLD865Oou6y3EeQLlNtu-Hn) - [German Forum of Akkudoktor EOS](https://akkudoktor.net/c/der-akkudoktor/eos) - [Akkudoktor-EOS GitHub Repository](https://github.com/Akkudoktor-EOS/EOS) - [Latest EOS Documentation](https://akkudoktor-eos.readthedocs.io/en/latest/) diff --git a/docs/akkudoktoreos/logging.md b/docs/akkudoktoreos/logging.md new file mode 100644 index 0000000..79f72f1 --- /dev/null +++ b/docs/akkudoktoreos/logging.md @@ -0,0 +1,75 @@ +% SPDX-License-Identifier: Apache-2.0 +(logging-page)= + +# Logging + +EOS automatically records important events and messages to help you understand what’s happening and +to troubleshoot problems. + +## How Logging Works + +- By default, logs are shown in your terminal (console). +- You can also save logs to a file for later review. +- Log files are rotated automatically to avoid becoming too large. + +## Controlling Log Details + +### 1. Command-Line Option + +Set the amount of log detail shown on the console by using `--log-level` when starting EOS. + +Example: + +```{eval-rst} +.. tabs:: + + .. tab:: Windows + + .. code-block:: powershell + + .venv\Scripts\python src/akkudoktoreos/server/eos.py --log-level DEBUG + + .. tab:: Linux + + .. code-block:: bash + + .venv/bin/python src/akkudoktoreos/server/eos.py --log-level DEBUG + +``` + +Common levels: + +- DEBUG (most detail) +- INFO (default) +- WARNING +- ERROR +- CRITICAL (least detail) + +### 2. Configuration File + +You can also set logging options in your EOS configuration file (EOS.config.json). + +```Json +{ + "logging": { + "console_level": "INFO", + "file_level": "DEBUG" + } +} +``` + +### 3. Environment Variable + +You can also control the log level by setting the `EOS_LOGGING__CONSOLE_LEVEL` and the +`EOS_LOGGING__FILE_LEVEL` environment variables. + +```bash + EOS_LOGGING__CONSOLE_LEVEL="INFO" + EOS_LOGGING__FILE_LEVEL="DEBUG" +``` + +## File Logging + +If the `file_level` configuration is set, log records are written to a rotating log file. The log +file is in the data output directory and named `eos.log`. You may directly read the file or use +the `/v1/logging/log` endpoint to access the file log. diff --git a/docs/akkudoktoreos/prediction.md b/docs/akkudoktoreos/prediction.md index f5c161a..734b9ad 100644 --- a/docs/akkudoktoreos/prediction.md +++ b/docs/akkudoktoreos/prediction.md @@ -375,28 +375,28 @@ Example: "surface_azimuth": -10, "surface_tilt": 7, "userhorizon": [20, 27, 22, 20], - "inverter_paco": 10000, + "inverter_paco": 10000 }, { "peakpower": 4.8, "surface_azimuth": -90, "surface_tilt": 7, "userhorizon": [30, 30, 30, 50], - "inverter_paco": 10000, + "inverter_paco": 10000 }, { "peakpower": 1.4, "surface_azimuth": -40, "surface_tilt": 60, "userhorizon": [60, 30, 0, 30], - "inverter_paco": 2000, + "inverter_paco": 2000 }, { "peakpower": 1.6, "surface_azimuth": 5, "surface_tilt": 45, "userhorizon": [45, 25, 30, 60], - "inverter_paco": 1400, + "inverter_paco": 1400 } ] } diff --git a/docs/index.md b/docs/index.md index 1671808..c0cd50c 100644 --- a/docs/index.md +++ b/docs/index.md @@ -40,6 +40,7 @@ akkudoktoreos/optimization.md akkudoktoreos/prediction.md akkudoktoreos/measurement.md akkudoktoreos/integration.md +akkudoktoreos/logging.md akkudoktoreos/serverapi.md akkudoktoreos/api.rst diff --git a/openapi.json b/openapi.json index c08951b..64f4596 100644 --- a/openapi.json +++ b/openapi.json @@ -1,4613 +1,4833 @@ { - "components": { - "schemas": { - "BaseBatteryParameters": { - "additionalProperties": false, - "description": "Battery Device Simulation Configuration.", - "properties": { - "capacity_wh": { - "description": "An integer representing the capacity of the battery in watt-hours.", - "examples": [ - 8000 - ], - "exclusiveMinimum": 0.0, - "title": "Capacity Wh", - "type": "integer" - }, - "charging_efficiency": { - "default": 0.88, - "description": "A float representing the charging efficiency of the battery.", - "exclusiveMinimum": 0.0, - "maximum": 1.0, - "title": "Charging Efficiency", - "type": "number" - }, - "device_id": { - "description": "ID of battery", - "examples": [ - "battery1" - ], - "title": "Device Id", - "type": "string" - }, - "discharging_efficiency": { - "default": 0.88, - "description": "A float representing the discharge efficiency of the battery.", - "exclusiveMinimum": 0.0, - "maximum": 1.0, - "title": "Discharging Efficiency", - "type": "number" - }, - "hours": { - "anyOf": [ - { - "exclusiveMinimum": 0.0, - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Number of prediction hours. Defaults to global config prediction hours.", - "examples": [ - null - ], - "title": "Hours" - }, - "initial_soc_percentage": { - "default": 0, - "description": "An integer representing the state of charge of the battery at the **start** of the current hour (not the current state).", - "examples": [ - 42 - ], - "maximum": 100.0, - "minimum": 0.0, - "title": "Initial Soc Percentage", - "type": "integer" - }, - "max_charge_power_w": { - "anyOf": [ - { - "exclusiveMinimum": 0.0, - "type": "number" - }, - { - "type": "null" - } - ], - "default": 5000, - "description": "Maximum charging power in watts.", - "title": "Max Charge Power W" - }, - "max_soc_percentage": { - "default": 100, - "description": "An integer representing the maximum state of charge (SOC) of the battery in percentage.", - "maximum": 100.0, - "minimum": 0.0, - "title": "Max Soc Percentage", - "type": "integer" - }, - "min_soc_percentage": { - "default": 0, - "description": "An integer representing the minimum state of charge (SOC) of the battery in percentage.", - "examples": [ - 10 - ], - "maximum": 100.0, - "minimum": 0.0, - "title": "Min Soc Percentage", - "type": "integer" - } + "openapi": "3.1.0", + "info": { + "title": "Akkudoktor-EOS", + "description": "This project provides a comprehensive solution for simulating and optimizing an energy system based on renewable energy sources. With a focus on photovoltaic (PV) systems, battery storage (batteries), load management (consumer requirements), heat pumps, electric vehicles, and consideration of electricity price data, this system enables forecasting and optimization of energy flow and costs over a specified period.", + "version": "0.0.1" + }, + "paths": { + "/v1/admin/cache/clear": { + "post": { + "tags": [ + "admin" + ], + "summary": "Fastapi Admin Cache Clear Post", + "description": "Clear the cache from expired data.\n\nDeletes expired cache files.\n\nArgs:\n clear_all (Optional[bool]): Delete all cached files. Default is False.\n\nReturns:\n data (dict): The management data after cleanup.", + "operationId": "fastapi_admin_cache_clear_post_v1_admin_cache_clear_post", + "parameters": [ + { + "name": "clear_all", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "boolean" }, - "required": [ - "device_id", - "capacity_wh" - ], - "title": "BaseBatteryParameters", - "type": "object" - }, - "CacheCommonSettings": { - "description": "Cache Configuration.", - "properties": { - "cleanup_interval": { - "default": 300, - "description": "Intervall in seconds for EOS file cache cleanup.", - "title": "Cleanup Interval", - "type": "number" - }, - "subpath": { - "anyOf": [ - { - "format": "path", - "type": "string" - }, - { - "type": "null" - } - ], - "default": "cache", - "description": "Sub-path for the EOS cache data directory.", - "title": "Subpath" - } - }, - "title": "CacheCommonSettings", - "type": "object" - }, - "ConfigEOS": { - "additionalProperties": false, - "description": "Singleton configuration handler for the EOS application.\n\nConfigEOS extends `SettingsEOS` with support for default configuration paths and automatic\ninitialization.\n\n`ConfigEOS` ensures that only one instance of the class is created throughout the application,\nallowing consistent access to EOS configuration settings. This singleton instance loads\nconfiguration data from a predefined set of directories or creates a default configuration if\nnone is found.\n\nInitialization Process:\n - Upon instantiation, the singleton instance attempts to load a configuration file in this order:\n 1. The directory specified by the `EOS_CONFIG_DIR` environment variable\n 2. The directory specified by the `EOS_DIR` environment variable.\n 3. A platform specific default directory for EOS.\n 4. The current working directory.\n - The first available configuration file found in these directories is loaded.\n - If no configuration file is found, a default configuration file is created in the platform\n specific default directory, and default settings are loaded into it.\n\nAttributes from the loaded configuration are accessible directly as instance attributes of\n`ConfigEOS`, providing a centralized, shared configuration object for EOS.\n\nSingleton Behavior:\n - This class uses the `SingletonMixin` to ensure that all requests for `ConfigEOS` return\n the same instance, which contains the most up-to-date configuration. Modifying the configuration\n in one part of the application reflects across all references to this class.\n\nAttributes:\n config_folder_path (Optional[Path]): Path to the configuration directory.\n config_file_path (Optional[Path]): Path to the configuration file.\n\nRaises:\n FileNotFoundError: If no configuration file is found, and creating a default configuration fails.\n\nExample:\n To initialize and access configuration attributes (only one instance is created):\n ```python\n config_eos = ConfigEOS() # Always returns the same instance\n print(config_eos.prediction.hours) # Access a setting from the loaded configuration\n ```", - "properties": { - "cache": { - "$ref": "#/components/schemas/CacheCommonSettings", - "default": { - "cleanup_interval": 300.0, - "subpath": "cache" - } - }, - "devices": { - "$ref": "#/components/schemas/DevicesCommonSettings", - "default": {} - }, - "elecprice": { - "$ref": "#/components/schemas/ElecPriceCommonSettings", - "default": {} - }, - "ems": { - "$ref": "#/components/schemas/EnergyManagementCommonSettings", - "default": { - "startup_delay": 5.0 - } - }, - "general": { - "$ref": "#/components/schemas/GeneralSettings-Output", - "default": { - "config_file_path": "/home/user/.config/net.akkudoktoreos.net/EOS.config.json", - "config_folder_path": "/home/user/.config/net.akkudoktoreos.net", - "data_output_subpath": "output", - "latitude": 52.52, - "longitude": 13.405, - "timezone": "Europe/Berlin" - } - }, - "load": { - "$ref": "#/components/schemas/LoadCommonSettings", - "default": {} - }, - "logging": { - "$ref": "#/components/schemas/LoggingCommonSettings-Output", - "default": { - "root_level": "INFO" - } - }, - "measurement": { - "$ref": "#/components/schemas/MeasurementCommonSettings", - "default": {} - }, - "optimization": { - "$ref": "#/components/schemas/OptimizationCommonSettings", - "default": { - "ev_available_charge_rates_percent": [ - 0.0, - 0.375, - 0.5, - 0.625, - 0.75, - 0.875, - 1.0 - ], - "hours": 48, - "penalty": 10 - } - }, - "prediction": { - "$ref": "#/components/schemas/PredictionCommonSettings", - "default": { - "historic_hours": 48, - "hours": 48 - } - }, - "pvforecast": { - "$ref": "#/components/schemas/PVForecastCommonSettings-Output", - "default": { - "max_planes": 0, - "planes_azimuth": [], - "planes_inverter_paco": [], - "planes_peakpower": [], - "planes_tilt": [], - "planes_userhorizon": [] - } - }, - "server": { - "$ref": "#/components/schemas/ServerCommonSettings", - "default": { - "eosdash_host": "127.0.0.1", - "eosdash_port": 8504, - "host": "127.0.0.1", - "port": 8503, - "startup_eosdash": true, - "verbose": false - } - }, - "utils": { - "$ref": "#/components/schemas/UtilsCommonSettings", - "default": {} - }, - "weather": { - "$ref": "#/components/schemas/WeatherCommonSettings", - "default": {} - } - }, - "title": "ConfigEOS", - "type": "object" - }, - "DevicesCommonSettings": { - "description": "Base configuration for devices simulation settings.", - "properties": { - "batteries": { - "anyOf": [ - { - "items": { - "$ref": "#/components/schemas/BaseBatteryParameters" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "description": "List of battery/ev devices", - "examples": [ - [ - { - "capacity_wh": 8000, - "device_id": "battery1" - } - ] - ], - "title": "Batteries" - }, - "home_appliances": { - "anyOf": [ - { - "items": { - "$ref": "#/components/schemas/HomeApplianceParameters" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "description": "List of home appliances", - "examples": [ - [] - ], - "title": "Home Appliances" - }, - "inverters": { - "anyOf": [ - { - "items": { - "$ref": "#/components/schemas/InverterParameters" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "description": "List of inverters", - "examples": [ - [] - ], - "title": "Inverters" - } - }, - "title": "DevicesCommonSettings", - "type": "object" - }, - "ElecPriceCommonSettings": { - "description": "Electricity Price Prediction Configuration.", - "properties": { - "charges_kwh": { - "anyOf": [ - { - "minimum": 0.0, - "type": "number" - }, - { - "type": "null" - } - ], - "description": "Electricity price charges (\u20ac/kWh).", - "examples": [ - 0.21 - ], - "title": "Charges Kwh" - }, - "provider": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Electricity price provider id of provider to be used.", - "examples": [ - "ElecPriceAkkudoktor" - ], - "title": "Provider" - }, - "provider_settings": { - "anyOf": [ - { - "$ref": "#/components/schemas/ElecPriceImportCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Provider settings", - "examples": [ - null - ] - } - }, - "title": "ElecPriceCommonSettings", - "type": "object" - }, - "ElecPriceImportCommonSettings": { - "description": "Common settings for elecprice data import from file or JSON String.", - "properties": { - "import_file_path": { - "anyOf": [ - { - "type": "string" - }, - { - "format": "path", - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Path to the file to import elecprice data from.", - "examples": [ - null, - "/path/to/prices.json" - ], - "title": "Import File Path" - }, - "import_json": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "JSON string, dictionary of electricity price forecast value lists.", - "examples": [ - "{\"elecprice_marketprice_wh\": [0.0003384, 0.0003318, 0.0003284]}" - ], - "title": "Import Json" - } - }, - "title": "ElecPriceImportCommonSettings", - "type": "object" - }, - "ElectricVehicleParameters": { - "additionalProperties": false, - "description": "Battery Electric Vehicle Device Simulation Configuration.", - "properties": { - "capacity_wh": { - "description": "An integer representing the capacity of the battery in watt-hours.", - "examples": [ - 8000 - ], - "exclusiveMinimum": 0.0, - "title": "Capacity Wh", - "type": "integer" - }, - "charging_efficiency": { - "default": 0.88, - "description": "A float representing the charging efficiency of the battery.", - "exclusiveMinimum": 0.0, - "maximum": 1.0, - "title": "Charging Efficiency", - "type": "number" - }, - "device_id": { - "description": "ID of electric vehicle", - "examples": [ - "ev1" - ], - "title": "Device Id", - "type": "string" - }, - "discharging_efficiency": { - "default": 1.0, - "description": "A float representing the discharge efficiency of the battery.", - "exclusiveMinimum": 0.0, - "maximum": 1.0, - "title": "Discharging Efficiency", - "type": "number" - }, - "hours": { - "anyOf": [ - { - "exclusiveMinimum": 0.0, - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Number of prediction hours. Defaults to global config prediction hours.", - "examples": [ - null - ], - "title": "Hours" - }, - "initial_soc_percentage": { - "default": 0, - "description": "An integer representing the current state of charge (SOC) of the battery in percentage.", - "examples": [ - 42 - ], - "maximum": 100.0, - "minimum": 0.0, - "title": "Initial Soc Percentage", - "type": "integer" - }, - "max_charge_power_w": { - "anyOf": [ - { - "exclusiveMinimum": 0.0, - "type": "number" - }, - { - "type": "null" - } - ], - "default": 5000, - "description": "Maximum charging power in watts.", - "title": "Max Charge Power W" - }, - "max_soc_percentage": { - "default": 100, - "description": "An integer representing the maximum state of charge (SOC) of the battery in percentage.", - "maximum": 100.0, - "minimum": 0.0, - "title": "Max Soc Percentage", - "type": "integer" - }, - "min_soc_percentage": { - "default": 0, - "description": "An integer representing the minimum state of charge (SOC) of the battery in percentage.", - "examples": [ - 10 - ], - "maximum": 100.0, - "minimum": 0.0, - "title": "Min Soc Percentage", - "type": "integer" - } - }, - "required": [ - "device_id", - "capacity_wh" - ], - "title": "ElectricVehicleParameters", - "type": "object" - }, - "ElectricVehicleResult": { - "additionalProperties": false, - "description": "Result class containing information related to the electric vehicle's charging and discharging behavior.", - "properties": { - "capacity_wh": { - "description": "Capacity of the EV\u2019s battery in watt-hours.", - "title": "Capacity Wh", - "type": "integer" - }, - "charge_array": { - "description": "Hourly charging status (0 for no charging, 1 for charging).", - "items": { - "type": "number" - }, - "title": "Charge Array", - "type": "array" - }, - "charging_efficiency": { - "description": "Charging efficiency as a float..", - "title": "Charging Efficiency", - "type": "number" - }, - "device_id": { - "description": "ID of electric vehicle", - "examples": [ - "ev1" - ], - "title": "Device Id", - "type": "string" - }, - "discharge_array": { - "description": "Hourly discharging status (0 for no discharging, 1 for discharging).", - "items": { - "type": "integer" - }, - "title": "Discharge Array", - "type": "array" - }, - "discharging_efficiency": { - "description": "The discharge efficiency as a float..", - "title": "Discharging Efficiency", - "type": "number" - }, - "hours": { - "description": "Number of hours in the simulation.", - "examples": [ - 24 - ], - "exclusiveMinimum": 0.0, - "title": "Hours", - "type": "integer" - }, - "initial_soc_percentage": { - "description": "State of charge at the start of the simulation in percentage.", - "title": "Initial Soc Percentage", - "type": "integer" - }, - "max_charge_power_w": { - "description": "Maximum charging power in watts.", - "title": "Max Charge Power W", - "type": "integer" - }, - "soc_wh": { - "description": "State of charge of the battery in watt-hours at the start of the simulation.", - "title": "Soc Wh", - "type": "number" - } - }, - "required": [ - "device_id", - "hours", - "charge_array", - "discharge_array", - "discharging_efficiency", - "capacity_wh", - "charging_efficiency", - "max_charge_power_w", - "soc_wh", - "initial_soc_percentage" - ], - "title": "ElectricVehicleResult", - "type": "object" - }, - "EnergyManagementCommonSettings": { - "description": "Energy Management Configuration.", - "properties": { - "interval": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ], - "description": "Intervall in seconds between EOS energy management runs.", - "examples": [ - "300" - ], - "title": "Interval" - }, - "startup_delay": { - "default": 5, - "description": "Startup delay in seconds for EOS energy management runs.", - "minimum": 1.0, - "title": "Startup Delay", - "type": "number" - } - }, - "title": "EnergyManagementCommonSettings", - "type": "object" - }, - "EnergyManagementParameters": { - "additionalProperties": false, - "properties": { - "einspeiseverguetung_euro_pro_wh": { - "anyOf": [ - { - "items": { - "type": "number" - }, - "type": "array" - }, - { - "type": "number" - } - ], - "description": "A float or array of floats representing the feed-in compensation in euros per watt-hour.", - "title": "Einspeiseverguetung Euro Pro Wh" - }, - "gesamtlast": { - "description": "An array of floats representing the total load (consumption) in watts for different time intervals.", - "items": { - "type": "number" - }, - "title": "Gesamtlast", - "type": "array" - }, - "preis_euro_pro_wh_akku": { - "description": "A float representing the cost of battery energy per watt-hour.", - "title": "Preis Euro Pro Wh Akku", - "type": "number" - }, - "pv_prognose_wh": { - "description": "An array of floats representing the forecasted photovoltaic output in watts for different time intervals.", - "items": { - "type": "number" - }, - "title": "Pv Prognose Wh", - "type": "array" - }, - "strompreis_euro_pro_wh": { - "description": "An array of floats representing the electricity price in euros per watt-hour for different time intervals.", - "items": { - "type": "number" - }, - "title": "Strompreis Euro Pro Wh", - "type": "array" - } - }, - "required": [ - "pv_prognose_wh", - "strompreis_euro_pro_wh", - "einspeiseverguetung_euro_pro_wh", - "preis_euro_pro_wh_akku", - "gesamtlast" - ], - "title": "EnergyManagementParameters", - "type": "object" - }, - "ForecastResponse": { - "properties": { - "pvpower": { - "items": { - "type": "number" - }, - "title": "Pvpower", - "type": "array" - }, - "temperature": { - "items": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "title": "Temperature", - "type": "array" - } - }, - "required": [ - "temperature", - "pvpower" - ], - "title": "ForecastResponse", - "type": "object" - }, - "GeneralSettings-Input": { - "description": "Settings for common configuration.\n\nGeneral configuration to set directories of cache and output files and system location (latitude\nand longitude).\nValidators ensure each parameter is within a specified range. A computed property, `timezone`,\ndetermines the time zone based on latitude and longitude.\n\nAttributes:\n latitude (Optional[float]): Latitude in degrees, must be between -90 and 90.\n longitude (Optional[float]): Longitude in degrees, must be between -180 and 180.\n\nProperties:\n timezone (Optional[str]): Computed time zone string based on the specified latitude\n and longitude.\n\nValidators:\n validate_latitude (float): Ensures `latitude` is within the range -90 to 90.\n validate_longitude (float): Ensures `longitude` is within the range -180 to 180.", - "properties": { - "data_folder_path": { - "anyOf": [ - { - "format": "path", - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Path to EOS data directory.", - "examples": [ - null, - "/home/eos/data" - ], - "title": "Data Folder Path" - }, - "data_output_subpath": { - "anyOf": [ - { - "format": "path", - "type": "string" - }, - { - "type": "null" - } - ], - "default": "output", - "description": "Sub-path for the EOS output data directory.", - "title": "Data Output Subpath" - }, - "latitude": { - "anyOf": [ - { - "maximum": 90.0, - "minimum": -90.0, - "type": "number" - }, - { - "type": "null" - } - ], - "default": 52.52, - "description": "Latitude in decimal degrees, between -90 and 90, north is positive (ISO 19115) (\u00b0)", - "title": "Latitude" - }, - "longitude": { - "anyOf": [ - { - "maximum": 180.0, - "minimum": -180.0, - "type": "number" - }, - { - "type": "null" - } - ], - "default": 13.405, - "description": "Longitude in decimal degrees, within -180 to 180 (\u00b0)", - "title": "Longitude" - } - }, - "title": "GeneralSettings", - "type": "object" - }, - "GeneralSettings-Output": { - "description": "Settings for common configuration.\n\nGeneral configuration to set directories of cache and output files and system location (latitude\nand longitude).\nValidators ensure each parameter is within a specified range. A computed property, `timezone`,\ndetermines the time zone based on latitude and longitude.\n\nAttributes:\n latitude (Optional[float]): Latitude in degrees, must be between -90 and 90.\n longitude (Optional[float]): Longitude in degrees, must be between -180 and 180.\n\nProperties:\n timezone (Optional[str]): Computed time zone string based on the specified latitude\n and longitude.\n\nValidators:\n validate_latitude (float): Ensures `latitude` is within the range -90 to 90.\n validate_longitude (float): Ensures `longitude` is within the range -180 to 180.", - "properties": { - "config_file_path": { - "anyOf": [ - { - "format": "path", - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Path to EOS configuration file.", - "readOnly": true, - "title": "Config File Path" - }, - "config_folder_path": { - "anyOf": [ - { - "format": "path", - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Path to EOS configuration directory.", - "readOnly": true, - "title": "Config Folder Path" - }, - "data_folder_path": { - "anyOf": [ - { - "format": "path", - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Path to EOS data directory.", - "examples": [ - null, - "/home/eos/data" - ], - "title": "Data Folder Path" - }, - "data_output_path": { - "anyOf": [ - { - "format": "path", - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Compute data_output_path based on data_folder_path.", - "readOnly": true, - "title": "Data Output Path" - }, - "data_output_subpath": { - "anyOf": [ - { - "format": "path", - "type": "string" - }, - { - "type": "null" - } - ], - "default": "output", - "description": "Sub-path for the EOS output data directory.", - "title": "Data Output Subpath" - }, - "latitude": { - "anyOf": [ - { - "maximum": 90.0, - "minimum": -90.0, - "type": "number" - }, - { - "type": "null" - } - ], - "default": 52.52, - "description": "Latitude in decimal degrees, between -90 and 90, north is positive (ISO 19115) (\u00b0)", - "title": "Latitude" - }, - "longitude": { - "anyOf": [ - { - "maximum": 180.0, - "minimum": -180.0, - "type": "number" - }, - { - "type": "null" - } - ], - "default": 13.405, - "description": "Longitude in decimal degrees, within -180 to 180 (\u00b0)", - "title": "Longitude" - }, - "timezone": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Compute timezone based on latitude and longitude.", - "readOnly": true, - "title": "Timezone" - } - }, - "required": [ - "timezone", - "data_output_path", - "config_folder_path", - "config_file_path" - ], - "title": "GeneralSettings", - "type": "object" - }, - "GesamtlastRequest": { - "properties": { - "hours": { - "title": "Hours", - "type": "integer" - }, - "measured_data": { - "items": { - "additionalProperties": true, - "type": "object" - }, - "title": "Measured Data", - "type": "array" - }, - "year_energy": { - "title": "Year Energy", - "type": "number" - } - }, - "required": [ - "year_energy", - "measured_data", - "hours" - ], - "title": "GesamtlastRequest", - "type": "object" - }, - "HTTPValidationError": { - "properties": { - "detail": { - "items": { - "$ref": "#/components/schemas/ValidationError" - }, - "title": "Detail", - "type": "array" - } - }, - "title": "HTTPValidationError", - "type": "object" - }, - "HomeApplianceParameters": { - "additionalProperties": false, - "description": "Home Appliance Device Simulation Configuration.", - "properties": { - "consumption_wh": { - "description": "An integer representing the energy consumption of a household device in watt-hours.", - "examples": [ - 2000 - ], - "exclusiveMinimum": 0.0, - "title": "Consumption Wh", - "type": "integer" - }, - "device_id": { - "description": "ID of home appliance", - "examples": [ - "dishwasher" - ], - "title": "Device Id", - "type": "string" - }, - "duration_h": { - "description": "An integer representing the usage duration of a household device in hours.", - "examples": [ - 3 - ], - "exclusiveMinimum": 0.0, - "title": "Duration H", - "type": "integer" - }, - "hours": { - "anyOf": [ - { - "exclusiveMinimum": 0.0, - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Number of prediction hours. Defaults to global config prediction hours.", - "examples": [ - null - ], - "title": "Hours" - } - }, - "required": [ - "device_id", - "consumption_wh", - "duration_h" - ], - "title": "HomeApplianceParameters", - "type": "object" - }, - "InverterParameters": { - "additionalProperties": false, - "description": "Inverter Device Simulation Configuration.", - "properties": { - "battery_id": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "ID of battery", - "examples": [ - null, - "battery1" - ], - "title": "Battery Id" - }, - "device_id": { - "description": "ID of inverter", - "examples": [ - "inverter1" - ], - "title": "Device Id", - "type": "string" - }, - "hours": { - "anyOf": [ - { - "exclusiveMinimum": 0.0, - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Number of prediction hours. Defaults to global config prediction hours.", - "examples": [ - null - ], - "title": "Hours" - }, - "max_power_wh": { - "examples": [ - 10000 - ], - "exclusiveMinimum": 0.0, - "title": "Max Power Wh", - "type": "number" - } - }, - "required": [ - "device_id", - "max_power_wh" - ], - "title": "InverterParameters", - "type": "object" - }, - "LoadAkkudoktorCommonSettings": { - "description": "Common settings for load data import from file.", - "properties": { - "loadakkudoktor_year_energy": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ], - "description": "Yearly energy consumption (kWh).", - "examples": [ - 40421 - ], - "title": "Loadakkudoktor Year Energy" - } - }, - "title": "LoadAkkudoktorCommonSettings", - "type": "object" - }, - "LoadCommonSettings": { - "description": "Load Prediction Configuration.", - "properties": { - "provider": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Load provider id of provider to be used.", - "examples": [ - "LoadAkkudoktor" - ], - "title": "Provider" - }, - "provider_settings": { - "anyOf": [ - { - "$ref": "#/components/schemas/LoadAkkudoktorCommonSettings" - }, - { - "$ref": "#/components/schemas/LoadImportCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Provider settings", - "examples": [ - null - ], - "title": "Provider Settings" - } - }, - "title": "LoadCommonSettings", - "type": "object" - }, - "LoadImportCommonSettings": { - "description": "Common settings for load data import from file or JSON string.", - "properties": { - "import_file_path": { - "anyOf": [ - { - "type": "string" - }, - { - "format": "path", - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Path to the file to import load data from.", - "examples": [ - null, - "/path/to/yearly_load.json" - ], - "title": "Import File Path" - }, - "import_json": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "JSON string, dictionary of load forecast value lists.", - "examples": [ - "{\"load0_mean\": [676.71, 876.19, 527.13]}" - ], - "title": "Import Json" - } - }, - "title": "LoadImportCommonSettings", - "type": "object" - }, - "LoggingCommonSettings-Input": { - "description": "Logging Configuration.", - "properties": { - "level": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "EOS default logging level.", - "examples": [ - "INFO", - "DEBUG", - "WARNING", - "ERROR", - "CRITICAL" - ], - "title": "Level" - } - }, - "title": "LoggingCommonSettings", - "type": "object" - }, - "LoggingCommonSettings-Output": { - "description": "Logging Configuration.", - "properties": { - "level": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "EOS default logging level.", - "examples": [ - "INFO", - "DEBUG", - "WARNING", - "ERROR", - "CRITICAL" - ], - "title": "Level" - }, - "root_level": { - "description": "Root logger logging level.", - "readOnly": true, - "title": "Root Level", - "type": "string" - } - }, - "required": [ - "root_level" - ], - "title": "LoggingCommonSettings", - "type": "object" - }, - "MeasurementCommonSettings": { - "description": "Measurement Configuration.", - "properties": { - "load0_name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Name of the load0 source", - "examples": [ - "Household", - "Heat Pump" - ], - "title": "Load0 Name" - }, - "load1_name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Name of the load1 source", - "examples": [ - null - ], - "title": "Load1 Name" - }, - "load2_name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Name of the load2 source", - "examples": [ - null - ], - "title": "Load2 Name" - }, - "load3_name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Name of the load3 source", - "examples": [ - null - ], - "title": "Load3 Name" - }, - "load4_name": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Name of the load4 source", - "examples": [ - null - ], - "title": "Load4 Name" - } - }, - "title": "MeasurementCommonSettings", - "type": "object" - }, - "OptimizationCommonSettings": { - "description": "General Optimization Configuration.\n\nAttributes:\n hours (int): Number of hours for optimizations.", - "properties": { - "ev_available_charge_rates_percent": { - "anyOf": [ - { - "items": { - "type": "number" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "default": [ - 0.0, - 0.375, - 0.5, - 0.625, - 0.75, - 0.875, - 1.0 - ], - "description": "Charge rates available for the EV in percent of maximum charge.", - "title": "Ev Available Charge Rates Percent" - }, - "hours": { - "anyOf": [ - { - "minimum": 0.0, - "type": "integer" - }, - { - "type": "null" - } - ], - "default": 48, - "description": "Number of hours into the future for optimizations.", - "title": "Hours" - }, - "penalty": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": 10, - "description": "Penalty factor used in optimization.", - "title": "Penalty" - } - }, - "title": "OptimizationCommonSettings", - "type": "object" - }, - "OptimizationParameters": { - "additionalProperties": false, - "properties": { - "dishwasher": { - "anyOf": [ - { - "$ref": "#/components/schemas/HomeApplianceParameters" - }, - { - "type": "null" - } - ] - }, - "eauto": { - "anyOf": [ - { - "$ref": "#/components/schemas/ElectricVehicleParameters" - }, - { - "type": "null" - } - ] - }, - "ems": { - "$ref": "#/components/schemas/EnergyManagementParameters" - }, - "inverter": { - "anyOf": [ - { - "$ref": "#/components/schemas/InverterParameters" - }, - { - "type": "null" - } - ] - }, - "pv_akku": { - "anyOf": [ - { - "$ref": "#/components/schemas/SolarPanelBatteryParameters" - }, - { - "type": "null" - } - ] - }, - "start_solution": { - "anyOf": [ - { - "items": { - "type": "number" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "description": "Can be `null` or contain a previous solution (if available).", - "title": "Start Solution" - }, - "temperature_forecast": { - "anyOf": [ - { - "items": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "type": "array" - }, - { - "type": "null" - } - ], - "description": "An array of floats representing the temperature forecast in degrees Celsius for different time intervals.", - "title": "Temperature Forecast" - } - }, - "required": [ - "ems", - "pv_akku", - "inverter", - "eauto" - ], - "title": "OptimizationParameters", - "type": "object" - }, - "OptimizeResponse": { - "additionalProperties": false, - "description": "**Note**: The first value of \"Last_Wh_per_hour\", \"Netzeinspeisung_Wh_per_hour\", and \"Netzbezug_Wh_per_hour\", will be set to null in the JSON output and represented as NaN or None in the corresponding classes' data returns. This approach is adopted to ensure that the current hour's processing remains unchanged.", - "properties": { - "ac_charge": { - "description": "Array with AC charging values as relative power (0-1), other values set to 0.", - "items": { - "type": "number" - }, - "title": "Ac Charge", - "type": "array" - }, - "dc_charge": { - "description": "Array with DC charging values as relative power (0-1), other values set to 0.", - "items": { - "type": "number" - }, - "title": "Dc Charge", - "type": "array" - }, - "discharge_allowed": { - "description": "Array with discharge values (1 for discharge, 0 otherwise).", - "items": { - "type": "integer" - }, - "title": "Discharge Allowed", - "type": "array" - }, - "eauto_obj": { - "anyOf": [ - { - "$ref": "#/components/schemas/ElectricVehicleResult" - }, - { - "type": "null" - } - ] - }, - "eautocharge_hours_float": { - "anyOf": [ - { - "items": { - "type": "number" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "description": "TBD", - "title": "Eautocharge Hours Float" - }, - "result": { - "$ref": "#/components/schemas/SimulationResult" - }, - "start_solution": { - "anyOf": [ - { - "items": { - "type": "number" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "description": "An array of binary values (0 or 1) representing a possible starting solution for the simulation.", - "title": "Start Solution" - }, - "washingstart": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Can be `null` or contain an object representing the start of washing (if applicable).", - "title": "Washingstart" - } - }, - "required": [ - "ac_charge", - "dc_charge", - "discharge_allowed", - "eautocharge_hours_float", - "result", - "eauto_obj" - ], - "title": "OptimizeResponse", - "type": "object" - }, - "PVForecastCommonSettings-Input": { - "description": "PV Forecast Configuration.", - "properties": { - "max_planes": { - "anyOf": [ - { - "minimum": 0.0, - "type": "integer" - }, - { - "type": "null" - } - ], - "default": 0, - "description": "Maximum number of planes that can be set", - "title": "Max Planes" - }, - "planes": { - "anyOf": [ - { - "items": { - "$ref": "#/components/schemas/PVForecastPlaneSetting" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "description": "Plane configuration.", - "examples": [ - [ - { - "inverter_paco": 6000, - "loss": 14.0, - "modules_per_string": 20, - "mountingplace": "free", - "optimal_surface_tilt": false, - "optimalangles": false, - "peakpower": 5.0, - "pvtechchoice": "crystSi", - "strings_per_inverter": 2, - "surface_azimuth": 180.0, - "surface_tilt": 10.0, - "trackingtype": 0, - "userhorizon": [ - 10.0, - 20.0, - 30.0 - ] - }, - { - "inverter_paco": 4000, - "loss": 14.0, - "modules_per_string": 20, - "mountingplace": "free", - "optimal_surface_tilt": false, - "optimalangles": false, - "peakpower": 3.5, - "pvtechchoice": "crystSi", - "strings_per_inverter": 2, - "surface_azimuth": 90.0, - "surface_tilt": 20.0, - "trackingtype": 1, - "userhorizon": [ - 5.0, - 15.0, - 25.0 - ] - } - ] - ], - "title": "Planes" - }, - "provider": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "PVForecast provider id of provider to be used.", - "examples": [ - "PVForecastAkkudoktor" - ], - "title": "Provider" - }, - "provider_settings": { - "anyOf": [ - { - "$ref": "#/components/schemas/PVForecastImportCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Provider settings", - "examples": [ - null - ] - } - }, - "title": "PVForecastCommonSettings", - "type": "object" - }, - "PVForecastCommonSettings-Output": { - "description": "PV Forecast Configuration.", - "properties": { - "max_planes": { - "anyOf": [ - { - "minimum": 0.0, - "type": "integer" - }, - { - "type": "null" - } - ], - "default": 0, - "description": "Maximum number of planes that can be set", - "title": "Max Planes" - }, - "planes": { - "anyOf": [ - { - "items": { - "$ref": "#/components/schemas/PVForecastPlaneSetting" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "description": "Plane configuration.", - "examples": [ - [ - { - "inverter_paco": 6000, - "loss": 14.0, - "modules_per_string": 20, - "mountingplace": "free", - "optimal_surface_tilt": false, - "optimalangles": false, - "peakpower": 5.0, - "pvtechchoice": "crystSi", - "strings_per_inverter": 2, - "surface_azimuth": 180.0, - "surface_tilt": 10.0, - "trackingtype": 0, - "userhorizon": [ - 10.0, - 20.0, - 30.0 - ] - }, - { - "inverter_paco": 4000, - "loss": 14.0, - "modules_per_string": 20, - "mountingplace": "free", - "optimal_surface_tilt": false, - "optimalangles": false, - "peakpower": 3.5, - "pvtechchoice": "crystSi", - "strings_per_inverter": 2, - "surface_azimuth": 90.0, - "surface_tilt": 20.0, - "trackingtype": 1, - "userhorizon": [ - 5.0, - 15.0, - 25.0 - ] - } - ] - ], - "title": "Planes" - }, - "planes_azimuth": { - "description": "Compute a list of the azimuths per active planes.", - "items": { - "type": "number" - }, - "readOnly": true, - "title": "Planes Azimuth", - "type": "array" - }, - "planes_inverter_paco": { - "description": "Compute a list of the maximum power rating of the inverter per active planes.", - "readOnly": true, - "title": "Planes Inverter Paco" - }, - "planes_peakpower": { - "description": "Compute a list of the peak power per active planes.", - "items": { - "type": "number" - }, - "readOnly": true, - "title": "Planes Peakpower", - "type": "array" - }, - "planes_tilt": { - "description": "Compute a list of the tilts per active planes.", - "items": { - "type": "number" - }, - "readOnly": true, - "title": "Planes Tilt", - "type": "array" - }, - "planes_userhorizon": { - "description": "Compute a list of the user horizon per active planes.", - "readOnly": true, - "title": "Planes Userhorizon" - }, - "provider": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "PVForecast provider id of provider to be used.", - "examples": [ - "PVForecastAkkudoktor" - ], - "title": "Provider" - }, - "provider_settings": { - "anyOf": [ - { - "$ref": "#/components/schemas/PVForecastImportCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Provider settings", - "examples": [ - null - ] - } - }, - "required": [ - "planes_peakpower", - "planes_azimuth", - "planes_tilt", - "planes_userhorizon", - "planes_inverter_paco" - ], - "title": "PVForecastCommonSettings", - "type": "object" - }, - "PVForecastImportCommonSettings": { - "description": "Common settings for pvforecast data import from file or JSON string.", - "properties": { - "import_file_path": { - "anyOf": [ - { - "type": "string" - }, - { - "format": "path", - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Path to the file to import PV forecast data from.", - "examples": [ - null, - "/path/to/pvforecast.json" - ], - "title": "Import File Path" - }, - "import_json": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "JSON string, dictionary of PV forecast value lists.", - "examples": [ - "{\"pvforecast_ac_power\": [0, 8.05, 352.91]}" - ], - "title": "Import Json" - } - }, - "title": "PVForecastImportCommonSettings", - "type": "object" - }, - "PVForecastPlaneSetting": { - "description": "PV Forecast Plane Configuration.", - "properties": { - "albedo": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ], - "description": "Proportion of the light hitting the ground that it reflects back.", - "examples": [ - null - ], - "title": "Albedo" - }, - "inverter_model": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Model of the inverter of this plane.", - "examples": [ - null - ], - "title": "Inverter Model" - }, - "inverter_paco": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "AC power rating of the inverter [W].", - "examples": [ - 6000, - 4000 - ], - "title": "Inverter Paco" - }, - "loss": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ], - "default": 14.0, - "description": "Sum of PV system losses in percent", - "title": "Loss" - }, - "module_model": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Model of the PV modules of this plane.", - "examples": [ - null - ], - "title": "Module Model" - }, - "modules_per_string": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Number of the PV modules of the strings of this plane.", - "examples": [ - 20 - ], - "title": "Modules Per String" - }, - "mountingplace": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": "free", - "description": "Type of mounting for PV system. Options are 'free' for free-standing and 'building' for building-integrated.", - "title": "Mountingplace" - }, - "optimal_surface_tilt": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": false, - "description": "Calculate the optimum tilt angle. Ignored for two-axis tracking.", - "examples": [ - false - ], - "title": "Optimal Surface Tilt" - }, - "optimalangles": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": false, - "description": "Calculate the optimum tilt and azimuth angles. Ignored for two-axis tracking.", - "examples": [ - false - ], - "title": "Optimalangles" - }, - "peakpower": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ], - "description": "Nominal power of PV system in kW.", - "examples": [ - 5.0, - 3.5 - ], - "title": "Peakpower" - }, - "pvtechchoice": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "default": "crystSi", - "description": "PV technology. One of 'crystSi', 'CIS', 'CdTe', 'Unknown'.", - "title": "Pvtechchoice" - }, - "strings_per_inverter": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Number of the strings of the inverter of this plane.", - "examples": [ - 2 - ], - "title": "Strings Per Inverter" - }, - "surface_azimuth": { - "anyOf": [ - { - "maximum": 360.0, - "minimum": 0.0, - "type": "number" - }, - { - "type": "null" - } - ], - "default": 180.0, - "description": "Orientation (azimuth angle) of the (fixed) plane. Clockwise from north (north=0, east=90, south=180, west=270).", - "examples": [ - 180.0, - 90.0 - ], - "title": "Surface Azimuth" - }, - "surface_tilt": { - "anyOf": [ - { - "maximum": 90.0, - "minimum": 0.0, - "type": "number" - }, - { - "type": "null" - } - ], - "default": 30.0, - "description": "Tilt angle from horizontal plane. Ignored for two-axis tracking.", - "examples": [ - 10.0, - 20.0 - ], - "title": "Surface Tilt" - }, - "trackingtype": { - "anyOf": [ - { - "maximum": 5.0, - "minimum": 0.0, - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Type of suntracking. 0=fixed, 1=single horizontal axis aligned north-south, 2=two-axis tracking, 3=vertical axis tracking, 4=single horizontal axis aligned east-west, 5=single inclined axis aligned north-south.", - "examples": [ - 0, - 1, - 2, - 3, - 4, - 5 - ], - "title": "Trackingtype" - }, - "userhorizon": { - "anyOf": [ - { - "items": { - "type": "number" - }, - "type": "array" - }, - { - "type": "null" - } - ], - "description": "Elevation of horizon in degrees, at equally spaced azimuth clockwise from north.", - "examples": [ - [ - 10.0, - 20.0, - 30.0 - ], - [ - 5.0, - 15.0, - 25.0 - ] - ], - "title": "Userhorizon" - } - }, - "title": "PVForecastPlaneSetting", - "type": "object" - }, - "PredictionCommonSettings": { - "description": "General Prediction Configuration.\n\nThis class provides configuration for prediction settings, allowing users to specify\nparameters such as the forecast duration (in hours).\nValidators ensure each parameter is within a specified range.\n\nAttributes:\n hours (Optional[int]): Number of hours into the future for predictions.\n Must be non-negative.\n historic_hours (Optional[int]): Number of hours into the past for historical data.\n Must be non-negative.\n\nValidators:\n validate_hours (int): Ensures `hours` is a non-negative integer.\n validate_historic_hours (int): Ensures `historic_hours` is a non-negative integer.", - "properties": { - "historic_hours": { - "anyOf": [ - { - "minimum": 0.0, - "type": "integer" - }, - { - "type": "null" - } - ], - "default": 48, - "description": "Number of hours into the past for historical predictions data", - "title": "Historic Hours" - }, - "hours": { - "anyOf": [ - { - "minimum": 0.0, - "type": "integer" - }, - { - "type": "null" - } - ], - "default": 48, - "description": "Number of hours into the future for predictions", - "title": "Hours" - } - }, - "title": "PredictionCommonSettings", - "type": "object" - }, - "PydanticDateTimeData": { - "additionalProperties": { - "anyOf": [ - { - "type": "string" - }, - { - "items": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "integer" - }, - { - "type": "string" - }, - { - "type": "null" - } - ] - }, - "type": "array" - } - ] - }, - "description": "Pydantic model for time series data with consistent value lengths.\n\nThis model validates a dictionary where:\n- Keys are strings representing data series names\n- Values are lists of numeric or string values\n- Special keys 'start_datetime' and 'interval' can contain string values\nfor time series indexing\n- All value lists must have the same length\n\nExample:\n {\n \"start_datetime\": \"2024-01-01 00:00:00\", # optional\n \"interval\": \"1 Hour\", # optional\n \"load_mean\": [20.5, 21.0, 22.1],\n \"load_min\": [18.5, 19.0, 20.1]\n }", - "title": "PydanticDateTimeData", - "type": "object" - }, - "PydanticDateTimeDataFrame": { - "description": "Pydantic model for validating pandas DataFrame data with datetime index.", - "properties": { - "data": { - "additionalProperties": { - "additionalProperties": true, - "type": "object" - }, - "title": "Data", - "type": "object" - }, - "datetime_columns": { - "description": "Columns to be treated as datetime", - "items": { - "type": "string" - }, - "title": "Datetime Columns", - "type": "array" - }, - "dtypes": { - "additionalProperties": { - "type": "string" - }, - "title": "Dtypes", - "type": "object" - }, - "tz": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Timezone for datetime values", - "title": "Tz" - } - }, - "required": [ - "data" - ], - "title": "PydanticDateTimeDataFrame", - "type": "object" - }, - "PydanticDateTimeSeries": { - "description": "Pydantic model for validating pandas Series with datetime index in JSON format.\n\nThis model handles Series data serialized with orient='index', where the keys are\ndatetime strings and values are the series values. Provides validation and\nconversion between JSON and pandas Series with datetime index.\n\nAttributes:\n data (Dict[str, Any]): Dictionary mapping datetime strings to values.\n dtype (str): The data type of the series values.\n tz (str | None): Timezone name if the datetime index is timezone-aware.", - "properties": { - "data": { - "additionalProperties": true, - "title": "Data", - "type": "object" - }, - "dtype": { - "default": "float64", - "title": "Dtype", - "type": "string" - }, - "tz": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "title": "Tz" - } - }, - "required": [ - "data" - ], - "title": "PydanticDateTimeSeries", - "type": "object" - }, - "ServerCommonSettings": { - "description": "Server Configuration.", - "properties": { - "eosdash_host": { - "anyOf": [ - { - "format": "ipvanyaddress", - "type": "string" - }, - { - "type": "null" - } - ], - "default": "127.0.0.1", - "description": "EOSdash server IP address.", - "title": "Eosdash Host" - }, - "eosdash_port": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": 8504, - "description": "EOSdash server IP port number.", - "title": "Eosdash Port" - }, - "host": { - "anyOf": [ - { - "format": "ipvanyaddress", - "type": "string" - }, - { - "type": "null" - } - ], - "default": "127.0.0.1", - "description": "EOS server IP address.", - "title": "Host" - }, - "port": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "default": 8503, - "description": "EOS server IP port number.", - "title": "Port" - }, - "startup_eosdash": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": true, - "description": "EOS server to start EOSdash server.", - "title": "Startup Eosdash" - }, - "verbose": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": false, - "description": "Enable debug output", - "title": "Verbose" - } - }, - "title": "ServerCommonSettings", - "type": "object" - }, - "SettingsEOS": { - "additionalProperties": false, - "description": "Settings for all EOS.\n\nUsed by updating the configuration with specific settings only.", - "properties": { - "cache": { - "anyOf": [ - { - "$ref": "#/components/schemas/CacheCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Cache Settings" - }, - "devices": { - "anyOf": [ - { - "$ref": "#/components/schemas/DevicesCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Devices Settings" - }, - "elecprice": { - "anyOf": [ - { - "$ref": "#/components/schemas/ElecPriceCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Electricity Price Settings" - }, - "ems": { - "anyOf": [ - { - "$ref": "#/components/schemas/EnergyManagementCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Energy Management Settings" - }, - "general": { - "anyOf": [ - { - "$ref": "#/components/schemas/GeneralSettings-Input" - }, - { - "type": "null" - } - ], - "description": "General Settings" - }, - "load": { - "anyOf": [ - { - "$ref": "#/components/schemas/LoadCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Load Settings" - }, - "logging": { - "anyOf": [ - { - "$ref": "#/components/schemas/LoggingCommonSettings-Input" - }, - { - "type": "null" - } - ], - "description": "Logging Settings" - }, - "measurement": { - "anyOf": [ - { - "$ref": "#/components/schemas/MeasurementCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Measurement Settings" - }, - "optimization": { - "anyOf": [ - { - "$ref": "#/components/schemas/OptimizationCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Optimization Settings" - }, - "prediction": { - "anyOf": [ - { - "$ref": "#/components/schemas/PredictionCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Prediction Settings" - }, - "pvforecast": { - "anyOf": [ - { - "$ref": "#/components/schemas/PVForecastCommonSettings-Input" - }, - { - "type": "null" - } - ], - "description": "PV Forecast Settings" - }, - "server": { - "anyOf": [ - { - "$ref": "#/components/schemas/ServerCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Server Settings" - }, - "utils": { - "anyOf": [ - { - "$ref": "#/components/schemas/UtilsCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Utilities Settings" - }, - "weather": { - "anyOf": [ - { - "$ref": "#/components/schemas/WeatherCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Weather Settings" - } - }, - "title": "SettingsEOS", - "type": "object" - }, - "SimulationResult": { - "additionalProperties": false, - "description": "This object contains the results of the simulation and provides insights into various parameters over the entire forecast period.", - "properties": { - "EAuto_SoC_pro_Stunde": { - "description": "The state of charge of the EV for each hour.", - "items": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "title": "Eauto Soc Pro Stunde", - "type": "array" - }, - "Einnahmen_Euro_pro_Stunde": { - "description": "The revenue from grid feed-in or other sources in euros per hour.", - "items": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "title": "Einnahmen Euro Pro Stunde", - "type": "array" - }, - "Electricity_price": { - "description": "Used Electricity Price, including predictions", - "items": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "title": "Electricity Price", - "type": "array" - }, - "Gesamt_Verluste": { - "description": "The total losses in watt-hours over the entire period.", - "title": "Gesamt Verluste", - "type": "number" - }, - "Gesamtbilanz_Euro": { - "description": "The total balance of revenues minus costs in euros.", - "title": "Gesamtbilanz Euro", - "type": "number" - }, - "Gesamteinnahmen_Euro": { - "description": "The total revenues in euros.", - "title": "Gesamteinnahmen Euro", - "type": "number" - }, - "Gesamtkosten_Euro": { - "description": "The total costs in euros.", - "title": "Gesamtkosten Euro", - "type": "number" - }, - "Home_appliance_wh_per_hour": { - "description": "The energy consumption of a household appliance in watt-hours per hour.", - "items": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "title": "Home Appliance Wh Per Hour", - "type": "array" - }, - "Kosten_Euro_pro_Stunde": { - "description": "The costs in euros per hour.", - "items": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "title": "Kosten Euro Pro Stunde", - "type": "array" - }, - "Last_Wh_pro_Stunde": { - "description": "TBD", - "items": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "title": "Last Wh Pro Stunde", - "type": "array" - }, - "Netzbezug_Wh_pro_Stunde": { - "description": "The grid energy drawn in watt-hours per hour.", - "items": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "title": "Netzbezug Wh Pro Stunde", - "type": "array" - }, - "Netzeinspeisung_Wh_pro_Stunde": { - "description": "The energy fed into the grid in watt-hours per hour.", - "items": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "title": "Netzeinspeisung Wh Pro Stunde", - "type": "array" - }, - "Verluste_Pro_Stunde": { - "description": "The losses in watt-hours per hour.", - "items": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "title": "Verluste Pro Stunde", - "type": "array" - }, - "akku_soc_pro_stunde": { - "description": "The state of charge of the battery (not the EV) in percentage per hour.", - "items": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "null" - } - ] - }, - "title": "Akku Soc Pro Stunde", - "type": "array" - } - }, - "required": [ - "Last_Wh_pro_Stunde", - "EAuto_SoC_pro_Stunde", - "Einnahmen_Euro_pro_Stunde", - "Gesamt_Verluste", - "Gesamtbilanz_Euro", - "Gesamteinnahmen_Euro", - "Gesamtkosten_Euro", - "Home_appliance_wh_per_hour", - "Kosten_Euro_pro_Stunde", - "Netzbezug_Wh_pro_Stunde", - "Netzeinspeisung_Wh_pro_Stunde", - "Verluste_Pro_Stunde", - "akku_soc_pro_stunde", - "Electricity_price" - ], - "title": "SimulationResult", - "type": "object" - }, - "SolarPanelBatteryParameters": { - "additionalProperties": false, - "properties": { - "capacity_wh": { - "description": "An integer representing the capacity of the battery in watt-hours.", - "examples": [ - 8000 - ], - "exclusiveMinimum": 0.0, - "title": "Capacity Wh", - "type": "integer" - }, - "charging_efficiency": { - "default": 0.88, - "description": "A float representing the charging efficiency of the battery.", - "exclusiveMinimum": 0.0, - "maximum": 1.0, - "title": "Charging Efficiency", - "type": "number" - }, - "device_id": { - "description": "ID of battery", - "examples": [ - "battery1" - ], - "title": "Device Id", - "type": "string" - }, - "discharging_efficiency": { - "default": 0.88, - "description": "A float representing the discharge efficiency of the battery.", - "exclusiveMinimum": 0.0, - "maximum": 1.0, - "title": "Discharging Efficiency", - "type": "number" - }, - "hours": { - "anyOf": [ - { - "exclusiveMinimum": 0.0, - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Number of prediction hours. Defaults to global config prediction hours.", - "examples": [ - null - ], - "title": "Hours" - }, - "initial_soc_percentage": { - "default": 0, - "description": "An integer representing the state of charge of the battery at the **start** of the current hour (not the current state).", - "examples": [ - 42 - ], - "maximum": 100.0, - "minimum": 0.0, - "title": "Initial Soc Percentage", - "type": "integer" - }, - "max_charge_power_w": { - "anyOf": [ - { - "exclusiveMinimum": 0.0, - "type": "number" - }, - { - "type": "null" - } - ], - "default": 5000, - "description": "Maximum charging power in watts.", - "title": "Max Charge Power W" - }, - "max_soc_percentage": { - "default": 100, - "description": "An integer representing the maximum state of charge (SOC) of the battery in percentage.", - "maximum": 100.0, - "minimum": 0.0, - "title": "Max Soc Percentage", - "type": "integer" - }, - "min_soc_percentage": { - "default": 0, - "description": "An integer representing the minimum state of charge (SOC) of the battery in percentage.", - "examples": [ - 10 - ], - "maximum": 100.0, - "minimum": 0.0, - "title": "Min Soc Percentage", - "type": "integer" - } - }, - "required": [ - "device_id", - "capacity_wh" - ], - "title": "SolarPanelBatteryParameters", - "type": "object" - }, - "UtilsCommonSettings": { - "description": "Utils Configuration.", - "properties": {}, - "title": "UtilsCommonSettings", - "type": "object" - }, - "ValidationError": { - "properties": { - "loc": { - "items": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "integer" - } - ] - }, - "title": "Location", - "type": "array" - }, - "msg": { - "title": "Message", - "type": "string" - }, - "type": { - "title": "Error Type", - "type": "string" - } - }, - "required": [ - "loc", - "msg", - "type" - ], - "title": "ValidationError", - "type": "object" - }, - "WeatherCommonSettings": { - "description": "Weather Forecast Configuration.", - "properties": { - "provider": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Weather provider id of provider to be used.", - "examples": [ - "WeatherImport" - ], - "title": "Provider" - }, - "provider_settings": { - "anyOf": [ - { - "$ref": "#/components/schemas/WeatherImportCommonSettings" - }, - { - "type": "null" - } - ], - "description": "Provider settings", - "examples": [ - null - ] - } - }, - "title": "WeatherCommonSettings", - "type": "object" - }, - "WeatherImportCommonSettings": { - "description": "Common settings for weather data import from file or JSON string.", - "properties": { - "import_file_path": { - "anyOf": [ - { - "type": "string" - }, - { - "format": "path", - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Path to the file to import weather data from.", - "examples": [ - null, - "/path/to/weather_data.json" - ], - "title": "Import File Path" - }, - "import_json": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "JSON string, dictionary of weather forecast value lists.", - "examples": [ - "{\"weather_temp_air\": [18.3, 17.8, 16.9]}" - ], - "title": "Import Json" - } - }, - "title": "WeatherImportCommonSettings", - "type": "object" + { + "type": "null" + } + ], + "title": "Clear All" } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "object", + "additionalProperties": true, + "title": "Response Fastapi Admin Cache Clear Post V1 Admin Cache Clear Post" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } } + } }, - "info": { - "description": "This project provides a comprehensive solution for simulating and optimizing an energy system based on renewable energy sources. With a focus on photovoltaic (PV) systems, battery storage (batteries), load management (consumer requirements), heat pumps, electric vehicles, and consideration of electricity price data, this system enables forecasting and optimization of energy flow and costs over a specified period.", - "title": "Akkudoktor-EOS", - "version": "0.0.1" - }, - "openapi": "3.1.0", - "paths": { - "/gesamtlast": { - "post": { - "description": "Deprecated: Total Load Prediction with adjustment.\n\nEndpoint to handle total load prediction adjusted by latest measured data.\n\nTotal load prediction starts at 00.00.00 today and is provided for 48 hours.\nIf no prediction values are available the missing ones at the start of the series are\nfilled with the first available prediction value.\n\nNote:\n Use '/v1/prediction/list?key=load_mean_adjusted' instead.\n Load energy meter readings to be added to EOS measurement by:\n '/v1/measurement/load-mr/value/by-name' or\n '/v1/measurement/value'", - "operationId": "fastapi_gesamtlast_gesamtlast_post", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/GesamtlastRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "items": { - "type": "number" - }, - "title": "Response Fastapi Gesamtlast Gesamtlast Post", - "type": "array" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Gesamtlast", - "tags": [ - "prediction" - ] - } - }, - "/gesamtlast_simple": { - "get": { - "description": "Deprecated: Total Load Prediction.\n\nEndpoint to handle total load prediction.\n\nTotal load prediction starts at 00.00.00 today and is provided for 48 hours.\nIf no prediction values are available the missing ones at the start of the series are\nfilled with the first available prediction value.\n\nArgs:\n year_energy (float): Yearly energy consumption in Wh.\n\nNote:\n Set LoadAkkudoktor as provider, then update data with\n '/v1/prediction/update'\n and then request data with\n '/v1/prediction/list?key=load_mean' instead.", - "operationId": "fastapi_gesamtlast_simple_gesamtlast_simple_get", - "parameters": [ - { - "in": "query", - "name": "year_energy", - "required": true, - "schema": { - "title": "Year Energy", - "type": "number" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "items": { - "type": "number" - }, - "title": "Response Fastapi Gesamtlast Simple Gesamtlast Simple Get", - "type": "array" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Gesamtlast Simple", - "tags": [ - "prediction" - ] - } - }, - "/optimize": { - "post": { - "operationId": "fastapi_optimize_optimize_post", - "parameters": [ - { - "description": "Defaults to current hour of the day.", - "in": "query", - "name": "start_hour", - "required": false, - "schema": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "description": "Defaults to current hour of the day.", - "title": "Start Hour" - } - }, - { - "in": "query", - "name": "ngen", - "required": false, - "schema": { - "anyOf": [ - { - "type": "integer" - }, - { - "type": "null" - } - ], - "title": "Ngen" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/OptimizationParameters" - } - } - }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/OptimizeResponse" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Optimize", - "tags": [ - "optimize" - ] - } - }, - "/pvforecast": { - "get": { - "description": "Deprecated: PV Forecast Prediction.\n\nEndpoint to handle PV forecast prediction.\n\nPVForecast starts at 00.00.00 today and is provided for 48 hours.\nIf no forecast values are available the missing ones at the start of the series are\nfilled with the first available forecast value.\n\nNote:\n Set PVForecastAkkudoktor as provider, then update data with\n '/v1/prediction/update'\n and then request data with\n '/v1/prediction/list?key=pvforecast_ac_power' and\n '/v1/prediction/list?key=pvforecastakkudoktor_temp_air' instead.", - "operationId": "fastapi_pvforecast_pvforecast_get", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ForecastResponse" - } - } - }, - "description": "Successful Response" - } - }, - "summary": "Fastapi Pvforecast", - "tags": [ - "prediction" - ] - } - }, - "/strompreis": { - "get": { - "description": "Deprecated: Electricity Market Price Prediction per Wh (\u20ac/Wh).\n\nElectricity prices start at 00.00.00 today and are provided for 48 hours.\nIf no prices are available the missing ones at the start of the series are\nfilled with the first available price.\n\nNote:\n Electricity price charges are added.\n\nNote:\n Set ElecPriceAkkudoktor as provider, then update data with\n '/v1/prediction/update'\n and then request data with\n '/v1/prediction/list?key=elecprice_marketprice_wh' or\n '/v1/prediction/list?key=elecprice_marketprice_kwh' instead.", - "operationId": "fastapi_strompreis_strompreis_get", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "items": { - "type": "number" - }, - "title": "Response Fastapi Strompreis Strompreis Get", - "type": "array" - } - } - }, - "description": "Successful Response" - } - }, - "summary": "Fastapi Strompreis", - "tags": [ - "prediction" - ] - } - }, - "/v1/admin/cache": { - "get": { - "description": "Current cache management data.\n\nReturns:\n data (dict): The management data.", - "operationId": "fastapi_admin_cache_get_v1_admin_cache_get", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "additionalProperties": true, - "title": "Response Fastapi Admin Cache Get V1 Admin Cache Get", - "type": "object" - } - } - }, - "description": "Successful Response" - } - }, - "summary": "Fastapi Admin Cache Get", - "tags": [ - "admin" - ] - } - }, - "/v1/admin/cache/clear": { - "post": { - "description": "Clear the cache from expired data.\n\nDeletes expired cache files.\n\nArgs:\n clear_all (Optional[bool]): Delete all cached files. Default is False.\n\nReturns:\n data (dict): The management data after cleanup.", - "operationId": "fastapi_admin_cache_clear_post_v1_admin_cache_clear_post", - "parameters": [ - { - "in": "query", - "name": "clear_all", - "required": false, - "schema": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "title": "Clear All" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "additionalProperties": true, - "title": "Response Fastapi Admin Cache Clear Post V1 Admin Cache Clear Post", - "type": "object" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Admin Cache Clear Post", - "tags": [ - "admin" - ] - } - }, - "/v1/admin/cache/load": { - "post": { - "description": "Load cache management data.\n\nReturns:\n data (dict): The management data that was loaded.", - "operationId": "fastapi_admin_cache_load_post_v1_admin_cache_load_post", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "additionalProperties": true, - "title": "Response Fastapi Admin Cache Load Post V1 Admin Cache Load Post", - "type": "object" - } - } - }, - "description": "Successful Response" - } - }, - "summary": "Fastapi Admin Cache Load Post", - "tags": [ - "admin" - ] - } - }, - "/v1/admin/cache/save": { - "post": { - "description": "Save the current cache management data.\n\nReturns:\n data (dict): The management data that was saved.", - "operationId": "fastapi_admin_cache_save_post_v1_admin_cache_save_post", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "additionalProperties": true, - "title": "Response Fastapi Admin Cache Save Post V1 Admin Cache Save Post", - "type": "object" - } - } - }, - "description": "Successful Response" - } - }, - "summary": "Fastapi Admin Cache Save Post", - "tags": [ - "admin" - ] - } - }, - "/v1/admin/server/restart": { - "post": { - "description": "Restart the server.\n\nRestart EOS properly by starting a new instance before exiting the old one.", - "operationId": "fastapi_admin_server_restart_post_v1_admin_server_restart_post", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "additionalProperties": true, - "title": "Response Fastapi Admin Server Restart Post V1 Admin Server Restart Post", - "type": "object" - } - } - }, - "description": "Successful Response" - } - }, - "summary": "Fastapi Admin Server Restart Post", - "tags": [ - "admin" - ] - } - }, - "/v1/admin/server/shutdown": { - "post": { - "description": "Shutdown the server.", - "operationId": "fastapi_admin_server_shutdown_post_v1_admin_server_shutdown_post", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "additionalProperties": true, - "title": "Response Fastapi Admin Server Shutdown Post V1 Admin Server Shutdown Post", - "type": "object" - } - } - }, - "description": "Successful Response" - } - }, - "summary": "Fastapi Admin Server Shutdown Post", - "tags": [ - "admin" - ] - } - }, - "/v1/config": { - "get": { - "description": "Get the current configuration.\n\nReturns:\n configuration (ConfigEOS): The current configuration.", - "operationId": "fastapi_config_get_v1_config_get", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ConfigEOS" - } - } - }, - "description": "Successful Response" - } - }, - "summary": "Fastapi Config Get", - "tags": [ - "config" - ] - }, - "put": { - "description": "Update the current config with the provided settings.\n\nNote that for any setting value that is None or unset, the configuration will fall back to\nvalues from other sources such as environment variables, the EOS configuration file, or default\nvalues.\n\nArgs:\n settings (SettingsEOS): The settings to write into the current settings.\n\nReturns:\n configuration (ConfigEOS): The current configuration after the write.", - "operationId": "fastapi_config_put_v1_config_put", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SettingsEOS" - } - } - }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ConfigEOS" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Config Put", - "tags": [ - "config" - ] - } - }, - "/v1/config/file": { - "put": { - "description": "Save the current configuration to the EOS configuration file.\n\nReturns:\n configuration (ConfigEOS): The current configuration that was saved.", - "operationId": "fastapi_config_file_put_v1_config_file_put", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ConfigEOS" - } - } - }, - "description": "Successful Response" - } - }, - "summary": "Fastapi Config File Put", - "tags": [ - "config" - ] - } - }, - "/v1/config/reset": { - "post": { - "description": "Reset the configuration to the EOS configuration file.\n\nReturns:\n configuration (ConfigEOS): The current configuration after update.", - "operationId": "fastapi_config_reset_post_v1_config_reset_post", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ConfigEOS" - } - } - }, - "description": "Successful Response" - } - }, - "summary": "Fastapi Config Reset Post", - "tags": [ - "config" - ] - } - }, - "/v1/config/{path}": { - "get": { - "description": "Get the value of a nested key or index in the config model.\n\nArgs:\n path (str): The nested path to the key (e.g., \"general/latitude\" or \"optimize/nested_list/0\").\n\nReturns:\n value (Any): The value of the selected nested key.", - "operationId": "fastapi_config_get_key_v1_config__path__get", - "parameters": [ - { - "description": "The nested path to the configuration key (e.g., general/latitude).", - "in": "path", - "name": "path", - "required": true, - "schema": { - "description": "The nested path to the configuration key (e.g., general/latitude).", - "title": "Path", - "type": "string" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": {} - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Config Get Key", - "tags": [ - "config" - ] - }, - "put": { - "description": "Update a nested key or index in the config model.\n\nArgs:\n path (str): The nested path to the key (e.g., \"general/latitude\" or \"optimize/nested_list/0\").\n value (Any): The new value to assign to the key or index at path.\n\nReturns:\n configuration (ConfigEOS): The current configuration after the update.", - "operationId": "fastapi_config_put_key_v1_config__path__put", - "parameters": [ - { - "description": "The nested path to the configuration key (e.g., general/latitude).", - "in": "path", - "name": "path", - "required": true, - "schema": { - "description": "The nested path to the configuration key (e.g., general/latitude).", - "title": "Path", - "type": "string" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "anyOf": [ - {}, - { - "type": "null" - } - ], - "description": "The value to assign to the specified configuration path (can be None).", - "title": "Value" - } - } - } - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/ConfigEOS" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Config Put Key", - "tags": [ - "config" - ] - } - }, - "/v1/health": { - "get": { - "description": "Health check endpoint to verify that the EOS server is alive.", - "operationId": "fastapi_health_get_v1_health_get", - "responses": { - "200": { - "content": { - "application/json": { - "schema": {} - } - }, - "description": "Successful Response" - } - }, - "summary": "Fastapi Health Get" - } - }, - "/v1/measurement/data": { - "put": { - "description": "Merge the measurement data given as datetime data into EOS measurements.", - "operationId": "fastapi_measurement_data_put_v1_measurement_data_put", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PydanticDateTimeData" - } - } - }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": {} - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Measurement Data Put", - "tags": [ - "measurement" - ] - } - }, - "/v1/measurement/dataframe": { - "put": { - "description": "Merge the measurement data given as dataframe into EOS measurements.", - "operationId": "fastapi_measurement_dataframe_put_v1_measurement_dataframe_put", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PydanticDateTimeDataFrame" - } - } - }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": {} - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Measurement Dataframe Put", - "tags": [ - "measurement" - ] - } - }, - "/v1/measurement/keys": { - "get": { - "description": "Get a list of available measurement keys.", - "operationId": "fastapi_measurement_keys_get_v1_measurement_keys_get", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "items": { - "type": "string" - }, - "title": "Response Fastapi Measurement Keys Get V1 Measurement Keys Get", - "type": "array" - } - } - }, - "description": "Successful Response" - } - }, - "summary": "Fastapi Measurement Keys Get", - "tags": [ - "measurement" - ] - } - }, - "/v1/measurement/load-mr/series/by-name": { - "get": { - "description": "Get the meter reading of given load name as series.", - "operationId": "fastapi_measurement_load_mr_series_by_name_get_v1_measurement_load_mr_series_by_name_get", - "parameters": [ - { - "description": "Load name.", - "in": "query", - "name": "name", - "required": true, - "schema": { - "description": "Load name.", - "title": "Name", - "type": "string" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PydanticDateTimeSeries" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Measurement Load Mr Series By Name Get", - "tags": [ - "measurement" - ] - }, - "put": { - "description": "Merge the meter readings series of given load name into EOS measurements at given datetime.", - "operationId": "fastapi_measurement_load_mr_series_by_name_put_v1_measurement_load_mr_series_by_name_put", - "parameters": [ - { - "description": "Load name.", - "in": "query", - "name": "name", - "required": true, - "schema": { - "description": "Load name.", - "title": "Name", - "type": "string" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PydanticDateTimeSeries" - } - } - }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PydanticDateTimeSeries" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Measurement Load Mr Series By Name Put", - "tags": [ - "measurement" - ] - } - }, - "/v1/measurement/load-mr/value/by-name": { - "put": { - "description": "Merge the meter reading of given load name and value into EOS measurements at given datetime.", - "operationId": "fastapi_measurement_load_mr_value_by_name_put_v1_measurement_load_mr_value_by_name_put", - "parameters": [ - { - "description": "Datetime.", - "in": "query", - "name": "datetime", - "required": true, - "schema": { - "description": "Datetime.", - "title": "Datetime", - "type": "string" - } - }, - { - "description": "Load name.", - "in": "query", - "name": "name", - "required": true, - "schema": { - "description": "Load name.", - "title": "Name", - "type": "string" - } - }, - { - "in": "query", - "name": "value", - "required": true, - "schema": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "string" - } - ], - "title": "Value" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PydanticDateTimeSeries" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Measurement Load Mr Value By Name Put", - "tags": [ - "measurement" - ] - } - }, - "/v1/measurement/series": { - "get": { - "description": "Get the measurements of given key as series.", - "operationId": "fastapi_measurement_series_get_v1_measurement_series_get", - "parameters": [ - { - "description": "Prediction key.", - "in": "query", - "name": "key", - "required": true, - "schema": { - "description": "Prediction key.", - "title": "Key", - "type": "string" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PydanticDateTimeSeries" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Measurement Series Get", - "tags": [ - "measurement" - ] - }, - "put": { - "description": "Merge measurement given as series into given key.", - "operationId": "fastapi_measurement_series_put_v1_measurement_series_put", - "parameters": [ - { - "description": "Prediction key.", - "in": "query", - "name": "key", - "required": true, - "schema": { - "description": "Prediction key.", - "title": "Key", - "type": "string" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PydanticDateTimeSeries" - } - } - }, - "required": true - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PydanticDateTimeSeries" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Measurement Series Put", - "tags": [ - "measurement" - ] - } - }, - "/v1/measurement/value": { - "put": { - "description": "Merge the measurement of given key and value into EOS measurements at given datetime.", - "operationId": "fastapi_measurement_value_put_v1_measurement_value_put", - "parameters": [ - { - "description": "Datetime.", - "in": "query", - "name": "datetime", - "required": true, - "schema": { - "description": "Datetime.", - "title": "Datetime", - "type": "string" - } - }, - { - "description": "Prediction key.", - "in": "query", - "name": "key", - "required": true, - "schema": { - "description": "Prediction key.", - "title": "Key", - "type": "string" - } - }, - { - "in": "query", - "name": "value", - "required": true, - "schema": { - "anyOf": [ - { - "type": "number" - }, - { - "type": "string" - } - ], - "title": "Value" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PydanticDateTimeSeries" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Measurement Value Put", - "tags": [ - "measurement" - ] - } - }, - "/v1/prediction/dataframe": { - "get": { - "description": "Get prediction for given key within given date range as series.\n\nArgs:\n key (str): Prediction key\n start_datetime (Optional[str]): Starting datetime (inclusive).\n Defaults to start datetime of latest prediction.\n end_datetime (Optional[str]: Ending datetime (exclusive).\n\nDefaults to end datetime of latest prediction.", - "operationId": "fastapi_prediction_dataframe_get_v1_prediction_dataframe_get", - "parameters": [ - { - "description": "Prediction keys.", - "in": "query", - "name": "keys", - "required": true, - "schema": { - "description": "Prediction keys.", - "items": { - "type": "string" - }, - "title": "Keys", - "type": "array" - } - }, - { - "description": "Starting datetime (inclusive).", - "in": "query", - "name": "start_datetime", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Starting datetime (inclusive).", - "title": "Start Datetime" - } - }, - { - "description": "Ending datetime (exclusive).", - "in": "query", - "name": "end_datetime", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Ending datetime (exclusive).", - "title": "End Datetime" - } - }, - { - "description": "Time duration for each interval. Defaults to 1 hour.", - "in": "query", - "name": "interval", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Time duration for each interval. Defaults to 1 hour.", - "title": "Interval" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PydanticDateTimeDataFrame" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Prediction Dataframe Get", - "tags": [ - "prediction" - ] - } - }, - "/v1/prediction/import/{provider_id}": { - "put": { - "description": "Import prediction for given provider ID.\n\nArgs:\n provider_id: ID of provider to update.\n data: Prediction data.\n force_enable: Update data even if provider is disabled.\n Defaults to False.", - "operationId": "fastapi_prediction_import_provider_v1_prediction_import__provider_id__put", - "parameters": [ - { - "description": "Provider ID.", - "in": "path", - "name": "provider_id", - "required": true, - "schema": { - "description": "Provider ID.", - "title": "Provider Id", - "type": "string" - } - }, - { - "in": "query", - "name": "force_enable", - "required": false, - "schema": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "title": "Force Enable" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "anyOf": [ - { - "$ref": "#/components/schemas/PydanticDateTimeDataFrame" - }, - { - "$ref": "#/components/schemas/PydanticDateTimeData" - }, - { - "additionalProperties": true, - "type": "object" - }, - { - "type": "null" - } - ], - "title": "Data" - } - } - } - }, - "responses": { - "200": { - "content": { - "application/json": { - "schema": {} - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Prediction Import Provider", - "tags": [ - "prediction" - ] - } - }, - "/v1/prediction/keys": { - "get": { - "description": "Get a list of available prediction keys.", - "operationId": "fastapi_prediction_keys_get_v1_prediction_keys_get", - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "items": { - "type": "string" - }, - "title": "Response Fastapi Prediction Keys Get V1 Prediction Keys Get", - "type": "array" - } - } - }, - "description": "Successful Response" - } - }, - "summary": "Fastapi Prediction Keys Get", - "tags": [ - "prediction" - ] - } - }, - "/v1/prediction/list": { - "get": { - "description": "Get prediction for given key within given date range as value list.\n\nArgs:\n key (str): Prediction key\n start_datetime (Optional[str]): Starting datetime (inclusive).\n Defaults to start datetime of latest prediction.\n end_datetime (Optional[str]: Ending datetime (exclusive).\n Defaults to end datetime of latest prediction.\n interval (Optional[str]): Time duration for each interval.\n Defaults to 1 hour.", - "operationId": "fastapi_prediction_list_get_v1_prediction_list_get", - "parameters": [ - { - "description": "Prediction key.", - "in": "query", - "name": "key", - "required": true, - "schema": { - "description": "Prediction key.", - "title": "Key", - "type": "string" - } - }, - { - "description": "Starting datetime (inclusive).", - "in": "query", - "name": "start_datetime", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Starting datetime (inclusive).", - "title": "Start Datetime" - } - }, - { - "description": "Ending datetime (exclusive).", - "in": "query", - "name": "end_datetime", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Ending datetime (exclusive).", - "title": "End Datetime" - } - }, - { - "description": "Time duration for each interval. Defaults to 1 hour.", - "in": "query", - "name": "interval", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Time duration for each interval. Defaults to 1 hour.", - "title": "Interval" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "items": {}, - "title": "Response Fastapi Prediction List Get V1 Prediction List Get", - "type": "array" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Prediction List Get", - "tags": [ - "prediction" - ] - } - }, - "/v1/prediction/providers": { - "get": { - "description": "Get a list of available prediction providers.\n\nArgs:\n enabled (bool): Return enabled/disabled providers. If unset, return all providers.", - "operationId": "fastapi_prediction_providers_get_v1_prediction_providers_get", - "parameters": [ - { - "in": "query", - "name": "enabled", - "required": false, - "schema": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "title": "Enabled" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "items": { - "type": "string" - }, - "title": "Response Fastapi Prediction Providers Get V1 Prediction Providers Get", - "type": "array" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Prediction Providers Get", - "tags": [ - "prediction" - ] - } - }, - "/v1/prediction/series": { - "get": { - "description": "Get prediction for given key within given date range as series.\n\nArgs:\n key (str): Prediction key\n start_datetime (Optional[str]): Starting datetime (inclusive).\n Defaults to start datetime of latest prediction.\n end_datetime (Optional[str]: Ending datetime (exclusive).\n Defaults to end datetime of latest prediction.", - "operationId": "fastapi_prediction_series_get_v1_prediction_series_get", - "parameters": [ - { - "description": "Prediction key.", - "in": "query", - "name": "key", - "required": true, - "schema": { - "description": "Prediction key.", - "title": "Key", - "type": "string" - } - }, - { - "description": "Starting datetime (inclusive).", - "in": "query", - "name": "start_datetime", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Starting datetime (inclusive).", - "title": "Start Datetime" - } - }, - { - "description": "Ending datetime (exclusive).", - "in": "query", - "name": "end_datetime", - "required": false, - "schema": { - "anyOf": [ - { - "type": "string" - }, - { - "type": "null" - } - ], - "description": "Ending datetime (exclusive).", - "title": "End Datetime" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/PydanticDateTimeSeries" - } - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Prediction Series Get", - "tags": [ - "prediction" - ] - } - }, - "/v1/prediction/update": { - "post": { - "description": "Update predictions for all providers.\n\nArgs:\n force_update: Update data even if it is already cached.\n Defaults to False.\n force_enable: Update data even if provider is disabled.\n Defaults to False.", - "operationId": "fastapi_prediction_update_v1_prediction_update_post", - "parameters": [ - { - "in": "query", - "name": "force_update", - "required": false, - "schema": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": false, - "title": "Force Update" - } - }, - { - "in": "query", - "name": "force_enable", - "required": false, - "schema": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": false, - "title": "Force Enable" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": {} - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Prediction Update", - "tags": [ - "prediction" - ] - } - }, - "/v1/prediction/update/{provider_id}": { - "post": { - "description": "Update predictions for given provider ID.\n\nArgs:\n provider_id: ID of provider to update.\n force_update: Update data even if it is already cached.\n Defaults to False.\n force_enable: Update data even if provider is disabled.\n Defaults to False.", - "operationId": "fastapi_prediction_update_provider_v1_prediction_update__provider_id__post", - "parameters": [ - { - "in": "path", - "name": "provider_id", - "required": true, - "schema": { - "title": "Provider Id", - "type": "string" - } - }, - { - "in": "query", - "name": "force_update", - "required": false, - "schema": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": false, - "title": "Force Update" - } - }, - { - "in": "query", - "name": "force_enable", - "required": false, - "schema": { - "anyOf": [ - { - "type": "boolean" - }, - { - "type": "null" - } - ], - "default": false, - "title": "Force Enable" - } - } - ], - "responses": { - "200": { - "content": { - "application/json": { - "schema": {} - } - }, - "description": "Successful Response" - }, - "422": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/HTTPValidationError" - } - } - }, - "description": "Validation Error" - } - }, - "summary": "Fastapi Prediction Update Provider", - "tags": [ - "prediction" - ] - } - }, - "/visualization_results.pdf": { - "get": { - "operationId": "get_pdf_visualization_results_pdf_get", - "responses": { - "200": { - "content": { - "application/pdf": { - "schema": { - "type": "string" - } - } - }, - "description": "Successful Response" - } - }, - "summary": "Get Pdf", - "tags": [ - "optimize" - ] + "/v1/admin/cache/save": { + "post": { + "tags": [ + "admin" + ], + "summary": "Fastapi Admin Cache Save Post", + "description": "Save the current cache management data.\n\nReturns:\n data (dict): The management data that was saved.", + "operationId": "fastapi_admin_cache_save_post_v1_admin_cache_save_post", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "additionalProperties": true, + "type": "object", + "title": "Response Fastapi Admin Cache Save Post V1 Admin Cache Save Post" + } + } } + } } + } + }, + "/v1/admin/cache/load": { + "post": { + "tags": [ + "admin" + ], + "summary": "Fastapi Admin Cache Load Post", + "description": "Load cache management data.\n\nReturns:\n data (dict): The management data that was loaded.", + "operationId": "fastapi_admin_cache_load_post_v1_admin_cache_load_post", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "additionalProperties": true, + "type": "object", + "title": "Response Fastapi Admin Cache Load Post V1 Admin Cache Load Post" + } + } + } + } + } + } + }, + "/v1/admin/cache": { + "get": { + "tags": [ + "admin" + ], + "summary": "Fastapi Admin Cache Get", + "description": "Current cache management data.\n\nReturns:\n data (dict): The management data.", + "operationId": "fastapi_admin_cache_get_v1_admin_cache_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "additionalProperties": true, + "type": "object", + "title": "Response Fastapi Admin Cache Get V1 Admin Cache Get" + } + } + } + } + } + } + }, + "/v1/admin/server/restart": { + "post": { + "tags": [ + "admin" + ], + "summary": "Fastapi Admin Server Restart Post", + "description": "Restart the server.\n\nRestart EOS properly by starting a new instance before exiting the old one.", + "operationId": "fastapi_admin_server_restart_post_v1_admin_server_restart_post", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "additionalProperties": true, + "type": "object", + "title": "Response Fastapi Admin Server Restart Post V1 Admin Server Restart Post" + } + } + } + } + } + } + }, + "/v1/admin/server/shutdown": { + "post": { + "tags": [ + "admin" + ], + "summary": "Fastapi Admin Server Shutdown Post", + "description": "Shutdown the server.", + "operationId": "fastapi_admin_server_shutdown_post_v1_admin_server_shutdown_post", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "additionalProperties": true, + "type": "object", + "title": "Response Fastapi Admin Server Shutdown Post V1 Admin Server Shutdown Post" + } + } + } + } + } + } + }, + "/v1/health": { + "get": { + "summary": "Fastapi Health Get", + "description": "Health check endpoint to verify that the EOS server is alive.", + "operationId": "fastapi_health_get_v1_health_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + } + } + } + }, + "/v1/config/reset": { + "post": { + "tags": [ + "config" + ], + "summary": "Fastapi Config Reset Post", + "description": "Reset the configuration to the EOS configuration file.\n\nReturns:\n configuration (ConfigEOS): The current configuration after update.", + "operationId": "fastapi_config_reset_post_v1_config_reset_post", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConfigEOS" + } + } + } + } + } + } + }, + "/v1/config/file": { + "put": { + "tags": [ + "config" + ], + "summary": "Fastapi Config File Put", + "description": "Save the current configuration to the EOS configuration file.\n\nReturns:\n configuration (ConfigEOS): The current configuration that was saved.", + "operationId": "fastapi_config_file_put_v1_config_file_put", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConfigEOS" + } + } + } + } + } + } + }, + "/v1/config": { + "get": { + "tags": [ + "config" + ], + "summary": "Fastapi Config Get", + "description": "Get the current configuration.\n\nReturns:\n configuration (ConfigEOS): The current configuration.", + "operationId": "fastapi_config_get_v1_config_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConfigEOS" + } + } + } + } + } + }, + "put": { + "tags": [ + "config" + ], + "summary": "Fastapi Config Put", + "description": "Update the current config with the provided settings.\n\nNote that for any setting value that is None or unset, the configuration will fall back to\nvalues from other sources such as environment variables, the EOS configuration file, or default\nvalues.\n\nArgs:\n settings (SettingsEOS): The settings to write into the current settings.\n\nReturns:\n configuration (ConfigEOS): The current configuration after the write.", + "operationId": "fastapi_config_put_v1_config_put", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SettingsEOS" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConfigEOS" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/v1/config/{path}": { + "put": { + "tags": [ + "config" + ], + "summary": "Fastapi Config Put Key", + "description": "Update a nested key or index in the config model.\n\nArgs:\n path (str): The nested path to the key (e.g., \"general/latitude\" or \"optimize/nested_list/0\").\n value (Any): The new value to assign to the key or index at path.\n\nReturns:\n configuration (ConfigEOS): The current configuration after the update.", + "operationId": "fastapi_config_put_key_v1_config__path__put", + "parameters": [ + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "The nested path to the configuration key (e.g., general/latitude).", + "title": "Path" + }, + "description": "The nested path to the configuration key (e.g., general/latitude)." + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + {}, + { + "type": "null" + } + ], + "description": "The value to assign to the specified configuration path (can be None).", + "title": "Value" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ConfigEOS" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "get": { + "tags": [ + "config" + ], + "summary": "Fastapi Config Get Key", + "description": "Get the value of a nested key or index in the config model.\n\nArgs:\n path (str): The nested path to the key (e.g., \"general/latitude\" or \"optimize/nested_list/0\").\n\nReturns:\n value (Any): The value of the selected nested key.", + "operationId": "fastapi_config_get_key_v1_config__path__get", + "parameters": [ + { + "name": "path", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "The nested path to the configuration key (e.g., general/latitude).", + "title": "Path" + }, + "description": "The nested path to the configuration key (e.g., general/latitude)." + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/v1/logging/log": { + "get": { + "tags": [ + "logging" + ], + "summary": "Fastapi Logging Get Log", + "description": "Get structured log entries from the EOS log file.\n\nFilters and returns log entries based on the specified query parameters. The log\nfile is expected to contain newline-delimited JSON entries.\n\nArgs:\n limit (int): Maximum number of entries to return.\n level (Optional[str]): Filter logs by severity level (e.g., DEBUG, INFO).\n contains (Optional[str]): Return only logs that include this string in the message.\n regex (Optional[str]): Return logs that match this regular expression in the message.\n from_time (Optional[str]): ISO 8601 timestamp to filter logs not older than this.\n to_time (Optional[str]): ISO 8601 timestamp to filter logs not newer than this.\n tail (bool): If True, fetch the most recent log entries (like `tail`).\n\nReturns:\n JSONResponse: A JSON list of log entries.", + "operationId": "fastapi_logging_get_log_v1_logging_log_get", + "parameters": [ + { + "name": "limit", + "in": "query", + "required": false, + "schema": { + "type": "integer", + "description": "Maximum number of log entries to return.", + "default": 100, + "title": "Limit" + }, + "description": "Maximum number of log entries to return." + }, + { + "name": "level", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Filter by log level (e.g., INFO, ERROR).", + "title": "Level" + }, + "description": "Filter by log level (e.g., INFO, ERROR)." + }, + { + "name": "contains", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Filter logs containing this substring.", + "title": "Contains" + }, + "description": "Filter logs containing this substring." + }, + { + "name": "regex", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Filter logs by matching regex in message.", + "title": "Regex" + }, + "description": "Filter logs by matching regex in message." + }, + { + "name": "from_time", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Start time (ISO format) for filtering logs.", + "title": "From Time" + }, + "description": "Start time (ISO format) for filtering logs." + }, + { + "name": "to_time", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "End time (ISO format) for filtering logs.", + "title": "To Time" + }, + "description": "End time (ISO format) for filtering logs." + }, + { + "name": "tail", + "in": "query", + "required": false, + "schema": { + "type": "boolean", + "description": "If True, returns the most recent lines (tail mode).", + "default": false, + "title": "Tail" + }, + "description": "If True, returns the most recent lines (tail mode)." + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/v1/measurement/keys": { + "get": { + "tags": [ + "measurement" + ], + "summary": "Fastapi Measurement Keys Get", + "description": "Get a list of available measurement keys.", + "operationId": "fastapi_measurement_keys_get_v1_measurement_keys_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Response Fastapi Measurement Keys Get V1 Measurement Keys Get" + } + } + } + } + } + } + }, + "/v1/measurement/load-mr/series/by-name": { + "get": { + "tags": [ + "measurement" + ], + "summary": "Fastapi Measurement Load Mr Series By Name Get", + "description": "Get the meter reading of given load name as series.", + "operationId": "fastapi_measurement_load_mr_series_by_name_get_v1_measurement_load_mr_series_by_name_get", + "parameters": [ + { + "name": "name", + "in": "query", + "required": true, + "schema": { + "type": "string", + "description": "Load name.", + "title": "Name" + }, + "description": "Load name." + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PydanticDateTimeSeries" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "put": { + "tags": [ + "measurement" + ], + "summary": "Fastapi Measurement Load Mr Series By Name Put", + "description": "Merge the meter readings series of given load name into EOS measurements at given datetime.", + "operationId": "fastapi_measurement_load_mr_series_by_name_put_v1_measurement_load_mr_series_by_name_put", + "parameters": [ + { + "name": "name", + "in": "query", + "required": true, + "schema": { + "type": "string", + "description": "Load name.", + "title": "Name" + }, + "description": "Load name." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PydanticDateTimeSeries" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PydanticDateTimeSeries" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/v1/measurement/load-mr/value/by-name": { + "put": { + "tags": [ + "measurement" + ], + "summary": "Fastapi Measurement Load Mr Value By Name Put", + "description": "Merge the meter reading of given load name and value into EOS measurements at given datetime.", + "operationId": "fastapi_measurement_load_mr_value_by_name_put_v1_measurement_load_mr_value_by_name_put", + "parameters": [ + { + "name": "datetime", + "in": "query", + "required": true, + "schema": { + "type": "string", + "description": "Datetime.", + "title": "Datetime" + }, + "description": "Datetime." + }, + { + "name": "name", + "in": "query", + "required": true, + "schema": { + "type": "string", + "description": "Load name.", + "title": "Name" + }, + "description": "Load name." + }, + { + "name": "value", + "in": "query", + "required": true, + "schema": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "title": "Value" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PydanticDateTimeSeries" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/v1/measurement/series": { + "get": { + "tags": [ + "measurement" + ], + "summary": "Fastapi Measurement Series Get", + "description": "Get the measurements of given key as series.", + "operationId": "fastapi_measurement_series_get_v1_measurement_series_get", + "parameters": [ + { + "name": "key", + "in": "query", + "required": true, + "schema": { + "type": "string", + "description": "Prediction key.", + "title": "Key" + }, + "description": "Prediction key." + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PydanticDateTimeSeries" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + }, + "put": { + "tags": [ + "measurement" + ], + "summary": "Fastapi Measurement Series Put", + "description": "Merge measurement given as series into given key.", + "operationId": "fastapi_measurement_series_put_v1_measurement_series_put", + "parameters": [ + { + "name": "key", + "in": "query", + "required": true, + "schema": { + "type": "string", + "description": "Prediction key.", + "title": "Key" + }, + "description": "Prediction key." + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PydanticDateTimeSeries" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PydanticDateTimeSeries" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/v1/measurement/value": { + "put": { + "tags": [ + "measurement" + ], + "summary": "Fastapi Measurement Value Put", + "description": "Merge the measurement of given key and value into EOS measurements at given datetime.", + "operationId": "fastapi_measurement_value_put_v1_measurement_value_put", + "parameters": [ + { + "name": "datetime", + "in": "query", + "required": true, + "schema": { + "type": "string", + "description": "Datetime.", + "title": "Datetime" + }, + "description": "Datetime." + }, + { + "name": "key", + "in": "query", + "required": true, + "schema": { + "type": "string", + "description": "Prediction key.", + "title": "Key" + }, + "description": "Prediction key." + }, + { + "name": "value", + "in": "query", + "required": true, + "schema": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "string" + } + ], + "title": "Value" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PydanticDateTimeSeries" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/v1/measurement/dataframe": { + "put": { + "tags": [ + "measurement" + ], + "summary": "Fastapi Measurement Dataframe Put", + "description": "Merge the measurement data given as dataframe into EOS measurements.", + "operationId": "fastapi_measurement_dataframe_put_v1_measurement_dataframe_put", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PydanticDateTimeDataFrame" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/v1/measurement/data": { + "put": { + "tags": [ + "measurement" + ], + "summary": "Fastapi Measurement Data Put", + "description": "Merge the measurement data given as datetime data into EOS measurements.", + "operationId": "fastapi_measurement_data_put_v1_measurement_data_put", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PydanticDateTimeData" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/v1/prediction/providers": { + "get": { + "tags": [ + "prediction" + ], + "summary": "Fastapi Prediction Providers Get", + "description": "Get a list of available prediction providers.\n\nArgs:\n enabled (bool): Return enabled/disabled providers. If unset, return all providers.", + "operationId": "fastapi_prediction_providers_get_v1_prediction_providers_get", + "parameters": [ + { + "name": "enabled", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Enabled" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "string" + }, + "title": "Response Fastapi Prediction Providers Get V1 Prediction Providers Get" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/v1/prediction/keys": { + "get": { + "tags": [ + "prediction" + ], + "summary": "Fastapi Prediction Keys Get", + "description": "Get a list of available prediction keys.", + "operationId": "fastapi_prediction_keys_get_v1_prediction_keys_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Response Fastapi Prediction Keys Get V1 Prediction Keys Get" + } + } + } + } + } + } + }, + "/v1/prediction/series": { + "get": { + "tags": [ + "prediction" + ], + "summary": "Fastapi Prediction Series Get", + "description": "Get prediction for given key within given date range as series.\n\nArgs:\n key (str): Prediction key\n start_datetime (Optional[str]): Starting datetime (inclusive).\n Defaults to start datetime of latest prediction.\n end_datetime (Optional[str]: Ending datetime (exclusive).\n Defaults to end datetime of latest prediction.", + "operationId": "fastapi_prediction_series_get_v1_prediction_series_get", + "parameters": [ + { + "name": "key", + "in": "query", + "required": true, + "schema": { + "type": "string", + "description": "Prediction key.", + "title": "Key" + }, + "description": "Prediction key." + }, + { + "name": "start_datetime", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Starting datetime (inclusive).", + "title": "Start Datetime" + }, + "description": "Starting datetime (inclusive)." + }, + { + "name": "end_datetime", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Ending datetime (exclusive).", + "title": "End Datetime" + }, + "description": "Ending datetime (exclusive)." + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PydanticDateTimeSeries" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/v1/prediction/dataframe": { + "get": { + "tags": [ + "prediction" + ], + "summary": "Fastapi Prediction Dataframe Get", + "description": "Get prediction for given key within given date range as series.\n\nArgs:\n key (str): Prediction key\n start_datetime (Optional[str]): Starting datetime (inclusive).\n Defaults to start datetime of latest prediction.\n end_datetime (Optional[str]: Ending datetime (exclusive).\n\nDefaults to end datetime of latest prediction.", + "operationId": "fastapi_prediction_dataframe_get_v1_prediction_dataframe_get", + "parameters": [ + { + "name": "keys", + "in": "query", + "required": true, + "schema": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Prediction keys.", + "title": "Keys" + }, + "description": "Prediction keys." + }, + { + "name": "start_datetime", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Starting datetime (inclusive).", + "title": "Start Datetime" + }, + "description": "Starting datetime (inclusive)." + }, + { + "name": "end_datetime", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Ending datetime (exclusive).", + "title": "End Datetime" + }, + "description": "Ending datetime (exclusive)." + }, + { + "name": "interval", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Time duration for each interval. Defaults to 1 hour.", + "title": "Interval" + }, + "description": "Time duration for each interval. Defaults to 1 hour." + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PydanticDateTimeDataFrame" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/v1/prediction/list": { + "get": { + "tags": [ + "prediction" + ], + "summary": "Fastapi Prediction List Get", + "description": "Get prediction for given key within given date range as value list.\n\nArgs:\n key (str): Prediction key\n start_datetime (Optional[str]): Starting datetime (inclusive).\n Defaults to start datetime of latest prediction.\n end_datetime (Optional[str]: Ending datetime (exclusive).\n Defaults to end datetime of latest prediction.\n interval (Optional[str]): Time duration for each interval.\n Defaults to 1 hour.", + "operationId": "fastapi_prediction_list_get_v1_prediction_list_get", + "parameters": [ + { + "name": "key", + "in": "query", + "required": true, + "schema": { + "type": "string", + "description": "Prediction key.", + "title": "Key" + }, + "description": "Prediction key." + }, + { + "name": "start_datetime", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Starting datetime (inclusive).", + "title": "Start Datetime" + }, + "description": "Starting datetime (inclusive)." + }, + { + "name": "end_datetime", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Ending datetime (exclusive).", + "title": "End Datetime" + }, + "description": "Ending datetime (exclusive)." + }, + { + "name": "interval", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "description": "Time duration for each interval. Defaults to 1 hour.", + "title": "Interval" + }, + "description": "Time duration for each interval. Defaults to 1 hour." + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": {}, + "title": "Response Fastapi Prediction List Get V1 Prediction List Get" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/v1/prediction/import/{provider_id}": { + "put": { + "tags": [ + "prediction" + ], + "summary": "Fastapi Prediction Import Provider", + "description": "Import prediction for given provider ID.\n\nArgs:\n provider_id: ID of provider to update.\n data: Prediction data.\n force_enable: Update data even if provider is disabled.\n Defaults to False.", + "operationId": "fastapi_prediction_import_provider_v1_prediction_import__provider_id__put", + "parameters": [ + { + "name": "provider_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "description": "Provider ID.", + "title": "Provider Id" + }, + "description": "Provider ID." + }, + { + "name": "force_enable", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Force Enable" + } + } + ], + "requestBody": { + "content": { + "application/json": { + "schema": { + "anyOf": [ + { + "$ref": "#/components/schemas/PydanticDateTimeDataFrame" + }, + { + "$ref": "#/components/schemas/PydanticDateTimeData" + }, + { + "type": "object", + "additionalProperties": true + }, + { + "type": "null" + } + ], + "title": "Data" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/v1/prediction/update": { + "post": { + "tags": [ + "prediction" + ], + "summary": "Fastapi Prediction Update", + "description": "Update predictions for all providers.\n\nArgs:\n force_update: Update data even if it is already cached.\n Defaults to False.\n force_enable: Update data even if provider is disabled.\n Defaults to False.", + "operationId": "fastapi_prediction_update_v1_prediction_update_post", + "parameters": [ + { + "name": "force_update", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": false, + "title": "Force Update" + } + }, + { + "name": "force_enable", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": false, + "title": "Force Enable" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/v1/prediction/update/{provider_id}": { + "post": { + "tags": [ + "prediction" + ], + "summary": "Fastapi Prediction Update Provider", + "description": "Update predictions for given provider ID.\n\nArgs:\n provider_id: ID of provider to update.\n force_update: Update data even if it is already cached.\n Defaults to False.\n force_enable: Update data even if provider is disabled.\n Defaults to False.", + "operationId": "fastapi_prediction_update_provider_v1_prediction_update__provider_id__post", + "parameters": [ + { + "name": "provider_id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "title": "Provider Id" + } + }, + { + "name": "force_update", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": false, + "title": "Force Update" + } + }, + { + "name": "force_enable", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": false, + "title": "Force Enable" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": {} + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/strompreis": { + "get": { + "tags": [ + "prediction" + ], + "summary": "Fastapi Strompreis", + "description": "Deprecated: Electricity Market Price Prediction per Wh (\u20ac/Wh).\n\nElectricity prices start at 00.00.00 today and are provided for 48 hours.\nIf no prices are available the missing ones at the start of the series are\nfilled with the first available price.\n\nNote:\n Electricity price charges are added.\n\nNote:\n Set ElecPriceAkkudoktor as provider, then update data with\n '/v1/prediction/update'\n and then request data with\n '/v1/prediction/list?key=elecprice_marketprice_wh' or\n '/v1/prediction/list?key=elecprice_marketprice_kwh' instead.", + "operationId": "fastapi_strompreis_strompreis_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Response Fastapi Strompreis Strompreis Get" + } + } + } + } + } + } + }, + "/gesamtlast": { + "post": { + "tags": [ + "prediction" + ], + "summary": "Fastapi Gesamtlast", + "description": "Deprecated: Total Load Prediction with adjustment.\n\nEndpoint to handle total load prediction adjusted by latest measured data.\n\nTotal load prediction starts at 00.00.00 today and is provided for 48 hours.\nIf no prediction values are available the missing ones at the start of the series are\nfilled with the first available prediction value.\n\nNote:\n Use '/v1/prediction/list?key=load_mean_adjusted' instead.\n Load energy meter readings to be added to EOS measurement by:\n '/v1/measurement/load-mr/value/by-name' or\n '/v1/measurement/value'", + "operationId": "fastapi_gesamtlast_gesamtlast_post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/GesamtlastRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Response Fastapi Gesamtlast Gesamtlast Post" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/gesamtlast_simple": { + "get": { + "tags": [ + "prediction" + ], + "summary": "Fastapi Gesamtlast Simple", + "description": "Deprecated: Total Load Prediction.\n\nEndpoint to handle total load prediction.\n\nTotal load prediction starts at 00.00.00 today and is provided for 48 hours.\nIf no prediction values are available the missing ones at the start of the series are\nfilled with the first available prediction value.\n\nArgs:\n year_energy (float): Yearly energy consumption in Wh.\n\nNote:\n Set LoadAkkudoktor as provider, then update data with\n '/v1/prediction/update'\n and then request data with\n '/v1/prediction/list?key=load_mean' instead.", + "operationId": "fastapi_gesamtlast_simple_gesamtlast_simple_get", + "parameters": [ + { + "name": "year_energy", + "in": "query", + "required": true, + "schema": { + "type": "number", + "title": "Year Energy" + } + } + ], + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "type": "number" + }, + "title": "Response Fastapi Gesamtlast Simple Gesamtlast Simple Get" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/pvforecast": { + "get": { + "tags": [ + "prediction" + ], + "summary": "Fastapi Pvforecast", + "description": "Deprecated: PV Forecast Prediction.\n\nEndpoint to handle PV forecast prediction.\n\nPVForecast starts at 00.00.00 today and is provided for 48 hours.\nIf no forecast values are available the missing ones at the start of the series are\nfilled with the first available forecast value.\n\nNote:\n Set PVForecastAkkudoktor as provider, then update data with\n '/v1/prediction/update'\n and then request data with\n '/v1/prediction/list?key=pvforecast_ac_power' and\n '/v1/prediction/list?key=pvforecastakkudoktor_temp_air' instead.", + "operationId": "fastapi_pvforecast_pvforecast_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ForecastResponse" + } + } + } + } + } + } + }, + "/optimize": { + "post": { + "tags": [ + "optimize" + ], + "summary": "Fastapi Optimize", + "operationId": "fastapi_optimize_optimize_post", + "parameters": [ + { + "name": "start_hour", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "description": "Defaults to current hour of the day.", + "title": "Start Hour" + }, + "description": "Defaults to current hour of the day." + }, + { + "name": "ngen", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Ngen" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OptimizationParameters" + } + } + } + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OptimizeResponse" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, + "/visualization_results.pdf": { + "get": { + "tags": [ + "optimize" + ], + "summary": "Get Pdf", + "operationId": "get_pdf_visualization_results_pdf_get", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/pdf": { + "schema": { + "type": "string" + } + } + } + } + } + } } + }, + "components": { + "schemas": { + "BaseBatteryParameters": { + "properties": { + "device_id": { + "type": "string", + "title": "Device Id", + "description": "ID of battery", + "examples": [ + "battery1" + ] + }, + "hours": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Hours", + "description": "Number of prediction hours. Defaults to global config prediction hours.", + "examples": [ + null + ] + }, + "capacity_wh": { + "type": "integer", + "exclusiveMinimum": 0.0, + "title": "Capacity Wh", + "description": "An integer representing the capacity of the battery in watt-hours.", + "examples": [ + 8000 + ] + }, + "charging_efficiency": { + "type": "number", + "maximum": 1.0, + "exclusiveMinimum": 0.0, + "title": "Charging Efficiency", + "description": "A float representing the charging efficiency of the battery.", + "default": 0.88 + }, + "discharging_efficiency": { + "type": "number", + "maximum": 1.0, + "exclusiveMinimum": 0.0, + "title": "Discharging Efficiency", + "description": "A float representing the discharge efficiency of the battery.", + "default": 0.88 + }, + "max_charge_power_w": { + "anyOf": [ + { + "type": "number", + "exclusiveMinimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Max Charge Power W", + "description": "Maximum charging power in watts.", + "default": 5000 + }, + "initial_soc_percentage": { + "type": "integer", + "maximum": 100.0, + "minimum": 0.0, + "title": "Initial Soc Percentage", + "description": "An integer representing the state of charge of the battery at the **start** of the current hour (not the current state).", + "default": 0, + "examples": [ + 42 + ] + }, + "min_soc_percentage": { + "type": "integer", + "maximum": 100.0, + "minimum": 0.0, + "title": "Min Soc Percentage", + "description": "An integer representing the minimum state of charge (SOC) of the battery in percentage.", + "default": 0, + "examples": [ + 10 + ] + }, + "max_soc_percentage": { + "type": "integer", + "maximum": 100.0, + "minimum": 0.0, + "title": "Max Soc Percentage", + "description": "An integer representing the maximum state of charge (SOC) of the battery in percentage.", + "default": 100 + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "device_id", + "capacity_wh" + ], + "title": "BaseBatteryParameters", + "description": "Battery Device Simulation Configuration." + }, + "CacheCommonSettings": { + "properties": { + "subpath": { + "anyOf": [ + { + "type": "string", + "format": "path" + }, + { + "type": "null" + } + ], + "title": "Subpath", + "description": "Sub-path for the EOS cache data directory.", + "default": "cache" + }, + "cleanup_interval": { + "type": "number", + "title": "Cleanup Interval", + "description": "Intervall in seconds for EOS file cache cleanup.", + "default": 300 + } + }, + "type": "object", + "title": "CacheCommonSettings", + "description": "Cache Configuration." + }, + "ConfigEOS": { + "properties": { + "general": { + "$ref": "#/components/schemas/GeneralSettings-Output", + "default": { + "data_output_subpath": "output", + "latitude": 52.52, + "longitude": 13.405, + "timezone": "Europe/Berlin", + "config_folder_path": "/home/user/.config/net.akkudoktoreos.net", + "config_file_path": "/home/user/.config/net.akkudoktoreos.net/EOS.config.json" + } + }, + "cache": { + "$ref": "#/components/schemas/CacheCommonSettings", + "default": { + "subpath": "cache", + "cleanup_interval": 300.0 + } + }, + "ems": { + "$ref": "#/components/schemas/EnergyManagementCommonSettings", + "default": { + "startup_delay": 5.0 + } + }, + "logging": { + "$ref": "#/components/schemas/LoggingCommonSettings-Output", + "default": { + "file_path": "/home/user/.local/share/net.akkudoktoreos.net/output/eos.log" + } + }, + "devices": { + "$ref": "#/components/schemas/DevicesCommonSettings", + "default": {} + }, + "measurement": { + "$ref": "#/components/schemas/MeasurementCommonSettings", + "default": {} + }, + "optimization": { + "$ref": "#/components/schemas/OptimizationCommonSettings", + "default": { + "hours": 48, + "penalty": 10, + "ev_available_charge_rates_percent": [ + 0.0, + 0.375, + 0.5, + 0.625, + 0.75, + 0.875, + 1.0 + ] + } + }, + "prediction": { + "$ref": "#/components/schemas/PredictionCommonSettings", + "default": { + "hours": 48, + "historic_hours": 48 + } + }, + "elecprice": { + "$ref": "#/components/schemas/ElecPriceCommonSettings", + "default": {} + }, + "load": { + "$ref": "#/components/schemas/LoadCommonSettings", + "default": {} + }, + "pvforecast": { + "$ref": "#/components/schemas/PVForecastCommonSettings-Output", + "default": { + "max_planes": 0, + "planes_peakpower": [], + "planes_azimuth": [], + "planes_tilt": [], + "planes_userhorizon": [], + "planes_inverter_paco": [] + } + }, + "weather": { + "$ref": "#/components/schemas/WeatherCommonSettings", + "default": {} + }, + "server": { + "$ref": "#/components/schemas/ServerCommonSettings", + "default": { + "host": "127.0.0.1", + "port": 8503, + "verbose": false, + "startup_eosdash": true, + "eosdash_host": "127.0.0.1", + "eosdash_port": 8504 + } + }, + "utils": { + "$ref": "#/components/schemas/UtilsCommonSettings", + "default": {} + } + }, + "additionalProperties": false, + "type": "object", + "title": "ConfigEOS", + "description": "Singleton configuration handler for the EOS application.\n\nConfigEOS extends `SettingsEOS` with support for default configuration paths and automatic\ninitialization.\n\n`ConfigEOS` ensures that only one instance of the class is created throughout the application,\nallowing consistent access to EOS configuration settings. This singleton instance loads\nconfiguration data from a predefined set of directories or creates a default configuration if\nnone is found.\n\nInitialization Process:\n - Upon instantiation, the singleton instance attempts to load a configuration file in this order:\n 1. The directory specified by the `EOS_CONFIG_DIR` environment variable\n 2. The directory specified by the `EOS_DIR` environment variable.\n 3. A platform specific default directory for EOS.\n 4. The current working directory.\n - The first available configuration file found in these directories is loaded.\n - If no configuration file is found, a default configuration file is created in the platform\n specific default directory, and default settings are loaded into it.\n\nAttributes from the loaded configuration are accessible directly as instance attributes of\n`ConfigEOS`, providing a centralized, shared configuration object for EOS.\n\nSingleton Behavior:\n - This class uses the `SingletonMixin` to ensure that all requests for `ConfigEOS` return\n the same instance, which contains the most up-to-date configuration. Modifying the configuration\n in one part of the application reflects across all references to this class.\n\nAttributes:\n config_folder_path (Optional[Path]): Path to the configuration directory.\n config_file_path (Optional[Path]): Path to the configuration file.\n\nRaises:\n FileNotFoundError: If no configuration file is found, and creating a default configuration fails.\n\nExample:\n To initialize and access configuration attributes (only one instance is created):\n ```python\n config_eos = ConfigEOS() # Always returns the same instance\n print(config_eos.prediction.hours) # Access a setting from the loaded configuration\n ```" + }, + "DevicesCommonSettings": { + "properties": { + "batteries": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/BaseBatteryParameters" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Batteries", + "description": "List of battery/ev devices", + "examples": [ + [ + { + "capacity_wh": 8000, + "device_id": "battery1" + } + ] + ] + }, + "inverters": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/InverterParameters" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Inverters", + "description": "List of inverters", + "examples": [ + [] + ] + }, + "home_appliances": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/HomeApplianceParameters" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Home Appliances", + "description": "List of home appliances", + "examples": [ + [] + ] + } + }, + "type": "object", + "title": "DevicesCommonSettings", + "description": "Base configuration for devices simulation settings." + }, + "ElecPriceCommonSettings": { + "properties": { + "provider": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Provider", + "description": "Electricity price provider id of provider to be used.", + "examples": [ + "ElecPriceAkkudoktor" + ] + }, + "charges_kwh": { + "anyOf": [ + { + "type": "number", + "minimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Charges Kwh", + "description": "Electricity price charges (\u20ac/kWh).", + "examples": [ + 0.21 + ] + }, + "provider_settings": { + "anyOf": [ + { + "$ref": "#/components/schemas/ElecPriceImportCommonSettings" + }, + { + "type": "null" + } + ], + "description": "Provider settings", + "examples": [ + null + ] + } + }, + "type": "object", + "title": "ElecPriceCommonSettings", + "description": "Electricity Price Prediction Configuration." + }, + "ElecPriceImportCommonSettings": { + "properties": { + "import_file_path": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "format": "path" + }, + { + "type": "null" + } + ], + "title": "Import File Path", + "description": "Path to the file to import elecprice data from.", + "examples": [ + null, + "/path/to/prices.json" + ] + }, + "import_json": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Import Json", + "description": "JSON string, dictionary of electricity price forecast value lists.", + "examples": [ + "{\"elecprice_marketprice_wh\": [0.0003384, 0.0003318, 0.0003284]}" + ] + } + }, + "type": "object", + "title": "ElecPriceImportCommonSettings", + "description": "Common settings for elecprice data import from file or JSON String." + }, + "ElectricVehicleParameters": { + "properties": { + "device_id": { + "type": "string", + "title": "Device Id", + "description": "ID of electric vehicle", + "examples": [ + "ev1" + ] + }, + "hours": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Hours", + "description": "Number of prediction hours. Defaults to global config prediction hours.", + "examples": [ + null + ] + }, + "capacity_wh": { + "type": "integer", + "exclusiveMinimum": 0.0, + "title": "Capacity Wh", + "description": "An integer representing the capacity of the battery in watt-hours.", + "examples": [ + 8000 + ] + }, + "charging_efficiency": { + "type": "number", + "maximum": 1.0, + "exclusiveMinimum": 0.0, + "title": "Charging Efficiency", + "description": "A float representing the charging efficiency of the battery.", + "default": 0.88 + }, + "discharging_efficiency": { + "type": "number", + "maximum": 1.0, + "exclusiveMinimum": 0.0, + "title": "Discharging Efficiency", + "description": "A float representing the discharge efficiency of the battery.", + "default": 1.0 + }, + "max_charge_power_w": { + "anyOf": [ + { + "type": "number", + "exclusiveMinimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Max Charge Power W", + "description": "Maximum charging power in watts.", + "default": 5000 + }, + "initial_soc_percentage": { + "type": "integer", + "maximum": 100.0, + "minimum": 0.0, + "title": "Initial Soc Percentage", + "description": "An integer representing the current state of charge (SOC) of the battery in percentage.", + "default": 0, + "examples": [ + 42 + ] + }, + "min_soc_percentage": { + "type": "integer", + "maximum": 100.0, + "minimum": 0.0, + "title": "Min Soc Percentage", + "description": "An integer representing the minimum state of charge (SOC) of the battery in percentage.", + "default": 0, + "examples": [ + 10 + ] + }, + "max_soc_percentage": { + "type": "integer", + "maximum": 100.0, + "minimum": 0.0, + "title": "Max Soc Percentage", + "description": "An integer representing the maximum state of charge (SOC) of the battery in percentage.", + "default": 100 + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "device_id", + "capacity_wh" + ], + "title": "ElectricVehicleParameters", + "description": "Battery Electric Vehicle Device Simulation Configuration." + }, + "ElectricVehicleResult": { + "properties": { + "device_id": { + "type": "string", + "title": "Device Id", + "description": "ID of electric vehicle", + "examples": [ + "ev1" + ] + }, + "hours": { + "type": "integer", + "exclusiveMinimum": 0.0, + "title": "Hours", + "description": "Number of hours in the simulation.", + "examples": [ + 24 + ] + }, + "charge_array": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Charge Array", + "description": "Hourly charging status (0 for no charging, 1 for charging)." + }, + "discharge_array": { + "items": { + "type": "integer" + }, + "type": "array", + "title": "Discharge Array", + "description": "Hourly discharging status (0 for no discharging, 1 for discharging)." + }, + "discharging_efficiency": { + "type": "number", + "title": "Discharging Efficiency", + "description": "The discharge efficiency as a float.." + }, + "capacity_wh": { + "type": "integer", + "title": "Capacity Wh", + "description": "Capacity of the EV\u2019s battery in watt-hours." + }, + "charging_efficiency": { + "type": "number", + "title": "Charging Efficiency", + "description": "Charging efficiency as a float.." + }, + "max_charge_power_w": { + "type": "integer", + "title": "Max Charge Power W", + "description": "Maximum charging power in watts." + }, + "soc_wh": { + "type": "number", + "title": "Soc Wh", + "description": "State of charge of the battery in watt-hours at the start of the simulation." + }, + "initial_soc_percentage": { + "type": "integer", + "title": "Initial Soc Percentage", + "description": "State of charge at the start of the simulation in percentage." + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "device_id", + "hours", + "charge_array", + "discharge_array", + "discharging_efficiency", + "capacity_wh", + "charging_efficiency", + "max_charge_power_w", + "soc_wh", + "initial_soc_percentage" + ], + "title": "ElectricVehicleResult", + "description": "Result class containing information related to the electric vehicle's charging and discharging behavior." + }, + "EnergyManagementCommonSettings": { + "properties": { + "startup_delay": { + "type": "number", + "minimum": 1.0, + "title": "Startup Delay", + "description": "Startup delay in seconds for EOS energy management runs.", + "default": 5 + }, + "interval": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Interval", + "description": "Intervall in seconds between EOS energy management runs.", + "examples": [ + "300" + ] + } + }, + "type": "object", + "title": "EnergyManagementCommonSettings", + "description": "Energy Management Configuration." + }, + "EnergyManagementParameters": { + "properties": { + "pv_prognose_wh": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Pv Prognose Wh", + "description": "An array of floats representing the forecasted photovoltaic output in watts for different time intervals." + }, + "strompreis_euro_pro_wh": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Strompreis Euro Pro Wh", + "description": "An array of floats representing the electricity price in euros per watt-hour for different time intervals." + }, + "einspeiseverguetung_euro_pro_wh": { + "anyOf": [ + { + "items": { + "type": "number" + }, + "type": "array" + }, + { + "type": "number" + } + ], + "title": "Einspeiseverguetung Euro Pro Wh", + "description": "A float or array of floats representing the feed-in compensation in euros per watt-hour." + }, + "preis_euro_pro_wh_akku": { + "type": "number", + "title": "Preis Euro Pro Wh Akku", + "description": "A float representing the cost of battery energy per watt-hour." + }, + "gesamtlast": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Gesamtlast", + "description": "An array of floats representing the total load (consumption) in watts for different time intervals." + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "pv_prognose_wh", + "strompreis_euro_pro_wh", + "einspeiseverguetung_euro_pro_wh", + "preis_euro_pro_wh_akku", + "gesamtlast" + ], + "title": "EnergyManagementParameters" + }, + "ForecastResponse": { + "properties": { + "temperature": { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array", + "title": "Temperature" + }, + "pvpower": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Pvpower" + } + }, + "type": "object", + "required": [ + "temperature", + "pvpower" + ], + "title": "ForecastResponse" + }, + "GeneralSettings-Input": { + "properties": { + "data_folder_path": { + "anyOf": [ + { + "type": "string", + "format": "path" + }, + { + "type": "null" + } + ], + "title": "Data Folder Path", + "description": "Path to EOS data directory.", + "examples": [ + null, + "/home/eos/data" + ] + }, + "data_output_subpath": { + "anyOf": [ + { + "type": "string", + "format": "path" + }, + { + "type": "null" + } + ], + "title": "Data Output Subpath", + "description": "Sub-path for the EOS output data directory.", + "default": "output" + }, + "latitude": { + "anyOf": [ + { + "type": "number", + "maximum": 90.0, + "minimum": -90.0 + }, + { + "type": "null" + } + ], + "title": "Latitude", + "description": "Latitude in decimal degrees, between -90 and 90, north is positive (ISO 19115) (\u00b0)", + "default": 52.52 + }, + "longitude": { + "anyOf": [ + { + "type": "number", + "maximum": 180.0, + "minimum": -180.0 + }, + { + "type": "null" + } + ], + "title": "Longitude", + "description": "Longitude in decimal degrees, within -180 to 180 (\u00b0)", + "default": 13.405 + } + }, + "type": "object", + "title": "GeneralSettings", + "description": "Settings for common configuration.\n\nGeneral configuration to set directories of cache and output files and system location (latitude\nand longitude).\nValidators ensure each parameter is within a specified range. A computed property, `timezone`,\ndetermines the time zone based on latitude and longitude.\n\nAttributes:\n latitude (Optional[float]): Latitude in degrees, must be between -90 and 90.\n longitude (Optional[float]): Longitude in degrees, must be between -180 and 180.\n\nProperties:\n timezone (Optional[str]): Computed time zone string based on the specified latitude\n and longitude." + }, + "GeneralSettings-Output": { + "properties": { + "data_folder_path": { + "anyOf": [ + { + "type": "string", + "format": "path" + }, + { + "type": "null" + } + ], + "title": "Data Folder Path", + "description": "Path to EOS data directory.", + "examples": [ + null, + "/home/eos/data" + ] + }, + "data_output_subpath": { + "anyOf": [ + { + "type": "string", + "format": "path" + }, + { + "type": "null" + } + ], + "title": "Data Output Subpath", + "description": "Sub-path for the EOS output data directory.", + "default": "output" + }, + "latitude": { + "anyOf": [ + { + "type": "number", + "maximum": 90.0, + "minimum": -90.0 + }, + { + "type": "null" + } + ], + "title": "Latitude", + "description": "Latitude in decimal degrees, between -90 and 90, north is positive (ISO 19115) (\u00b0)", + "default": 52.52 + }, + "longitude": { + "anyOf": [ + { + "type": "number", + "maximum": 180.0, + "minimum": -180.0 + }, + { + "type": "null" + } + ], + "title": "Longitude", + "description": "Longitude in decimal degrees, within -180 to 180 (\u00b0)", + "default": 13.405 + }, + "timezone": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Timezone", + "description": "Compute timezone based on latitude and longitude.", + "readOnly": true + }, + "data_output_path": { + "anyOf": [ + { + "type": "string", + "format": "path" + }, + { + "type": "null" + } + ], + "title": "Data Output Path", + "description": "Compute data_output_path based on data_folder_path.", + "readOnly": true + }, + "config_folder_path": { + "anyOf": [ + { + "type": "string", + "format": "path" + }, + { + "type": "null" + } + ], + "title": "Config Folder Path", + "description": "Path to EOS configuration directory.", + "readOnly": true + }, + "config_file_path": { + "anyOf": [ + { + "type": "string", + "format": "path" + }, + { + "type": "null" + } + ], + "title": "Config File Path", + "description": "Path to EOS configuration file.", + "readOnly": true + } + }, + "type": "object", + "required": [ + "timezone", + "data_output_path", + "config_folder_path", + "config_file_path" + ], + "title": "GeneralSettings", + "description": "Settings for common configuration.\n\nGeneral configuration to set directories of cache and output files and system location (latitude\nand longitude).\nValidators ensure each parameter is within a specified range. A computed property, `timezone`,\ndetermines the time zone based on latitude and longitude.\n\nAttributes:\n latitude (Optional[float]): Latitude in degrees, must be between -90 and 90.\n longitude (Optional[float]): Longitude in degrees, must be between -180 and 180.\n\nProperties:\n timezone (Optional[str]): Computed time zone string based on the specified latitude\n and longitude." + }, + "GesamtlastRequest": { + "properties": { + "year_energy": { + "type": "number", + "title": "Year Energy" + }, + "measured_data": { + "items": { + "additionalProperties": true, + "type": "object" + }, + "type": "array", + "title": "Measured Data" + }, + "hours": { + "type": "integer", + "title": "Hours" + } + }, + "type": "object", + "required": [ + "year_energy", + "measured_data", + "hours" + ], + "title": "GesamtlastRequest" + }, + "HTTPValidationError": { + "properties": { + "detail": { + "items": { + "$ref": "#/components/schemas/ValidationError" + }, + "type": "array", + "title": "Detail" + } + }, + "type": "object", + "title": "HTTPValidationError" + }, + "HomeApplianceParameters": { + "properties": { + "device_id": { + "type": "string", + "title": "Device Id", + "description": "ID of home appliance", + "examples": [ + "dishwasher" + ] + }, + "hours": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Hours", + "description": "Number of prediction hours. Defaults to global config prediction hours.", + "examples": [ + null + ] + }, + "consumption_wh": { + "type": "integer", + "exclusiveMinimum": 0.0, + "title": "Consumption Wh", + "description": "An integer representing the energy consumption of a household device in watt-hours.", + "examples": [ + 2000 + ] + }, + "duration_h": { + "type": "integer", + "exclusiveMinimum": 0.0, + "title": "Duration H", + "description": "An integer representing the usage duration of a household device in hours.", + "examples": [ + 3 + ] + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "device_id", + "consumption_wh", + "duration_h" + ], + "title": "HomeApplianceParameters", + "description": "Home Appliance Device Simulation Configuration." + }, + "InverterParameters": { + "properties": { + "device_id": { + "type": "string", + "title": "Device Id", + "description": "ID of inverter", + "examples": [ + "inverter1" + ] + }, + "hours": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Hours", + "description": "Number of prediction hours. Defaults to global config prediction hours.", + "examples": [ + null + ] + }, + "max_power_wh": { + "type": "number", + "exclusiveMinimum": 0.0, + "title": "Max Power Wh", + "examples": [ + 10000 + ] + }, + "battery_id": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Battery Id", + "description": "ID of battery", + "examples": [ + null, + "battery1" + ] + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "device_id", + "max_power_wh" + ], + "title": "InverterParameters", + "description": "Inverter Device Simulation Configuration." + }, + "LoadAkkudoktorCommonSettings": { + "properties": { + "loadakkudoktor_year_energy": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Loadakkudoktor Year Energy", + "description": "Yearly energy consumption (kWh).", + "examples": [ + 40421 + ] + } + }, + "type": "object", + "title": "LoadAkkudoktorCommonSettings", + "description": "Common settings for load data import from file." + }, + "LoadCommonSettings": { + "properties": { + "provider": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Provider", + "description": "Load provider id of provider to be used.", + "examples": [ + "LoadAkkudoktor" + ] + }, + "provider_settings": { + "anyOf": [ + { + "$ref": "#/components/schemas/LoadAkkudoktorCommonSettings" + }, + { + "$ref": "#/components/schemas/LoadImportCommonSettings" + }, + { + "type": "null" + } + ], + "title": "Provider Settings", + "description": "Provider settings", + "examples": [ + null + ] + } + }, + "type": "object", + "title": "LoadCommonSettings", + "description": "Load Prediction Configuration." + }, + "LoadImportCommonSettings": { + "properties": { + "import_file_path": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "format": "path" + }, + { + "type": "null" + } + ], + "title": "Import File Path", + "description": "Path to the file to import load data from.", + "examples": [ + null, + "/path/to/yearly_load.json" + ] + }, + "import_json": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Import Json", + "description": "JSON string, dictionary of load forecast value lists.", + "examples": [ + "{\"load0_mean\": [676.71, 876.19, 527.13]}" + ] + } + }, + "type": "object", + "title": "LoadImportCommonSettings", + "description": "Common settings for load data import from file or JSON string." + }, + "LoggingCommonSettings-Input": { + "properties": { + "level": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Level", + "deprecated": true + }, + "console_level": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Console Level", + "description": "Logging level when logging to console.", + "examples": [ + "TRACE", + "DEBUG", + "INFO", + "WARNING", + "ERROR", + "CRITICAL" + ] + }, + "file_level": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "File Level", + "description": "Logging level when logging to file.", + "examples": [ + "TRACE", + "DEBUG", + "INFO", + "WARNING", + "ERROR", + "CRITICAL" + ] + } + }, + "type": "object", + "title": "LoggingCommonSettings", + "description": "Logging Configuration." + }, + "LoggingCommonSettings-Output": { + "properties": { + "level": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Level", + "deprecated": true + }, + "console_level": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Console Level", + "description": "Logging level when logging to console.", + "examples": [ + "TRACE", + "DEBUG", + "INFO", + "WARNING", + "ERROR", + "CRITICAL" + ] + }, + "file_level": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "File Level", + "description": "Logging level when logging to file.", + "examples": [ + "TRACE", + "DEBUG", + "INFO", + "WARNING", + "ERROR", + "CRITICAL" + ] + }, + "file_path": { + "anyOf": [ + { + "type": "string", + "format": "path" + }, + { + "type": "null" + } + ], + "title": "File Path", + "description": "Computed log file path based on data output path.", + "readOnly": true + } + }, + "type": "object", + "required": [ + "file_path" + ], + "title": "LoggingCommonSettings", + "description": "Logging Configuration." + }, + "MeasurementCommonSettings": { + "properties": { + "load0_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Load0 Name", + "description": "Name of the load0 source", + "examples": [ + "Household", + "Heat Pump" + ] + }, + "load1_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Load1 Name", + "description": "Name of the load1 source", + "examples": [ + null + ] + }, + "load2_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Load2 Name", + "description": "Name of the load2 source", + "examples": [ + null + ] + }, + "load3_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Load3 Name", + "description": "Name of the load3 source", + "examples": [ + null + ] + }, + "load4_name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Load4 Name", + "description": "Name of the load4 source", + "examples": [ + null + ] + } + }, + "type": "object", + "title": "MeasurementCommonSettings", + "description": "Measurement Configuration." + }, + "OptimizationCommonSettings": { + "properties": { + "hours": { + "anyOf": [ + { + "type": "integer", + "minimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Hours", + "description": "Number of hours into the future for optimizations.", + "default": 48 + }, + "penalty": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Penalty", + "description": "Penalty factor used in optimization.", + "default": 10 + }, + "ev_available_charge_rates_percent": { + "anyOf": [ + { + "items": { + "type": "number" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Ev Available Charge Rates Percent", + "description": "Charge rates available for the EV in percent of maximum charge.", + "default": [ + 0.0, + 0.375, + 0.5, + 0.625, + 0.75, + 0.875, + 1.0 + ] + } + }, + "type": "object", + "title": "OptimizationCommonSettings", + "description": "General Optimization Configuration.\n\nAttributes:\n hours (int): Number of hours for optimizations." + }, + "OptimizationParameters": { + "properties": { + "ems": { + "$ref": "#/components/schemas/EnergyManagementParameters" + }, + "pv_akku": { + "anyOf": [ + { + "$ref": "#/components/schemas/SolarPanelBatteryParameters" + }, + { + "type": "null" + } + ] + }, + "inverter": { + "anyOf": [ + { + "$ref": "#/components/schemas/InverterParameters" + }, + { + "type": "null" + } + ] + }, + "eauto": { + "anyOf": [ + { + "$ref": "#/components/schemas/ElectricVehicleParameters" + }, + { + "type": "null" + } + ] + }, + "dishwasher": { + "anyOf": [ + { + "$ref": "#/components/schemas/HomeApplianceParameters" + }, + { + "type": "null" + } + ] + }, + "temperature_forecast": { + "anyOf": [ + { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Temperature Forecast", + "description": "An array of floats representing the temperature forecast in degrees Celsius for different time intervals." + }, + "start_solution": { + "anyOf": [ + { + "items": { + "type": "number" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Start Solution", + "description": "Can be `null` or contain a previous solution (if available)." + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "ems", + "pv_akku", + "inverter", + "eauto" + ], + "title": "OptimizationParameters" + }, + "OptimizeResponse": { + "properties": { + "ac_charge": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Ac Charge", + "description": "Array with AC charging values as relative power (0-1), other values set to 0." + }, + "dc_charge": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Dc Charge", + "description": "Array with DC charging values as relative power (0-1), other values set to 0." + }, + "discharge_allowed": { + "items": { + "type": "integer" + }, + "type": "array", + "title": "Discharge Allowed", + "description": "Array with discharge values (1 for discharge, 0 otherwise)." + }, + "eautocharge_hours_float": { + "anyOf": [ + { + "items": { + "type": "number" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Eautocharge Hours Float", + "description": "TBD" + }, + "result": { + "$ref": "#/components/schemas/SimulationResult" + }, + "eauto_obj": { + "anyOf": [ + { + "$ref": "#/components/schemas/ElectricVehicleResult" + }, + { + "type": "null" + } + ] + }, + "start_solution": { + "anyOf": [ + { + "items": { + "type": "number" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Start Solution", + "description": "An array of binary values (0 or 1) representing a possible starting solution for the simulation." + }, + "washingstart": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Washingstart", + "description": "Can be `null` or contain an object representing the start of washing (if applicable)." + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "ac_charge", + "dc_charge", + "discharge_allowed", + "eautocharge_hours_float", + "result", + "eauto_obj" + ], + "title": "OptimizeResponse", + "description": "**Note**: The first value of \"Last_Wh_per_hour\", \"Netzeinspeisung_Wh_per_hour\", and \"Netzbezug_Wh_per_hour\", will be set to null in the JSON output and represented as NaN or None in the corresponding classes' data returns. This approach is adopted to ensure that the current hour's processing remains unchanged." + }, + "PVForecastCommonSettings-Input": { + "properties": { + "provider": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Provider", + "description": "PVForecast provider id of provider to be used.", + "examples": [ + "PVForecastAkkudoktor" + ] + }, + "provider_settings": { + "anyOf": [ + { + "$ref": "#/components/schemas/PVForecastImportCommonSettings" + }, + { + "type": "null" + } + ], + "description": "Provider settings", + "examples": [ + null + ] + }, + "planes": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/PVForecastPlaneSetting" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Planes", + "description": "Plane configuration.", + "examples": [ + [ + { + "inverter_paco": 6000, + "loss": 14.0, + "modules_per_string": 20, + "mountingplace": "free", + "optimal_surface_tilt": false, + "optimalangles": false, + "peakpower": 5.0, + "pvtechchoice": "crystSi", + "strings_per_inverter": 2, + "surface_azimuth": 180.0, + "surface_tilt": 10.0, + "trackingtype": 0, + "userhorizon": [ + 10.0, + 20.0, + 30.0 + ] + }, + { + "inverter_paco": 4000, + "loss": 14.0, + "modules_per_string": 20, + "mountingplace": "free", + "optimal_surface_tilt": false, + "optimalangles": false, + "peakpower": 3.5, + "pvtechchoice": "crystSi", + "strings_per_inverter": 2, + "surface_azimuth": 90.0, + "surface_tilt": 20.0, + "trackingtype": 1, + "userhorizon": [ + 5.0, + 15.0, + 25.0 + ] + } + ] + ] + }, + "max_planes": { + "anyOf": [ + { + "type": "integer", + "minimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Max Planes", + "description": "Maximum number of planes that can be set", + "default": 0 + } + }, + "type": "object", + "title": "PVForecastCommonSettings", + "description": "PV Forecast Configuration." + }, + "PVForecastCommonSettings-Output": { + "properties": { + "provider": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Provider", + "description": "PVForecast provider id of provider to be used.", + "examples": [ + "PVForecastAkkudoktor" + ] + }, + "provider_settings": { + "anyOf": [ + { + "$ref": "#/components/schemas/PVForecastImportCommonSettings" + }, + { + "type": "null" + } + ], + "description": "Provider settings", + "examples": [ + null + ] + }, + "planes": { + "anyOf": [ + { + "items": { + "$ref": "#/components/schemas/PVForecastPlaneSetting" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Planes", + "description": "Plane configuration.", + "examples": [ + [ + { + "inverter_paco": 6000, + "loss": 14.0, + "modules_per_string": 20, + "mountingplace": "free", + "optimal_surface_tilt": false, + "optimalangles": false, + "peakpower": 5.0, + "pvtechchoice": "crystSi", + "strings_per_inverter": 2, + "surface_azimuth": 180.0, + "surface_tilt": 10.0, + "trackingtype": 0, + "userhorizon": [ + 10.0, + 20.0, + 30.0 + ] + }, + { + "inverter_paco": 4000, + "loss": 14.0, + "modules_per_string": 20, + "mountingplace": "free", + "optimal_surface_tilt": false, + "optimalangles": false, + "peakpower": 3.5, + "pvtechchoice": "crystSi", + "strings_per_inverter": 2, + "surface_azimuth": 90.0, + "surface_tilt": 20.0, + "trackingtype": 1, + "userhorizon": [ + 5.0, + 15.0, + 25.0 + ] + } + ] + ] + }, + "max_planes": { + "anyOf": [ + { + "type": "integer", + "minimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Max Planes", + "description": "Maximum number of planes that can be set", + "default": 0 + }, + "planes_peakpower": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Planes Peakpower", + "description": "Compute a list of the peak power per active planes.", + "readOnly": true + }, + "planes_azimuth": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Planes Azimuth", + "description": "Compute a list of the azimuths per active planes.", + "readOnly": true + }, + "planes_tilt": { + "items": { + "type": "number" + }, + "type": "array", + "title": "Planes Tilt", + "description": "Compute a list of the tilts per active planes.", + "readOnly": true + }, + "planes_userhorizon": { + "title": "Planes Userhorizon", + "description": "Compute a list of the user horizon per active planes.", + "readOnly": true + }, + "planes_inverter_paco": { + "title": "Planes Inverter Paco", + "description": "Compute a list of the maximum power rating of the inverter per active planes.", + "readOnly": true + } + }, + "type": "object", + "required": [ + "planes_peakpower", + "planes_azimuth", + "planes_tilt", + "planes_userhorizon", + "planes_inverter_paco" + ], + "title": "PVForecastCommonSettings", + "description": "PV Forecast Configuration." + }, + "PVForecastImportCommonSettings": { + "properties": { + "import_file_path": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "format": "path" + }, + { + "type": "null" + } + ], + "title": "Import File Path", + "description": "Path to the file to import PV forecast data from.", + "examples": [ + null, + "/path/to/pvforecast.json" + ] + }, + "import_json": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Import Json", + "description": "JSON string, dictionary of PV forecast value lists.", + "examples": [ + "{\"pvforecast_ac_power\": [0, 8.05, 352.91]}" + ] + } + }, + "type": "object", + "title": "PVForecastImportCommonSettings", + "description": "Common settings for pvforecast data import from file or JSON string." + }, + "PVForecastPlaneSetting": { + "properties": { + "surface_tilt": { + "anyOf": [ + { + "type": "number", + "maximum": 90.0, + "minimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Surface Tilt", + "description": "Tilt angle from horizontal plane. Ignored for two-axis tracking.", + "default": 30.0, + "examples": [ + 10.0, + 20.0 + ] + }, + "surface_azimuth": { + "anyOf": [ + { + "type": "number", + "maximum": 360.0, + "minimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Surface Azimuth", + "description": "Orientation (azimuth angle) of the (fixed) plane. Clockwise from north (north=0, east=90, south=180, west=270).", + "default": 180.0, + "examples": [ + 180.0, + 90.0 + ] + }, + "userhorizon": { + "anyOf": [ + { + "items": { + "type": "number" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "title": "Userhorizon", + "description": "Elevation of horizon in degrees, at equally spaced azimuth clockwise from north.", + "examples": [ + [ + 10.0, + 20.0, + 30.0 + ], + [ + 5.0, + 15.0, + 25.0 + ] + ] + }, + "peakpower": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Peakpower", + "description": "Nominal power of PV system in kW.", + "examples": [ + 5.0, + 3.5 + ] + }, + "pvtechchoice": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Pvtechchoice", + "description": "PV technology. One of 'crystSi', 'CIS', 'CdTe', 'Unknown'.", + "default": "crystSi" + }, + "mountingplace": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Mountingplace", + "description": "Type of mounting for PV system. Options are 'free' for free-standing and 'building' for building-integrated.", + "default": "free" + }, + "loss": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Loss", + "description": "Sum of PV system losses in percent", + "default": 14.0 + }, + "trackingtype": { + "anyOf": [ + { + "type": "integer", + "maximum": 5.0, + "minimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Trackingtype", + "description": "Type of suntracking. 0=fixed, 1=single horizontal axis aligned north-south, 2=two-axis tracking, 3=vertical axis tracking, 4=single horizontal axis aligned east-west, 5=single inclined axis aligned north-south.", + "examples": [ + 0, + 1, + 2, + 3, + 4, + 5 + ] + }, + "optimal_surface_tilt": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Optimal Surface Tilt", + "description": "Calculate the optimum tilt angle. Ignored for two-axis tracking.", + "default": false, + "examples": [ + false + ] + }, + "optimalangles": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Optimalangles", + "description": "Calculate the optimum tilt and azimuth angles. Ignored for two-axis tracking.", + "default": false, + "examples": [ + false + ] + }, + "albedo": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ], + "title": "Albedo", + "description": "Proportion of the light hitting the ground that it reflects back.", + "examples": [ + null + ] + }, + "module_model": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Module Model", + "description": "Model of the PV modules of this plane.", + "examples": [ + null + ] + }, + "inverter_model": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Inverter Model", + "description": "Model of the inverter of this plane.", + "examples": [ + null + ] + }, + "inverter_paco": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Inverter Paco", + "description": "AC power rating of the inverter [W].", + "examples": [ + 6000, + 4000 + ] + }, + "modules_per_string": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Modules Per String", + "description": "Number of the PV modules of the strings of this plane.", + "examples": [ + 20 + ] + }, + "strings_per_inverter": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Strings Per Inverter", + "description": "Number of the strings of the inverter of this plane.", + "examples": [ + 2 + ] + } + }, + "type": "object", + "title": "PVForecastPlaneSetting", + "description": "PV Forecast Plane Configuration." + }, + "PredictionCommonSettings": { + "properties": { + "hours": { + "anyOf": [ + { + "type": "integer", + "minimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Hours", + "description": "Number of hours into the future for predictions", + "default": 48 + }, + "historic_hours": { + "anyOf": [ + { + "type": "integer", + "minimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Historic Hours", + "description": "Number of hours into the past for historical predictions data", + "default": 48 + } + }, + "type": "object", + "title": "PredictionCommonSettings", + "description": "General Prediction Configuration.\n\nThis class provides configuration for prediction settings, allowing users to specify\nparameters such as the forecast duration (in hours).\nValidators ensure each parameter is within a specified range.\n\nAttributes:\n hours (Optional[int]): Number of hours into the future for predictions.\n Must be non-negative.\n historic_hours (Optional[int]): Number of hours into the past for historical data.\n Must be non-negative.\n\nValidators:\n validate_hours (int): Ensures `hours` is a non-negative integer.\n validate_historic_hours (int): Ensures `historic_hours` is a non-negative integer." + }, + "PydanticDateTimeData": { + "additionalProperties": { + "anyOf": [ + { + "type": "string" + }, + { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "integer" + }, + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "type": "array" + } + ] + }, + "type": "object", + "title": "PydanticDateTimeData", + "description": "Pydantic model for time series data with consistent value lengths.\n\nThis model validates a dictionary where:\n- Keys are strings representing data series names\n- Values are lists of numeric or string values\n- Special keys 'start_datetime' and 'interval' can contain string values\nfor time series indexing\n- All value lists must have the same length\n\nExample:\n {\n \"start_datetime\": \"2024-01-01 00:00:00\", # optional\n \"interval\": \"1 Hour\", # optional\n \"load_mean\": [20.5, 21.0, 22.1],\n \"load_min\": [18.5, 19.0, 20.1]\n }" + }, + "PydanticDateTimeDataFrame": { + "properties": { + "data": { + "additionalProperties": { + "additionalProperties": true, + "type": "object" + }, + "type": "object", + "title": "Data" + }, + "dtypes": { + "additionalProperties": { + "type": "string" + }, + "type": "object", + "title": "Dtypes" + }, + "tz": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Tz", + "description": "Timezone for datetime values" + }, + "datetime_columns": { + "items": { + "type": "string" + }, + "type": "array", + "title": "Datetime Columns", + "description": "Columns to be treated as datetime" + } + }, + "type": "object", + "required": [ + "data" + ], + "title": "PydanticDateTimeDataFrame", + "description": "Pydantic model for validating pandas DataFrame data with datetime index." + }, + "PydanticDateTimeSeries": { + "properties": { + "data": { + "additionalProperties": true, + "type": "object", + "title": "Data" + }, + "dtype": { + "type": "string", + "title": "Dtype", + "default": "float64" + }, + "tz": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Tz" + } + }, + "type": "object", + "required": [ + "data" + ], + "title": "PydanticDateTimeSeries", + "description": "Pydantic model for validating pandas Series with datetime index in JSON format.\n\nThis model handles Series data serialized with orient='index', where the keys are\ndatetime strings and values are the series values. Provides validation and\nconversion between JSON and pandas Series with datetime index.\n\nAttributes:\n data (Dict[str, Any]): Dictionary mapping datetime strings to values.\n dtype (str): The data type of the series values.\n tz (str | None): Timezone name if the datetime index is timezone-aware." + }, + "ServerCommonSettings": { + "properties": { + "host": { + "anyOf": [ + { + "type": "string", + "format": "ipvanyaddress" + }, + { + "type": "null" + } + ], + "title": "Host", + "description": "EOS server IP address.", + "default": "127.0.0.1" + }, + "port": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Port", + "description": "EOS server IP port number.", + "default": 8503 + }, + "verbose": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Verbose", + "description": "Enable debug output", + "default": false + }, + "startup_eosdash": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "title": "Startup Eosdash", + "description": "EOS server to start EOSdash server.", + "default": true + }, + "eosdash_host": { + "anyOf": [ + { + "type": "string", + "format": "ipvanyaddress" + }, + { + "type": "null" + } + ], + "title": "Eosdash Host", + "description": "EOSdash server IP address.", + "default": "127.0.0.1" + }, + "eosdash_port": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Eosdash Port", + "description": "EOSdash server IP port number.", + "default": 8504 + } + }, + "type": "object", + "title": "ServerCommonSettings", + "description": "Server Configuration." + }, + "SettingsEOS": { + "properties": { + "general": { + "anyOf": [ + { + "$ref": "#/components/schemas/GeneralSettings-Input" + }, + { + "type": "null" + } + ], + "description": "General Settings" + }, + "cache": { + "anyOf": [ + { + "$ref": "#/components/schemas/CacheCommonSettings" + }, + { + "type": "null" + } + ], + "description": "Cache Settings" + }, + "ems": { + "anyOf": [ + { + "$ref": "#/components/schemas/EnergyManagementCommonSettings" + }, + { + "type": "null" + } + ], + "description": "Energy Management Settings" + }, + "logging": { + "anyOf": [ + { + "$ref": "#/components/schemas/LoggingCommonSettings-Input" + }, + { + "type": "null" + } + ], + "description": "Logging Settings" + }, + "devices": { + "anyOf": [ + { + "$ref": "#/components/schemas/DevicesCommonSettings" + }, + { + "type": "null" + } + ], + "description": "Devices Settings" + }, + "measurement": { + "anyOf": [ + { + "$ref": "#/components/schemas/MeasurementCommonSettings" + }, + { + "type": "null" + } + ], + "description": "Measurement Settings" + }, + "optimization": { + "anyOf": [ + { + "$ref": "#/components/schemas/OptimizationCommonSettings" + }, + { + "type": "null" + } + ], + "description": "Optimization Settings" + }, + "prediction": { + "anyOf": [ + { + "$ref": "#/components/schemas/PredictionCommonSettings" + }, + { + "type": "null" + } + ], + "description": "Prediction Settings" + }, + "elecprice": { + "anyOf": [ + { + "$ref": "#/components/schemas/ElecPriceCommonSettings" + }, + { + "type": "null" + } + ], + "description": "Electricity Price Settings" + }, + "load": { + "anyOf": [ + { + "$ref": "#/components/schemas/LoadCommonSettings" + }, + { + "type": "null" + } + ], + "description": "Load Settings" + }, + "pvforecast": { + "anyOf": [ + { + "$ref": "#/components/schemas/PVForecastCommonSettings-Input" + }, + { + "type": "null" + } + ], + "description": "PV Forecast Settings" + }, + "weather": { + "anyOf": [ + { + "$ref": "#/components/schemas/WeatherCommonSettings" + }, + { + "type": "null" + } + ], + "description": "Weather Settings" + }, + "server": { + "anyOf": [ + { + "$ref": "#/components/schemas/ServerCommonSettings" + }, + { + "type": "null" + } + ], + "description": "Server Settings" + }, + "utils": { + "anyOf": [ + { + "$ref": "#/components/schemas/UtilsCommonSettings" + }, + { + "type": "null" + } + ], + "description": "Utilities Settings" + } + }, + "additionalProperties": false, + "type": "object", + "title": "SettingsEOS", + "description": "Settings for all EOS.\n\nUsed by updating the configuration with specific settings only." + }, + "SimulationResult": { + "properties": { + "Last_Wh_pro_Stunde": { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array", + "title": "Last Wh Pro Stunde", + "description": "TBD" + }, + "EAuto_SoC_pro_Stunde": { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array", + "title": "Eauto Soc Pro Stunde", + "description": "The state of charge of the EV for each hour." + }, + "Einnahmen_Euro_pro_Stunde": { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array", + "title": "Einnahmen Euro Pro Stunde", + "description": "The revenue from grid feed-in or other sources in euros per hour." + }, + "Gesamt_Verluste": { + "type": "number", + "title": "Gesamt Verluste", + "description": "The total losses in watt-hours over the entire period." + }, + "Gesamtbilanz_Euro": { + "type": "number", + "title": "Gesamtbilanz Euro", + "description": "The total balance of revenues minus costs in euros." + }, + "Gesamteinnahmen_Euro": { + "type": "number", + "title": "Gesamteinnahmen Euro", + "description": "The total revenues in euros." + }, + "Gesamtkosten_Euro": { + "type": "number", + "title": "Gesamtkosten Euro", + "description": "The total costs in euros." + }, + "Home_appliance_wh_per_hour": { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array", + "title": "Home Appliance Wh Per Hour", + "description": "The energy consumption of a household appliance in watt-hours per hour." + }, + "Kosten_Euro_pro_Stunde": { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array", + "title": "Kosten Euro Pro Stunde", + "description": "The costs in euros per hour." + }, + "Netzbezug_Wh_pro_Stunde": { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array", + "title": "Netzbezug Wh Pro Stunde", + "description": "The grid energy drawn in watt-hours per hour." + }, + "Netzeinspeisung_Wh_pro_Stunde": { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array", + "title": "Netzeinspeisung Wh Pro Stunde", + "description": "The energy fed into the grid in watt-hours per hour." + }, + "Verluste_Pro_Stunde": { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array", + "title": "Verluste Pro Stunde", + "description": "The losses in watt-hours per hour." + }, + "akku_soc_pro_stunde": { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array", + "title": "Akku Soc Pro Stunde", + "description": "The state of charge of the battery (not the EV) in percentage per hour." + }, + "Electricity_price": { + "items": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "type": "array", + "title": "Electricity Price", + "description": "Used Electricity Price, including predictions" + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "Last_Wh_pro_Stunde", + "EAuto_SoC_pro_Stunde", + "Einnahmen_Euro_pro_Stunde", + "Gesamt_Verluste", + "Gesamtbilanz_Euro", + "Gesamteinnahmen_Euro", + "Gesamtkosten_Euro", + "Home_appliance_wh_per_hour", + "Kosten_Euro_pro_Stunde", + "Netzbezug_Wh_pro_Stunde", + "Netzeinspeisung_Wh_pro_Stunde", + "Verluste_Pro_Stunde", + "akku_soc_pro_stunde", + "Electricity_price" + ], + "title": "SimulationResult", + "description": "This object contains the results of the simulation and provides insights into various parameters over the entire forecast period." + }, + "SolarPanelBatteryParameters": { + "properties": { + "device_id": { + "type": "string", + "title": "Device Id", + "description": "ID of battery", + "examples": [ + "battery1" + ] + }, + "hours": { + "anyOf": [ + { + "type": "integer", + "exclusiveMinimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Hours", + "description": "Number of prediction hours. Defaults to global config prediction hours.", + "examples": [ + null + ] + }, + "capacity_wh": { + "type": "integer", + "exclusiveMinimum": 0.0, + "title": "Capacity Wh", + "description": "An integer representing the capacity of the battery in watt-hours.", + "examples": [ + 8000 + ] + }, + "charging_efficiency": { + "type": "number", + "maximum": 1.0, + "exclusiveMinimum": 0.0, + "title": "Charging Efficiency", + "description": "A float representing the charging efficiency of the battery.", + "default": 0.88 + }, + "discharging_efficiency": { + "type": "number", + "maximum": 1.0, + "exclusiveMinimum": 0.0, + "title": "Discharging Efficiency", + "description": "A float representing the discharge efficiency of the battery.", + "default": 0.88 + }, + "max_charge_power_w": { + "anyOf": [ + { + "type": "number", + "exclusiveMinimum": 0.0 + }, + { + "type": "null" + } + ], + "title": "Max Charge Power W", + "description": "Maximum charging power in watts.", + "default": 5000 + }, + "initial_soc_percentage": { + "type": "integer", + "maximum": 100.0, + "minimum": 0.0, + "title": "Initial Soc Percentage", + "description": "An integer representing the state of charge of the battery at the **start** of the current hour (not the current state).", + "default": 0, + "examples": [ + 42 + ] + }, + "min_soc_percentage": { + "type": "integer", + "maximum": 100.0, + "minimum": 0.0, + "title": "Min Soc Percentage", + "description": "An integer representing the minimum state of charge (SOC) of the battery in percentage.", + "default": 0, + "examples": [ + 10 + ] + }, + "max_soc_percentage": { + "type": "integer", + "maximum": 100.0, + "minimum": 0.0, + "title": "Max Soc Percentage", + "description": "An integer representing the maximum state of charge (SOC) of the battery in percentage.", + "default": 100 + } + }, + "additionalProperties": false, + "type": "object", + "required": [ + "device_id", + "capacity_wh" + ], + "title": "SolarPanelBatteryParameters" + }, + "UtilsCommonSettings": { + "properties": {}, + "type": "object", + "title": "UtilsCommonSettings", + "description": "Utils Configuration." + }, + "ValidationError": { + "properties": { + "loc": { + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "integer" + } + ] + }, + "type": "array", + "title": "Location" + }, + "msg": { + "type": "string", + "title": "Message" + }, + "type": { + "type": "string", + "title": "Error Type" + } + }, + "type": "object", + "required": [ + "loc", + "msg", + "type" + ], + "title": "ValidationError" + }, + "WeatherCommonSettings": { + "properties": { + "provider": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Provider", + "description": "Weather provider id of provider to be used.", + "examples": [ + "WeatherImport" + ] + }, + "provider_settings": { + "anyOf": [ + { + "$ref": "#/components/schemas/WeatherImportCommonSettings" + }, + { + "type": "null" + } + ], + "description": "Provider settings", + "examples": [ + null + ] + } + }, + "type": "object", + "title": "WeatherCommonSettings", + "description": "Weather Forecast Configuration." + }, + "WeatherImportCommonSettings": { + "properties": { + "import_file_path": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "string", + "format": "path" + }, + { + "type": "null" + } + ], + "title": "Import File Path", + "description": "Path to the file to import weather data from.", + "examples": [ + null, + "/path/to/weather_data.json" + ] + }, + "import_json": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Import Json", + "description": "JSON string, dictionary of weather forecast value lists.", + "examples": [ + "{\"weather_temp_air\": [18.3, 17.8, 16.9]}" + ] + } + }, + "type": "object", + "title": "WeatherImportCommonSettings", + "description": "Common settings for weather data import from file or JSON string." + } + } + } } \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index b5e56fd..36224ac 100644 --- a/requirements.txt +++ b/requirements.txt @@ -22,3 +22,4 @@ pydantic==2.11.5 statsmodels==0.14.4 pydantic-settings==2.9.1 linkify-it-py==2.0.3 +loguru==0.7.3 diff --git a/scripts/generate_config_md.py b/scripts/generate_config_md.py index ff599eb..eac87fb 100755 --- a/scripts/generate_config_md.py +++ b/scripts/generate_config_md.py @@ -4,22 +4,20 @@ import argparse import json import os +import re import sys import textwrap from pathlib import Path from typing import Any, Union +from loguru import logger from pydantic.fields import ComputedFieldInfo, FieldInfo from pydantic_core import PydanticUndefined from akkudoktoreos.config.config import ConfigEOS, GeneralSettings, get_config -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.core.pydantic import PydanticBaseModel from akkudoktoreos.utils.docs import get_model_structure_from_examples -logger = get_logger(__name__) - - documented_types: set[PydanticBaseModel] = set() undocumented_types: dict[PydanticBaseModel, tuple[str, list[str]]] = dict() @@ -145,6 +143,7 @@ def generate_config_table_md( field_type = field_info.annotation if regular_field else field_info.return_type default_value = get_default_value(field_info, regular_field) description = field_info.description if field_info.description else "-" + deprecated = field_info.deprecated if field_info.deprecated else None read_only = "rw" if regular_field else "ro" type_name = get_type_name(field_type) @@ -154,6 +153,11 @@ def generate_config_table_md( env_entry = f"| `{prefix}{config_name}` " else: env_entry = "| " + if deprecated: + if isinstance(deprecated, bool): + description = "Deprecated!" + else: + description = deprecated table += f"| {field_name} {env_entry}| `{type_name}` | `{read_only}` | `{default_value}` | {description} |\n" inner_types: dict[PydanticBaseModel, tuple[str, list[str]]] = dict() @@ -259,7 +263,7 @@ def generate_config_md(config_eos: ConfigEOS) -> str: markdown = "# Configuration Table\n\n" # Generate tables for each top level config - for field_name, field_info in config_eos.model_fields.items(): + for field_name, field_info in config_eos.__class__.model_fields.items(): field_type = field_info.annotation markdown += generate_config_table_md( field_type, [field_name], f"EOS_{field_name.upper()}__", True @@ -279,6 +283,13 @@ def generate_config_md(config_eos: ConfigEOS) -> str: markdown = markdown.rstrip("\n") markdown += "\n" + # Assure log path does not leak to documentation + markdown = re.sub( + r'(?<=["\'])/[^"\']*/output/eos\.log(?=["\'])', + '/home/user/.local/share/net.akkudoktoreos.net/output/eos.log', + markdown + ) + return markdown diff --git a/scripts/generate_openapi.py b/scripts/generate_openapi.py index 9aaec58..13ec283 100755 --- a/scripts/generate_openapi.py +++ b/scripts/generate_openapi.py @@ -42,6 +42,9 @@ def generate_openapi() -> dict: general = openapi_spec["components"]["schemas"]["ConfigEOS"]["properties"]["general"]["default"] general["config_file_path"] = "/home/user/.config/net.akkudoktoreos.net/EOS.config.json" general["config_folder_path"] = "/home/user/.config/net.akkudoktoreos.net" + # Fix file path for logging settings to not show local/test file path + logging = openapi_spec["components"]["schemas"]["ConfigEOS"]["properties"]["logging"]["default"] + logging["file_path"] = "/home/user/.local/share/net.akkudoktoreos.net/output/eos.log" return openapi_spec diff --git a/single_test_optimization.py b/single_test_optimization.py index 7b0f868..ccc9db9 100755 --- a/single_test_optimization.py +++ b/single_test_optimization.py @@ -12,15 +12,12 @@ import numpy as np from akkudoktoreos.config.config import get_config from akkudoktoreos.core.ems import get_ems -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.optimization.genetic import ( OptimizationParameters, optimization_problem, ) from akkudoktoreos.prediction.prediction import get_prediction -get_logger(__name__, logging_level="DEBUG") - def prepare_optimization_real_parameters() -> OptimizationParameters: """Prepare and return optimization parameters with real world data. diff --git a/src/akkudoktoreos/config/config.py b/src/akkudoktoreos/config/config.py index e9b5a3e..4260650 100644 --- a/src/akkudoktoreos/config/config.py +++ b/src/akkudoktoreos/config/config.py @@ -14,6 +14,7 @@ import shutil from pathlib import Path from typing import Any, ClassVar, Optional, Type +from loguru import logger from platformdirs import user_config_dir, user_data_dir from pydantic import Field, computed_field from pydantic_settings import ( @@ -29,7 +30,6 @@ from akkudoktoreos.core.cachesettings import CacheCommonSettings from akkudoktoreos.core.coreabc import SingletonMixin from akkudoktoreos.core.decorators import classproperty from akkudoktoreos.core.emsettings import EnergyManagementCommonSettings -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.core.logsettings import LoggingCommonSettings from akkudoktoreos.core.pydantic import PydanticModelNestedValueMixin, merge_models from akkudoktoreos.devices.settings import DevicesCommonSettings @@ -44,8 +44,6 @@ from akkudoktoreos.server.server import ServerCommonSettings from akkudoktoreos.utils.datetimeutil import to_timezone from akkudoktoreos.utils.utils import UtilsCommonSettings -logger = get_logger(__name__) - def get_absolute_path( basepath: Optional[Path | str], subpath: Optional[Path | str] @@ -80,10 +78,6 @@ class GeneralSettings(SettingsBaseModel): Properties: timezone (Optional[str]): Computed time zone string based on the specified latitude and longitude. - - Validators: - validate_latitude (float): Ensures `latitude` is within the range -90 to 90. - validate_longitude (float): Ensures `longitude` is within the range -180 to 180. """ _config_folder_path: ClassVar[Optional[Path]] = None @@ -283,6 +277,16 @@ class ConfigEOS(SingletonMixin, SettingsEOSDefaults): ENCODING: ClassVar[str] = "UTF-8" CONFIG_FILE_NAME: ClassVar[str] = "EOS.config.json" + def __hash__(self) -> int: + # ConfigEOS is a singleton + return hash("config_eos") + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, ConfigEOS): + return False + # ConfigEOS is a singleton + return True + @classmethod def settings_customise_sources( cls, diff --git a/src/akkudoktoreos/core/cache.py b/src/akkudoktoreos/core/cache.py index d4a1da6..45de386 100644 --- a/src/akkudoktoreos/core/cache.py +++ b/src/akkudoktoreos/core/cache.py @@ -27,17 +27,14 @@ from typing import ( ) import cachebox +from loguru import logger from pendulum import DateTime, Duration from pydantic import Field from akkudoktoreos.core.coreabc import ConfigMixin, SingletonMixin -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.core.pydantic import PydanticBaseModel from akkudoktoreos.utils.datetimeutil import compare_datetimes, to_datetime, to_duration -logger = get_logger(__name__) - - # --------------------------------- # In-Memory Caching Functionality # --------------------------------- diff --git a/src/akkudoktoreos/core/coreabc.py b/src/akkudoktoreos/core/coreabc.py index 3431f2d..2e90799 100644 --- a/src/akkudoktoreos/core/coreabc.py +++ b/src/akkudoktoreos/core/coreabc.py @@ -13,13 +13,10 @@ Classes: import threading from typing import Any, ClassVar, Dict, Optional, Type +from loguru import logger from pendulum import DateTime from pydantic import computed_field -from akkudoktoreos.core.logging import get_logger - -logger = get_logger(__name__) - config_eos: Any = None measurement_eos: Any = None prediction_eos: Any = None diff --git a/src/akkudoktoreos/core/dataabc.py b/src/akkudoktoreos/core/dataabc.py index a24334a..c82c68b 100644 --- a/src/akkudoktoreos/core/dataabc.py +++ b/src/akkudoktoreos/core/dataabc.py @@ -19,6 +19,7 @@ from typing import Any, Dict, Iterator, List, Optional, Tuple, Type, Union, over import numpy as np import pandas as pd import pendulum +from loguru import logger from numpydantic import NDArray, Shape from pendulum import DateTime, Duration from pydantic import ( @@ -31,7 +32,6 @@ from pydantic import ( ) from akkudoktoreos.core.coreabc import ConfigMixin, SingletonMixin, StartMixin -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.core.pydantic import ( PydanticBaseModel, PydanticDateTimeData, @@ -39,8 +39,6 @@ from akkudoktoreos.core.pydantic import ( ) from akkudoktoreos.utils.datetimeutil import compare_datetimes, to_datetime, to_duration -logger = get_logger(__name__) - class DataBase(ConfigMixin, StartMixin, PydanticBaseModel): """Base class for handling generic data. diff --git a/src/akkudoktoreos/core/decorators.py b/src/akkudoktoreos/core/decorators.py index ee83ed3..8c0fca6 100644 --- a/src/akkudoktoreos/core/decorators.py +++ b/src/akkudoktoreos/core/decorators.py @@ -1,10 +1,6 @@ from collections.abc import Callable from typing import Any, Optional -from akkudoktoreos.core.logging import get_logger - -logger = get_logger(__name__) - class classproperty: """A decorator to define a read-only property at the class level. diff --git a/src/akkudoktoreos/core/ems.py b/src/akkudoktoreos/core/ems.py index c366c12..043637e 100644 --- a/src/akkudoktoreos/core/ems.py +++ b/src/akkudoktoreos/core/ems.py @@ -2,6 +2,7 @@ import traceback from typing import Any, ClassVar, Optional import numpy as np +from loguru import logger from numpydantic import NDArray, Shape from pendulum import DateTime from pydantic import ConfigDict, Field, computed_field, field_validator, model_validator @@ -9,7 +10,6 @@ from typing_extensions import Self from akkudoktoreos.core.cache import CacheUntilUpdateStore from akkudoktoreos.core.coreabc import ConfigMixin, PredictionMixin, SingletonMixin -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.core.pydantic import ParametersBaseModel, PydanticBaseModel from akkudoktoreos.devices.battery import Battery from akkudoktoreos.devices.generic import HomeAppliance @@ -17,8 +17,6 @@ from akkudoktoreos.devices.inverter import Inverter from akkudoktoreos.utils.datetimeutil import compare_datetimes, to_datetime from akkudoktoreos.utils.utils import NumpyEncoder -logger = get_logger(__name__) - class EnergyManagementParameters(ParametersBaseModel): pv_prognose_wh: list[float] = Field( @@ -283,6 +281,8 @@ class EnergyManagement(SingletonMixin, ConfigMixin, PredictionMixin, PydanticBas self.prediction.update_data(force_enable=force_enable, force_update=force_update) # TODO: Create optimisation problem that calls into devices.update_data() for simulations. + logger.info("Energy management run (crippled version - prediction update only)") + def manage_energy(self) -> None: """Repeating task for managing energy. @@ -302,6 +302,7 @@ class EnergyManagement(SingletonMixin, ConfigMixin, PredictionMixin, PydanticBas Note: The task maintains the interval even if some intervals are missed. """ current_datetime = to_datetime() + interval = self.config.ems.interval # interval maybe changed in between if EnergyManagement._last_datetime is None: # Never run before @@ -316,13 +317,13 @@ class EnergyManagement(SingletonMixin, ConfigMixin, PredictionMixin, PydanticBas logger.error(message) return - if self.config.ems.interval is None or self.config.ems.interval == float("nan"): + if interval is None or interval == float("nan"): # No Repetition return if ( - compare_datetimes(current_datetime, self._last_datetime).time_diff - < self.config.ems.interval + compare_datetimes(current_datetime, EnergyManagement._last_datetime).time_diff + < interval ): # Wait for next run return @@ -337,9 +338,9 @@ class EnergyManagement(SingletonMixin, ConfigMixin, PredictionMixin, PydanticBas # Remember the energy management run - keep on interval even if we missed some intervals while ( compare_datetimes(current_datetime, EnergyManagement._last_datetime).time_diff - >= self.config.ems.interval + >= interval ): - EnergyManagement._last_datetime.add(seconds=self.config.ems.interval) + EnergyManagement._last_datetime = EnergyManagement._last_datetime.add(seconds=interval) def set_start_hour(self, start_hour: Optional[int] = None) -> None: """Sets start datetime to given hour. diff --git a/src/akkudoktoreos/core/logabc.py b/src/akkudoktoreos/core/logabc.py index 6dc4c57..bd8ae49 100644 --- a/src/akkudoktoreos/core/logabc.py +++ b/src/akkudoktoreos/core/logabc.py @@ -1,20 +1,3 @@ """Abstract and base classes for logging.""" -import logging - - -def logging_str_to_level(level_str: str) -> int: - """Convert log level string to logging level.""" - if level_str == "DEBUG": - level = logging.DEBUG - elif level_str == "INFO": - level = logging.INFO - elif level_str == "WARNING": - level = logging.WARNING - elif level_str == "CRITICAL": - level = logging.CRITICAL - elif level_str == "ERROR": - level = logging.ERROR - else: - raise ValueError(f"Unknown loggin level: {level_str}") - return level +LOGGING_LEVELS: list[str] = ["TRACE", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] diff --git a/src/akkudoktoreos/core/logging.py b/src/akkudoktoreos/core/logging.py index 5ff9e56..d27b4f2 100644 --- a/src/akkudoktoreos/core/logging.py +++ b/src/akkudoktoreos/core/logging.py @@ -1,95 +1,241 @@ -"""Utility functions for handling logging tasks. - -Functions: ----------- -- get_logger: Creates and configures a logger with console and optional rotating file logging. - -Example usage: --------------- - # Logger setup - >>> logger = get_logger(__name__, log_file="app.log", logging_level="DEBUG") - >>> logger.info("Logging initialized.") - -Notes: ------- -- The logger supports rotating log files to prevent excessive log file size. -""" +"""Utility for configuring Loguru loggers.""" +import json import logging as pylogging import os -from logging.handlers import RotatingFileHandler -from typing import Optional +import re +import sys +from pathlib import Path +from types import FrameType +from typing import Any, List, Optional -from akkudoktoreos.core.logabc import logging_str_to_level +import pendulum +from loguru import logger + +from akkudoktoreos.core.logabc import LOGGING_LEVELS -def get_logger( - name: str, - log_file: Optional[str] = None, - logging_level: Optional[str] = None, - max_bytes: int = 5000000, - backup_count: int = 5, -) -> pylogging.Logger: - """Creates and configures a logger with a given name. +class InterceptHandler(pylogging.Handler): + """A logging handler that redirects standard Python logging messages to Loguru. - The logger supports logging to both the console and an optional log file. File logging is - handled by a rotating file handler to prevent excessive log file size. + This handler ensures consistency between the `logging` module and Loguru by intercepting + logs sent to the standard logging system and re-emitting them through Loguru with proper + formatting and context (including exception info and call depth). + + Attributes: + loglevel_mapping (dict): Mapping from standard logging levels to Loguru level names. + """ + + loglevel_mapping: dict[int, str] = { + 50: "CRITICAL", + 40: "ERROR", + 30: "WARNING", + 20: "INFO", + 10: "DEBUG", + 5: "TRACE", + 0: "NOTSET", + } + + def emit(self, record: pylogging.LogRecord) -> None: + """Emits a logging record by forwarding it to Loguru with preserved metadata. + + Args: + record (logging.LogRecord): A record object containing log message and metadata. + """ + try: + level = logger.level(record.levelname).name + except AttributeError: + level = self.loglevel_mapping.get(record.levelno, "INFO") + + frame: Optional[FrameType] = pylogging.currentframe() + depth: int = 2 + while frame and frame.f_code.co_filename == pylogging.__file__: + frame = frame.f_back + depth += 1 + + log = logger.bind(request_id="app") + log.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage()) + + +console_handler_id = None +file_handler_id = None + + +def track_logging_config(config_eos: Any, path: str, old_value: Any, value: Any) -> None: + """Track logging config changes.""" + global console_handler_id, file_handler_id + + if not path.startswith("logging"): + raise ValueError(f"Logging shall not track '{path}'") + + if not config_eos.logging.console_level: + # No value given - check environment value - may also be None + config_eos.logging.console_level = os.getenv("EOS_LOGGING__LEVEL") + if not config_eos.logging.file_level: + # No value given - check environment value - may also be None + config_eos.logging.file_level = os.getenv("EOS_LOGGING__LEVEL") + + # Remove handlers + if console_handler_id: + try: + logger.remove(console_handler_id) + except Exception as e: + logger.debug("Exception on logger.remove: {}", e, exc_info=True) + console_handler_id = None + if file_handler_id: + try: + logger.remove(file_handler_id) + except Exception as e: + logger.debug("Exception on logger.remove: {}", e, exc_info=True) + file_handler_id = None + + # Create handlers with new configuration + # Always add console handler + if config_eos.logging.console_level not in LOGGING_LEVELS: + logger.error( + f"Invalid console log level '{config_eos.logging.console_level} - forced to INFO'." + ) + config_eos.logging.console_level = "INFO" + + console_handler_id = logger.add( + sys.stderr, + enqueue=True, + backtrace=True, + level=config_eos.logging.console_level, + # format=_console_format + ) + + # Add file handler + if config_eos.logging.file_level and config_eos.logging.file_path: + if config_eos.logging.file_level not in LOGGING_LEVELS: + logger.error( + f"Invalid file log level '{config_eos.logging.console_level}' - forced to INFO." + ) + config_eos.logging.file_level = "INFO" + + file_handler_id = logger.add( + sink=config_eos.logging.file_path, + rotation="100 MB", + retention="3 days", + enqueue=True, + backtrace=True, + level=config_eos.logging.file_level, + serialize=True, # JSON dict formatting + # format=_file_format + ) + + # Redirect standard logging to Loguru + pylogging.basicConfig(handlers=[InterceptHandler()], level=0) + # Redirect uvicorn and fastapi logging to Loguru + pylogging.getLogger("uvicorn.access").handlers = [InterceptHandler()] + for pylogger_name in ["uvicorn", "uvicorn.error", "fastapi"]: + pylogger = pylogging.getLogger(pylogger_name) + pylogger.handlers = [InterceptHandler()] + pylogger.propagate = False + + logger.info( + f"Logger reconfigured - console: {config_eos.logging.console_level}, file: {config_eos.logging.file_level}." + ) + + +def read_file_log( + log_path: Path, + limit: int = 100, + level: Optional[str] = None, + contains: Optional[str] = None, + regex: Optional[str] = None, + from_time: Optional[str] = None, + to_time: Optional[str] = None, + tail: bool = False, +) -> List[dict]: + """Read and filter structured log entries from a JSON-formatted log file. Args: - name (str): The name of the logger, typically `__name__` from the calling module. - log_file (Optional[str]): Path to the log file for file logging. If None, no file logging is done. - logging_level (Optional[str]): Logging level (e.g., "INFO", "DEBUG"). Defaults to "INFO". - max_bytes (int): Maximum size in bytes for log file before rotation. Defaults to 5 MB. - backup_count (int): Number of backup log files to keep. Defaults to 5. + log_path (Path): Path to the JSON-formatted log file. + limit (int, optional): Maximum number of log entries to return. Defaults to 100. + level (Optional[str], optional): Filter logs by log level (e.g., "INFO", "ERROR"). Defaults to None. + contains (Optional[str], optional): Filter logs that contain this substring in their message. Case-insensitive. Defaults to None. + regex (Optional[str], optional): Filter logs whose message matches this regular expression. Defaults to None. + from_time (Optional[str], optional): ISO 8601 datetime string to filter logs not earlier than this time. Defaults to None. + to_time (Optional[str], optional): ISO 8601 datetime string to filter logs not later than this time. Defaults to None. + tail (bool, optional): If True, read the last lines of the file (like `tail -n`). Defaults to False. Returns: - logging.Logger: Configured logger instance. + List[dict]: A list of filtered log entries as dictionaries. - Example: - logger = get_logger(__name__, log_file="app.log", logging_level="DEBUG") - logger.info("Application started") + Raises: + FileNotFoundError: If the log file does not exist. + ValueError: If the datetime strings are invalid or improperly formatted. + Exception: For other unforeseen I/O or parsing errors. """ - # Create a logger with the specified name - logger = pylogging.getLogger(name) - logger.propagate = True - # This is already supported by pydantic-settings in LoggingCommonSettings, however in case - # loading the config itself fails and to set the level before we load the config, we set it here manually. - if logging_level is None and (env_level := os.getenv("EOS_LOGGING__LEVEL")) is not None: - logging_level = env_level - if logging_level is not None: - level = logging_str_to_level(logging_level) - logger.setLevel(level) + if not log_path.exists(): + raise FileNotFoundError("Log file not found") - # The log message format - formatter = pylogging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") + try: + from_dt = pendulum.parse(from_time) if from_time else None + to_dt = pendulum.parse(to_time) if to_time else None + except Exception as e: + raise ValueError(f"Invalid date/time format: {e}") - # Prevent loggers from being added multiple times - # There may already be a logger from pytest - if not logger.handlers: - # Create a console handler with a standard output stream - console_handler = pylogging.StreamHandler() - if logging_level is not None: - console_handler.setLevel(level) - console_handler.setFormatter(formatter) + regex_pattern = re.compile(regex) if regex else None - # Add the console handler to the logger - logger.addHandler(console_handler) + def matches_filters(log: dict) -> bool: + if level and log.get("level", {}).get("name") != level.upper(): + return False + if contains and contains.lower() not in log.get("message", "").lower(): + return False + if regex_pattern and not regex_pattern.search(log.get("message", "")): + return False + if from_dt or to_dt: + try: + log_time = pendulum.parse(log["time"]) + except Exception: + return False + if from_dt and log_time < from_dt: + return False + if to_dt and log_time > to_dt: + return False + return True - if log_file and len(logger.handlers) < 2: # We assume a console logger to be the first logger - # If a log file path is specified, create a rotating file handler + matched_logs = [] + lines: list[str] = [] - # Ensure the log directory exists - log_dir = os.path.dirname(log_file) - if log_dir and not os.path.exists(log_dir): - os.makedirs(log_dir) + if tail: + with log_path.open("rb") as f: + f.seek(0, 2) + end = f.tell() + buffer = bytearray() + pointer = end - # Create a rotating file handler - file_handler = RotatingFileHandler(log_file, maxBytes=max_bytes, backupCount=backup_count) - if logging_level is not None: - file_handler.setLevel(level) - file_handler.setFormatter(formatter) + while pointer > 0 and len(lines) < limit * 5: + pointer -= 1 + f.seek(pointer) + byte = f.read(1) + if byte == b"\n": + if buffer: + line = buffer[::-1].decode("utf-8", errors="ignore") + lines.append(line) + buffer.clear() + else: + buffer.append(byte[0]) + if buffer: + line = buffer[::-1].decode("utf-8", errors="ignore") + lines.append(line) + lines = lines[::-1] + else: + with log_path.open("r", encoding="utf-8", newline=None) as f_txt: + lines = f_txt.readlines() - # Add the file handler to the logger - logger.addHandler(file_handler) + for line in lines: + if not line.strip(): + continue + try: + log = json.loads(line) + except json.JSONDecodeError: + continue + if matches_filters(log): + matched_logs.append(log) + if len(matched_logs) >= limit: + break - return logger + return matched_logs diff --git a/src/akkudoktoreos/core/logsettings.py b/src/akkudoktoreos/core/logsettings.py index fa5ce4b..d2ec48a 100644 --- a/src/akkudoktoreos/core/logsettings.py +++ b/src/akkudoktoreos/core/logsettings.py @@ -3,13 +3,13 @@ Kept in an extra module to avoid cyclic dependencies on package import. """ -import logging +from pathlib import Path from typing import Optional from pydantic import Field, computed_field, field_validator from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.logabc import logging_str_to_level +from akkudoktoreos.core.logabc import LOGGING_LEVELS class LoggingCommonSettings(SettingsBaseModel): @@ -17,27 +17,47 @@ class LoggingCommonSettings(SettingsBaseModel): level: Optional[str] = Field( default=None, - description="EOS default logging level.", - examples=["INFO", "DEBUG", "WARNING", "ERROR", "CRITICAL"], + deprecated="This is deprecated. Use console_level and file_level instead.", ) - # Validators - @field_validator("level", mode="after") - @classmethod - def set_default_logging_level(cls, value: Optional[str]) -> Optional[str]: - if isinstance(value, str) and value.upper() == "NONE": - value = None - if value is None: - return None - level = logging_str_to_level(value) - logging.getLogger().setLevel(level) - return value + console_level: Optional[str] = Field( + default=None, + description="Logging level when logging to console.", + examples=LOGGING_LEVELS, + ) + + file_level: Optional[str] = Field( + default=None, + description="Logging level when logging to file.", + examples=LOGGING_LEVELS, + ) - # Computed fields @computed_field # type: ignore[prop-decorator] @property - def root_level(self) -> str: - """Root logger logging level.""" - level = logging.getLogger().getEffectiveLevel() - level_name = logging.getLevelName(level) - return level_name + def file_path(self) -> Optional[Path]: + """Computed log file path based on data output path.""" + try: + path = SettingsBaseModel.config.general.data_output_path / "eos.log" + except: + # Config may not be fully set up + path = None + return path + + # Validators + @field_validator("console_level", "file_level", mode="after") + @classmethod + def validate_level(cls, value: Optional[str]) -> Optional[str]: + """Validate logging level string.""" + if value is None: + # Nothing to set + return None + if isinstance(value, str): + level = value.upper() + if level == "NONE": + return None + if level not in LOGGING_LEVELS: + raise ValueError(f"Logging level {value} not supported") + value = level + else: + raise TypeError(f"Invalid {type(value)} of logging level {value}") + return value diff --git a/src/akkudoktoreos/core/pydantic.py b/src/akkudoktoreos/core/pydantic.py index 933c8d6..ce072e1 100644 --- a/src/akkudoktoreos/core/pydantic.py +++ b/src/akkudoktoreos/core/pydantic.py @@ -12,20 +12,35 @@ Key Features: pandas DataFrames and Series with datetime indexes. """ +import inspect import json import re +import uuid +import weakref from copy import deepcopy -from typing import Any, Dict, List, Optional, Type, Union, get_args, get_origin +from typing import ( + Any, + Callable, + Dict, + List, + Optional, + Type, + Union, + get_args, + get_origin, +) from zoneinfo import ZoneInfo import pandas as pd import pendulum +from loguru import logger from pandas.api.types import is_datetime64_any_dtype from pydantic import ( AwareDatetime, BaseModel, ConfigDict, Field, + PrivateAttr, RootModel, TypeAdapter, ValidationError, @@ -35,6 +50,10 @@ from pydantic import ( from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration +# Global weakref dictionary to hold external state per model instance +# Used as a workaround for PrivateAttr not working in e.g. Mixin Classes +_model_private_state: "weakref.WeakKeyDictionary[Union[PydanticBaseModel, PydanticModelNestedValueMixin], Dict[str, Any]]" = weakref.WeakKeyDictionary() + def merge_models(source: BaseModel, update_dict: dict[str, Any]) -> dict[str, Any]: def deep_update(source_dict: dict[str, Any], update_dict: dict[str, Any]) -> dict[str, Any]: @@ -83,13 +102,164 @@ class PydanticTypeAdapterDateTime(TypeAdapter[pendulum.DateTime]): class PydanticModelNestedValueMixin: - """A mixin providing methods to get and set nested values within a Pydantic model. + """A mixin providing methods to get, set and track nested values within a Pydantic model. The methods use a '/'-separated path to denote the nested values. Supports handling `Optional`, `List`, and `Dict` types, ensuring correct initialization of missing attributes. + + + Example: + class Address(PydanticBaseModel): + city: str + + class User(PydanticBaseModel): + name: str + address: Address + + def on_city_change(old, new, path): + print(f"{path}: {old} -> {new}") + + user = User(name="Alice", address=Address(city="NY")) + user.track_nested_value("address/city", on_city_change) + user.set_nested_value("address/city", "LA") # triggers callback + """ + def track_nested_value(self, path: str, callback: Callable[[Any, str, Any, Any], None]) -> None: + """Register a callback for a specific path (or subtree). + + Callback triggers if set path is equal or deeper. + + Args: + path (str): '/'-separated path to track. + callback (callable): Function called as callback(model_instance, set_path, old_value, new_value). + """ + try: + self._validate_path_structure(path) + pass + except: + raise ValueError(f"Path '{path}' is invalid") + path = path.strip("/") + # Use private data workaround + # Should be: + # _nested_value_callbacks: dict[str, list[Callable[[str, Any, Any], None]]] + # = PrivateAttr(default_factory=dict) + nested_value_callbacks = get_private_attr(self, "nested_value_callbacks", dict()) + if path not in nested_value_callbacks: + nested_value_callbacks[path] = [] + nested_value_callbacks[path].append(callback) + set_private_attr(self, "nested_value_callbacks", nested_value_callbacks) + + logger.debug("Nested value callbacks {}", nested_value_callbacks) + + def _validate_path_structure(self, path: str) -> None: + """Validate that a '/'-separated path is structurally valid for this model. + + Checks that each segment of the path corresponds to a field or index in the model's type structure, + without requiring that all intermediate values are currently initialized. This method is intended + to ensure that the path could be valid for nested access or assignment, according to the model's + class definition. + + Args: + path (str): The '/'-separated attribute/index path to validate (e.g., "address/city" or "items/0/value"). + + Raises: + ValueError: If any segment of the path does not correspond to a valid field in the model, + or an invalid transition is made (such as an attribute on a non-model). + + Example: + class Address(PydanticBaseModel): + city: str + + class User(PydanticBaseModel): + name: str + address: Address + + user = User(name="Alice", address=Address(city="NY")) + user._validate_path_structure("address/city") # OK + user._validate_path_structure("address/zipcode") # Raises ValueError + """ + path_elements = path.strip("/").split("/") + # The model we are currently working on + model: Any = self + # The model we get the type information from. It is a pydantic BaseModel + parent: BaseModel = model + # The field that provides type information for the current key + # Fields may have nested types that translates to a sequence of keys, not just one + # - my_field: Optional[list[OtherModel]] -> e.g. "myfield/0" for index 0 + # parent_key = ["myfield",] ... ["myfield", "0"] + # parent_key_types = [list, OtherModel] + parent_key: list[str] = [] + parent_key_types: list = [] + + for i, key in enumerate(path_elements): + is_final_key = i == len(path_elements) - 1 + # Add current key to parent key to enable nested type tracking + parent_key.append(key) + + # Get next value + next_value = None + if isinstance(model, BaseModel): + # Track parent and key for possible assignment later + parent = model + parent_key = [ + key, + ] + parent_key_types = self._get_key_types(model.__class__, key) + + # If this is the final key, set the value + if is_final_key: + return + + # Attempt to access the next attribute, handling None values + next_value = getattr(model, key, None) + + # Handle missing values (initialize dict/list/model if necessary) + if next_value is None: + next_type = parent_key_types[len(parent_key) - 1] + next_value = self._initialize_value(next_type) + + elif isinstance(model, list): + # Handle lists + try: + idx = int(key) + except Exception as e: + raise IndexError( + f"Invalid list index '{key}' at '{path}': key = '{key}'; parent = '{parent}', parent_key = '{parent_key}'; model = '{model}'; {e}" + ) + + # Get next type from parent key type information + next_type = parent_key_types[len(parent_key) - 1] + + if len(model) > idx: + next_value = model[idx] + else: + return + + if is_final_key: + return + + elif isinstance(model, dict): + # Handle dictionaries (auto-create missing keys) + + # Get next type from parent key type information + next_type = parent_key_types[len(parent_key) - 1] + + if is_final_key: + return + + if key not in model: + return + else: + next_value = model[key] + + else: + raise KeyError(f"Key '{key}' not found in model.") + + # Move deeper + model = next_value + def get_nested_value(self, path: str) -> Any: """Retrieve a nested value from the model using a '/'-separated path. @@ -128,6 +298,11 @@ class PydanticModelNestedValueMixin: model = model[int(key)] except (ValueError, IndexError) as e: raise IndexError(f"Invalid list index at '{path}': {key}; {e}") + elif isinstance(model, dict): + try: + model = model[key] + except Exception as e: + raise KeyError(f"Invalid dict key at '{path}': {key}; {e}") elif isinstance(model, BaseModel): model = getattr(model, key) else: @@ -142,6 +317,8 @@ class PydanticModelNestedValueMixin: Automatically initializes missing `Optional`, `Union`, `dict`, and `list` fields if necessary. If a missing field cannot be initialized, raises an exception. + Triggers the callbacks registered by track_nested_value(). + Args: path (str): A '/'-separated path to the nested attribute (e.g., "key1/key2/0"). value (Any): The new value to set. @@ -170,6 +347,44 @@ class PydanticModelNestedValueMixin: print(user.settings) # Output: {'theme': 'dark'} ``` """ + path = path.strip("/") + # Store old value (if possible) + try: + old_value = self.get_nested_value(path) + except Exception as e: + # We can not get the old value + # raise ValueError(f"Can not get old (current) value of '{path}': {e}") from e + old_value = None + + # Proceed with core logic + self._set_nested_value(path, value) + + # Trigger all callbacks whose path is a prefix of set path + triggered = set() + nested_value_callbacks = get_private_attr(self, "nested_value_callbacks", dict()) + for cb_path, callbacks in nested_value_callbacks.items(): + # Match: cb_path == path, or cb_path is a prefix (parent) of path + pass + if path == cb_path or path.startswith(cb_path + "/"): + for cb in callbacks: + # Prevent duplicate calls + if (cb_path, id(cb)) not in triggered: + cb(self, path, old_value, value) + triggered.add((cb_path, id(cb))) + + def _set_nested_value(self, path: str, value: Any) -> None: + """Set a nested value core logic. + + Args: + path (str): A '/'-separated path to the nested attribute (e.g., "key1/key2/0"). + value (Any): The new value to set. + + Raises: + KeyError: If a key is not found in the model. + IndexError: If a list index is out of bounds or invalid. + ValueError: If a validation error occurs. + TypeError: If a missing field cannot be initialized. + """ path_elements = path.strip("/").split("/") # The model we are currently working on model: Any = self @@ -191,6 +406,13 @@ class PydanticModelNestedValueMixin: # Get next value next_value = None if isinstance(model, BaseModel): + # Track parent and key for possible assignment later + parent = model + parent_key = [ + key, + ] + parent_key_types = self._get_key_types(model.__class__, key) + # If this is the final key, set the value if is_final_key: try: @@ -199,13 +421,6 @@ class PydanticModelNestedValueMixin: raise ValueError(f"Error updating model: {e}") from e return - # Track parent and key for possible assignment later - parent = model - parent_key = [ - key, - ] - parent_key_types = self._get_key_types(model, key) - # Attempt to access the next attribute, handling None values next_value = getattr(model, key, None) @@ -227,7 +442,7 @@ class PydanticModelNestedValueMixin: idx = int(key) except Exception as e: raise IndexError( - f"Invalid list index '{key}' at '{path}': key = {key}; parent = {parent}, parent_key = {parent_key}; model = {model}; {e}" + f"Invalid list index '{key}' at '{path}': key = '{key}'; parent = '{parent}', parent_key = '{parent_key}'; model = '{model}'; {e}" ) # Get next type from parent key type information @@ -309,6 +524,9 @@ class PydanticModelNestedValueMixin: Raises: TypeError: If the key does not exist or lacks a valid type annotation. """ + if not inspect.isclass(model): + raise TypeError(f"Model '{model}' is not of class type.") + if key not in model.model_fields: raise TypeError(f"Field '{key}' does not exist in model '{model.__name__}'.") @@ -408,11 +626,13 @@ class PydanticModelNestedValueMixin: raise TypeError(f"Unsupported type hint '{type_hint}' for initialization.") -class PydanticBaseModel(BaseModel, PydanticModelNestedValueMixin): - """Base model class with automatic serialization and deserialization of `pendulum.DateTime` fields. +class PydanticBaseModel(PydanticModelNestedValueMixin, BaseModel): + """Base model with pendulum datetime support, nested value utilities, and stable hashing. - This model serializes pendulum.DateTime objects to ISO 8601 strings and - deserializes ISO 8601 strings to pendulum.DateTime objects. + This class provides: + - ISO 8601 serialization/deserialization of `pendulum.DateTime` fields. + - Nested attribute access and mutation via `PydanticModelNestedValueMixin`. + - A consistent hash using a UUID for use in sets and as dictionary keys """ # Enable custom serialization globally in config @@ -422,6 +642,17 @@ class PydanticBaseModel(BaseModel, PydanticModelNestedValueMixin): validate_assignment=True, ) + _uuid: str = PrivateAttr(default_factory=lambda: str(uuid.uuid4())) + """str: A private UUID string generated on instantiation, used for hashing.""" + + def __hash__(self) -> int: + """Returns a stable hash based on the instance's UUID. + + Returns: + int: Hash value derived from the model's UUID. + """ + return hash(self._uuid) + @field_validator("*", mode="before") def validate_and_convert_pendulum(cls, value: Any, info: ValidationInfo) -> Any: """Validator to convert fields of type `pendulum.DateTime`. @@ -839,3 +1070,27 @@ class PydanticDateTimeSeries(PydanticBaseModel): class ParametersBaseModel(PydanticBaseModel): model_config = ConfigDict(extra="forbid") + + +def set_private_attr( + model: Union[PydanticBaseModel, PydanticModelNestedValueMixin], key: str, value: Any +) -> None: + """Set a private attribute for a model instance (not stored in model itself).""" + if model not in _model_private_state: + _model_private_state[model] = {} + _model_private_state[model][key] = value + + +def get_private_attr( + model: Union[PydanticBaseModel, PydanticModelNestedValueMixin], key: str, default: Any = None +) -> Any: + """Get a private attribute or return default.""" + return _model_private_state.get(model, {}).get(key, default) + + +def del_private_attr( + model: Union[PydanticBaseModel, PydanticModelNestedValueMixin], key: str +) -> None: + """Delete a private attribute.""" + if model in _model_private_state and key in _model_private_state[model]: + del _model_private_state[model][key] diff --git a/src/akkudoktoreos/devices/battery.py b/src/akkudoktoreos/devices/battery.py index f12dff7..916a842 100644 --- a/src/akkudoktoreos/devices/battery.py +++ b/src/akkudoktoreos/devices/battery.py @@ -3,7 +3,6 @@ from typing import Any, Optional import numpy as np from pydantic import Field, field_validator -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.devices.devicesabc import ( DeviceBase, DeviceOptimizeResult, @@ -11,8 +10,6 @@ from akkudoktoreos.devices.devicesabc import ( ) from akkudoktoreos.utils.utils import NumpyEncoder -logger = get_logger(__name__) - def max_charging_power_field(description: Optional[str] = None) -> float: if description is None: diff --git a/src/akkudoktoreos/devices/devices.py b/src/akkudoktoreos/devices/devices.py index a2cc06e..ff3d38d 100644 --- a/src/akkudoktoreos/devices/devices.py +++ b/src/akkudoktoreos/devices/devices.py @@ -1,15 +1,12 @@ from typing import Optional from akkudoktoreos.core.coreabc import SingletonMixin -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.devices.battery import Battery from akkudoktoreos.devices.devicesabc import DevicesBase from akkudoktoreos.devices.generic import HomeAppliance from akkudoktoreos.devices.inverter import Inverter from akkudoktoreos.devices.settings import DevicesCommonSettings -logger = get_logger(__name__) - class Devices(SingletonMixin, DevicesBase): def __init__(self, settings: Optional[DevicesCommonSettings] = None): diff --git a/src/akkudoktoreos/devices/devicesabc.py b/src/akkudoktoreos/devices/devicesabc.py index 925f18b..a9599fd 100644 --- a/src/akkudoktoreos/devices/devicesabc.py +++ b/src/akkudoktoreos/devices/devicesabc.py @@ -3,6 +3,7 @@ from enum import Enum from typing import Optional, Type +from loguru import logger from pendulum import DateTime from pydantic import Field, computed_field @@ -12,12 +13,9 @@ from akkudoktoreos.core.coreabc import ( EnergyManagementSystemMixin, PredictionMixin, ) -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.core.pydantic import ParametersBaseModel from akkudoktoreos.utils.datetimeutil import to_duration -logger = get_logger(__name__) - class DeviceParameters(ParametersBaseModel): device_id: str = Field(description="ID of device", examples="device1") diff --git a/src/akkudoktoreos/devices/generic.py b/src/akkudoktoreos/devices/generic.py index 701bc0a..e6c9021 100644 --- a/src/akkudoktoreos/devices/generic.py +++ b/src/akkudoktoreos/devices/generic.py @@ -3,11 +3,8 @@ from typing import Optional import numpy as np from pydantic import Field -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.devices.devicesabc import DeviceBase, DeviceParameters -logger = get_logger(__name__) - class HomeApplianceParameters(DeviceParameters): """Home Appliance Device Simulation Configuration.""" diff --git a/src/akkudoktoreos/devices/heatpump.py b/src/akkudoktoreos/devices/heatpump.py index 5df98d5..6cd176c 100644 --- a/src/akkudoktoreos/devices/heatpump.py +++ b/src/akkudoktoreos/devices/heatpump.py @@ -1,6 +1,6 @@ from typing import List, Sequence -from akkudoktoreos.core.logging import get_logger +from loguru import logger class Heatpump: @@ -22,7 +22,6 @@ class Heatpump: def __init__(self, max_heat_output: int, hours: int): self.max_heat_output = max_heat_output self.hours = hours - self.log = get_logger(__name__) def __check_outside_temperature_range__(self, temp_celsius: float) -> bool: """Check if temperature is in valid range between -100 and 100 degree Celsius. @@ -59,7 +58,7 @@ class Heatpump: f"Outside temperature '{outside_temperature_celsius}' not in range " "(min: -100 Celsius, max: 100 Celsius)" ) - self.log.error(err_msg) + logger.error(err_msg) raise ValueError(err_msg) def calculate_heating_output(self, outside_temperature_celsius: float) -> float: @@ -87,7 +86,7 @@ class Heatpump: f"Outside temperature '{outside_temperature_celsius}' not in range " "(min: -100 Celsius, max: 100 Celsius)" ) - self.log.error(err_msg) + logger.error(err_msg) raise ValueError(err_msg) def calculate_heat_power(self, outside_temperature_celsius: float) -> float: @@ -111,7 +110,7 @@ class Heatpump: f"Outside temperature '{outside_temperature_celsius}' not in range " "(min: -100 Celsius, max: 100 Celsius)" ) - self.log.error(err_msg) + logger.error(err_msg) raise ValueError(err_msg) def simulate_24h(self, temperatures: Sequence[float]) -> List[float]: diff --git a/src/akkudoktoreos/devices/inverter.py b/src/akkudoktoreos/devices/inverter.py index 8c15141..11b02b1 100644 --- a/src/akkudoktoreos/devices/inverter.py +++ b/src/akkudoktoreos/devices/inverter.py @@ -1,13 +1,11 @@ from typing import Optional +from loguru import logger from pydantic import Field -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.devices.devicesabc import DeviceBase, DeviceParameters from akkudoktoreos.prediction.interpolator import get_eos_load_interpolator -logger = get_logger(__name__) - class InverterParameters(DeviceParameters): """Inverter Device Simulation Configuration.""" diff --git a/src/akkudoktoreos/devices/settings.py b/src/akkudoktoreos/devices/settings.py index 6d8e458..e9443ce 100644 --- a/src/akkudoktoreos/devices/settings.py +++ b/src/akkudoktoreos/devices/settings.py @@ -3,13 +3,10 @@ from typing import Optional from pydantic import Field from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.devices.battery import BaseBatteryParameters from akkudoktoreos.devices.generic import HomeApplianceParameters from akkudoktoreos.devices.inverter import InverterParameters -logger = get_logger(__name__) - class DevicesCommonSettings(SettingsBaseModel): """Base configuration for devices simulation settings.""" diff --git a/src/akkudoktoreos/measurement/measurement.py b/src/akkudoktoreos/measurement/measurement.py index 395e8a1..5b6fb74 100644 --- a/src/akkudoktoreos/measurement/measurement.py +++ b/src/akkudoktoreos/measurement/measurement.py @@ -9,6 +9,7 @@ The measurements can be added programmatically or imported from a file or JSON s from typing import Any, ClassVar, List, Optional import numpy as np +from loguru import logger from numpydantic import NDArray, Shape from pendulum import DateTime, Duration from pydantic import Field, computed_field @@ -16,11 +17,8 @@ from pydantic import Field, computed_field from akkudoktoreos.config.configabc import SettingsBaseModel from akkudoktoreos.core.coreabc import SingletonMixin from akkudoktoreos.core.dataabc import DataImportMixin, DataRecord, DataSequence -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.utils.datetimeutil import to_duration -logger = get_logger(__name__) - class MeasurementCommonSettings(SettingsBaseModel): """Measurement Configuration.""" diff --git a/src/akkudoktoreos/optimization/genetic.py b/src/akkudoktoreos/optimization/genetic.py index 05369af..dc8497f 100644 --- a/src/akkudoktoreos/optimization/genetic.py +++ b/src/akkudoktoreos/optimization/genetic.py @@ -4,6 +4,7 @@ from typing import Any, Optional import numpy as np from deap import algorithms, base, creator, tools +from loguru import logger from pydantic import Field, field_validator, model_validator from typing_extensions import Self @@ -13,7 +14,6 @@ from akkudoktoreos.core.coreabc import ( EnergyManagementSystemMixin, ) from akkudoktoreos.core.ems import EnergyManagementParameters, SimulationResult -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.core.pydantic import ParametersBaseModel from akkudoktoreos.devices.battery import ( Battery, @@ -25,8 +25,6 @@ from akkudoktoreos.devices.generic import HomeAppliance, HomeApplianceParameters from akkudoktoreos.devices.inverter import Inverter, InverterParameters from akkudoktoreos.utils.utils import NumpyEncoder -logger = get_logger(__name__) - class OptimizationParameters(ParametersBaseModel): ems: EnergyManagementParameters diff --git a/src/akkudoktoreos/optimization/optimization.py b/src/akkudoktoreos/optimization/optimization.py index 77dc0b4..f958e1c 100644 --- a/src/akkudoktoreos/optimization/optimization.py +++ b/src/akkudoktoreos/optimization/optimization.py @@ -3,9 +3,6 @@ from typing import List, Optional from pydantic import Field from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.logging import get_logger - -logger = get_logger(__name__) class OptimizationCommonSettings(SettingsBaseModel): diff --git a/src/akkudoktoreos/optimization/optimizationabc.py b/src/akkudoktoreos/optimization/optimizationabc.py index f82157f..5e49236 100644 --- a/src/akkudoktoreos/optimization/optimizationabc.py +++ b/src/akkudoktoreos/optimization/optimizationabc.py @@ -3,11 +3,8 @@ from pydantic import ConfigDict from akkudoktoreos.core.coreabc import ConfigMixin, PredictionMixin -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.core.pydantic import PydanticBaseModel -logger = get_logger(__name__) - class OptimizationBase(ConfigMixin, PredictionMixin, PydanticBaseModel): """Base class for handling optimization data. diff --git a/src/akkudoktoreos/prediction/elecpriceabc.py b/src/akkudoktoreos/prediction/elecpriceabc.py index 860cd8e..318b146 100644 --- a/src/akkudoktoreos/prediction/elecpriceabc.py +++ b/src/akkudoktoreos/prediction/elecpriceabc.py @@ -9,11 +9,8 @@ from typing import List, Optional from pydantic import Field, computed_field -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.prediction.predictionabc import PredictionProvider, PredictionRecord -logger = get_logger(__name__) - class ElecPriceDataRecord(PredictionRecord): """Represents a electricity price data record containing various price attributes at a specific datetime. diff --git a/src/akkudoktoreos/prediction/elecpriceakkudoktor.py b/src/akkudoktoreos/prediction/elecpriceakkudoktor.py index 6a05e81..65ffe13 100644 --- a/src/akkudoktoreos/prediction/elecpriceakkudoktor.py +++ b/src/akkudoktoreos/prediction/elecpriceakkudoktor.py @@ -11,17 +11,15 @@ from typing import Any, List, Optional, Union import numpy as np import pandas as pd import requests +from loguru import logger from pydantic import ValidationError from statsmodels.tsa.holtwinters import ExponentialSmoothing from akkudoktoreos.core.cache import cache_in_file -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.core.pydantic import PydanticBaseModel from akkudoktoreos.prediction.elecpriceabc import ElecPriceProvider from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration -logger = get_logger(__name__) - class AkkudoktorElecPriceMeta(PydanticBaseModel): start_timestamp: str diff --git a/src/akkudoktoreos/prediction/elecpriceimport.py b/src/akkudoktoreos/prediction/elecpriceimport.py index cf34d76..0cdfd12 100644 --- a/src/akkudoktoreos/prediction/elecpriceimport.py +++ b/src/akkudoktoreos/prediction/elecpriceimport.py @@ -9,15 +9,13 @@ format, enabling consistent access to forecasted and historical elecprice attrib from pathlib import Path from typing import Optional, Union +from loguru import logger from pydantic import Field, field_validator from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.prediction.elecpriceabc import ElecPriceProvider from akkudoktoreos.prediction.predictionabc import PredictionImportProvider -logger = get_logger(__name__) - class ElecPriceImportCommonSettings(SettingsBaseModel): """Common settings for elecprice data import from file or JSON String.""" diff --git a/src/akkudoktoreos/prediction/load.py b/src/akkudoktoreos/prediction/load.py index c46a705..eacd923 100644 --- a/src/akkudoktoreos/prediction/load.py +++ b/src/akkudoktoreos/prediction/load.py @@ -5,13 +5,11 @@ from typing import Optional, Union from pydantic import Field, field_validator from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.prediction.loadabc import LoadProvider from akkudoktoreos.prediction.loadakkudoktor import LoadAkkudoktorCommonSettings from akkudoktoreos.prediction.loadimport import LoadImportCommonSettings from akkudoktoreos.prediction.prediction import get_prediction -logger = get_logger(__name__) prediction_eos = get_prediction() # Valid load providers diff --git a/src/akkudoktoreos/prediction/loadabc.py b/src/akkudoktoreos/prediction/loadabc.py index 6c999c1..de0df8d 100644 --- a/src/akkudoktoreos/prediction/loadabc.py +++ b/src/akkudoktoreos/prediction/loadabc.py @@ -9,11 +9,8 @@ from typing import List, Optional from pydantic import Field -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.prediction.predictionabc import PredictionProvider, PredictionRecord -logger = get_logger(__name__) - class LoadDataRecord(PredictionRecord): """Represents a load data record containing various load attributes at a specific datetime.""" diff --git a/src/akkudoktoreos/prediction/loadakkudoktor.py b/src/akkudoktoreos/prediction/loadakkudoktor.py index cdeefbd..11d8d48 100644 --- a/src/akkudoktoreos/prediction/loadakkudoktor.py +++ b/src/akkudoktoreos/prediction/loadakkudoktor.py @@ -3,15 +3,13 @@ from typing import Optional import numpy as np +from loguru import logger from pydantic import Field from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.prediction.loadabc import LoadProvider from akkudoktoreos.utils.datetimeutil import compare_datetimes, to_datetime, to_duration -logger = get_logger(__name__) - class LoadAkkudoktorCommonSettings(SettingsBaseModel): """Common settings for load data import from file.""" diff --git a/src/akkudoktoreos/prediction/loadimport.py b/src/akkudoktoreos/prediction/loadimport.py index dd54519..13ce6c4 100644 --- a/src/akkudoktoreos/prediction/loadimport.py +++ b/src/akkudoktoreos/prediction/loadimport.py @@ -9,15 +9,13 @@ format, enabling consistent access to forecasted and historical load attributes. from pathlib import Path from typing import Optional, Union +from loguru import logger from pydantic import Field, field_validator from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.prediction.loadabc import LoadProvider from akkudoktoreos.prediction.predictionabc import PredictionImportProvider -logger = get_logger(__name__) - class LoadImportCommonSettings(SettingsBaseModel): """Common settings for load data import from file or JSON string.""" diff --git a/src/akkudoktoreos/prediction/predictionabc.py b/src/akkudoktoreos/prediction/predictionabc.py index 3c6464a..906eb44 100644 --- a/src/akkudoktoreos/prediction/predictionabc.py +++ b/src/akkudoktoreos/prediction/predictionabc.py @@ -10,6 +10,7 @@ and manipulation of configuration and prediction data in a clear, scalable, and from typing import List, Optional +from loguru import logger from pendulum import DateTime from pydantic import Field, computed_field @@ -22,11 +23,8 @@ from akkudoktoreos.core.dataabc import ( DataRecord, DataSequence, ) -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.utils.datetimeutil import to_duration -logger = get_logger(__name__) - class PredictionBase(DataBase, MeasurementMixin): """Base class for handling prediction data. diff --git a/src/akkudoktoreos/prediction/pvforecast.py b/src/akkudoktoreos/prediction/pvforecast.py index f2bd29e..2bd93b6 100644 --- a/src/akkudoktoreos/prediction/pvforecast.py +++ b/src/akkudoktoreos/prediction/pvforecast.py @@ -5,13 +5,11 @@ from typing import Any, List, Optional, Self from pydantic import Field, computed_field, field_validator, model_validator from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.prediction.prediction import get_prediction from akkudoktoreos.prediction.pvforecastabc import PVForecastProvider from akkudoktoreos.prediction.pvforecastimport import PVForecastImportCommonSettings from akkudoktoreos.utils.docs import get_model_structure_from_examples -logger = get_logger(__name__) prediction_eos = get_prediction() # Valid PV forecast providers diff --git a/src/akkudoktoreos/prediction/pvforecastabc.py b/src/akkudoktoreos/prediction/pvforecastabc.py index 33bf5c1..acbe5d3 100644 --- a/src/akkudoktoreos/prediction/pvforecastabc.py +++ b/src/akkudoktoreos/prediction/pvforecastabc.py @@ -7,13 +7,11 @@ Notes: from abc import abstractmethod from typing import List, Optional +from loguru import logger from pydantic import Field -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.prediction.predictionabc import PredictionProvider, PredictionRecord -logger = get_logger(__name__) - class PVForecastDataRecord(PredictionRecord): """Represents a pvforecast data record containing various pvforecast attributes at a specific datetime.""" diff --git a/src/akkudoktoreos/prediction/pvforecastakkudoktor.py b/src/akkudoktoreos/prediction/pvforecastakkudoktor.py index 78f25a6..21e1e03 100644 --- a/src/akkudoktoreos/prediction/pvforecastakkudoktor.py +++ b/src/akkudoktoreos/prediction/pvforecastakkudoktor.py @@ -78,10 +78,10 @@ Methods: from typing import Any, List, Optional, Union import requests +from loguru import logger from pydantic import Field, ValidationError, computed_field, field_validator from akkudoktoreos.core.cache import cache_in_file -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.core.pydantic import PydanticBaseModel from akkudoktoreos.prediction.pvforecastabc import ( PVForecastDataRecord, @@ -89,8 +89,6 @@ from akkudoktoreos.prediction.pvforecastabc import ( ) from akkudoktoreos.utils.datetimeutil import compare_datetimes, to_datetime -logger = get_logger(__name__) - class AkkudoktorForecastHorizon(PydanticBaseModel): altitude: int diff --git a/src/akkudoktoreos/prediction/pvforecastimport.py b/src/akkudoktoreos/prediction/pvforecastimport.py index a093369..528a7a4 100644 --- a/src/akkudoktoreos/prediction/pvforecastimport.py +++ b/src/akkudoktoreos/prediction/pvforecastimport.py @@ -9,15 +9,13 @@ format, enabling consistent access to forecasted and historical pvforecast attri from pathlib import Path from typing import Optional, Union +from loguru import logger from pydantic import Field, field_validator from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.prediction.predictionabc import PredictionImportProvider from akkudoktoreos.prediction.pvforecastabc import PVForecastProvider -logger = get_logger(__name__) - class PVForecastImportCommonSettings(SettingsBaseModel): """Common settings for pvforecast data import from file or JSON string.""" diff --git a/src/akkudoktoreos/prediction/weatherabc.py b/src/akkudoktoreos/prediction/weatherabc.py index 567f597..c98c046 100644 --- a/src/akkudoktoreos/prediction/weatherabc.py +++ b/src/akkudoktoreos/prediction/weatherabc.py @@ -14,11 +14,8 @@ import pandas as pd import pvlib from pydantic import Field -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.prediction.predictionabc import PredictionProvider, PredictionRecord -logger = get_logger(__name__) - class WeatherDataRecord(PredictionRecord): """Represents a weather data record containing various weather attributes at a specific datetime. diff --git a/src/akkudoktoreos/prediction/weatherbrightsky.py b/src/akkudoktoreos/prediction/weatherbrightsky.py index 1197718..7b30414 100644 --- a/src/akkudoktoreos/prediction/weatherbrightsky.py +++ b/src/akkudoktoreos/prediction/weatherbrightsky.py @@ -13,15 +13,12 @@ import numpy as np import pandas as pd import pvlib import requests +from loguru import logger from akkudoktoreos.core.cache import cache_in_file -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.prediction.weatherabc import WeatherDataRecord, WeatherProvider from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration -logger = get_logger(__name__) - - WheaterDataBrightSkyMapping: List[Tuple[str, Optional[str], Optional[Union[str, float]]]] = [ # brightsky_key, description, corr_factor ("timestamp", "DateTime", "to datetime in timezone"), diff --git a/src/akkudoktoreos/prediction/weatherclearoutside.py b/src/akkudoktoreos/prediction/weatherclearoutside.py index 9bf00f2..ec73609 100644 --- a/src/akkudoktoreos/prediction/weatherclearoutside.py +++ b/src/akkudoktoreos/prediction/weatherclearoutside.py @@ -18,15 +18,12 @@ from typing import Dict, List, Optional, Tuple import pandas as pd import requests from bs4 import BeautifulSoup +from loguru import logger from akkudoktoreos.core.cache import cache_in_file -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.prediction.weatherabc import WeatherDataRecord, WeatherProvider from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration, to_timezone -logger = get_logger(__name__) - - WheaterDataClearOutsideMapping: List[Tuple[str, Optional[str], Optional[float]]] = [ # clearoutside_key, description, corr_factor ("DateTime", "DateTime", None), diff --git a/src/akkudoktoreos/prediction/weatherimport.py b/src/akkudoktoreos/prediction/weatherimport.py index a0a5890..8241269 100644 --- a/src/akkudoktoreos/prediction/weatherimport.py +++ b/src/akkudoktoreos/prediction/weatherimport.py @@ -9,15 +9,13 @@ format, enabling consistent access to forecasted and historical weather attribut from pathlib import Path from typing import Optional, Union +from loguru import logger from pydantic import Field, field_validator from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.prediction.predictionabc import PredictionImportProvider from akkudoktoreos.prediction.weatherabc import WeatherProvider -logger = get_logger(__name__) - class WeatherImportCommonSettings(SettingsBaseModel): """Common settings for weather data import from file or JSON string.""" diff --git a/src/akkudoktoreos/server/dash/admin.py b/src/akkudoktoreos/server/dash/admin.py index 7605f4f..d8b1ea2 100644 --- a/src/akkudoktoreos/server/dash/admin.py +++ b/src/akkudoktoreos/server/dash/admin.py @@ -10,6 +10,7 @@ from typing import Any, Optional, Union import requests from fasthtml.common import Select +from loguru import logger from monsterui.foundations import stringify from monsterui.franken import ( # Select, TODO: Select from FrankenUI does not work - using Select from FastHTML instead H3, @@ -29,13 +30,10 @@ from monsterui.franken import ( # Select, TODO: Select from FrankenUI does not ) from platformdirs import user_config_dir -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.server.dash.components import Error, Success from akkudoktoreos.server.dash.configuration import get_nested_value from akkudoktoreos.utils.datetimeutil import to_datetime -logger = get_logger(__name__) - # Directory to export files to, or to import files from export_import_directory = Path(user_config_dir("net.akkudoktor.eosdash", "akkudoktor")) diff --git a/src/akkudoktoreos/server/dash/components.py b/src/akkudoktoreos/server/dash/components.py index 67c476d..87c489f 100644 --- a/src/akkudoktoreos/server/dash/components.py +++ b/src/akkudoktoreos/server/dash/components.py @@ -100,6 +100,7 @@ def ConfigCard( value: str, default: str, description: str, + deprecated: Optional[Union[str, bool]], update_error: Optional[str], update_value: Optional[str], update_open: Optional[bool], @@ -118,6 +119,7 @@ def ConfigCard( value (str): The current value of the configuration. default (str): The default value of the configuration. description (str): A description of the configuration. + deprecated (Optional[Union[str, bool]]): The deprecated marker of the configuration. update_error (Optional[str]): The error message, if any, during the update process. update_value (Optional[str]): The value to be updated, if different from the current value. update_open (Optional[bool]): A flag indicating whether the update section of the card @@ -131,6 +133,9 @@ def ConfigCard( update_value = value if not update_open: update_open = False + if deprecated: + if isinstance(deprecated, bool): + deprecated = "Deprecated" return Card( Details( Summary( @@ -151,13 +156,21 @@ def ConfigCard( Grid( P(description), P(config_type), - ), + ) + if not deprecated + else None, + Grid( + P(deprecated), + P("DEPRECATED!"), + ) + if deprecated + else None, # Default Grid( DivRAligned(P("default")), P(default), ) - if read_only == "rw" + if read_only == "rw" and not deprecated else None, # Set value Grid( @@ -172,7 +185,7 @@ def ConfigCard( ), ), ) - if read_only == "rw" + if read_only == "rw" and not deprecated else None, # Last error Grid( diff --git a/src/akkudoktoreos/server/dash/configuration.py b/src/akkudoktoreos/server/dash/configuration.py index 9c72b15..a7c37dc 100644 --- a/src/akkudoktoreos/server/dash/configuration.py +++ b/src/akkudoktoreos/server/dash/configuration.py @@ -2,6 +2,7 @@ import json from typing import Any, Dict, List, Optional, Sequence, TypeVar, Union import requests +from loguru import logger from monsterui.franken import ( H3, H4, @@ -22,13 +23,10 @@ from pydantic.fields import ComputedFieldInfo, FieldInfo from pydantic_core import PydanticUndefined from akkudoktoreos.config.config import ConfigEOS -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.core.pydantic import PydanticBaseModel from akkudoktoreos.prediction.pvforecast import PVForecastPlaneSetting from akkudoktoreos.server.dash.components import ConfigCard -logger = get_logger(__name__) - T = TypeVar("T") # Latest configuration update results @@ -166,7 +164,7 @@ def configuration( if found_basic: continue - config = {} + config: dict[str, Optional[Any]] = {} config["name"] = ".".join(values_prefix + parent_types) config["value"] = json.dumps( get_nested_value(values, values_prefix + parent_types, "") @@ -175,6 +173,9 @@ def configuration( config["description"] = ( subfield_info.description if subfield_info.description else "" ) + config["deprecated"] = ( + subfield_info.deprecated if subfield_info.deprecated else None + ) if isinstance(subfield_info, ComputedFieldInfo): config["read-only"] = "ro" type_description = str(subfield_info.return_type) @@ -319,6 +320,7 @@ def ConfigPlanesCard( config["value"], config["default"], config["description"], + config["deprecated"], update_error, update_value, update_open, @@ -457,6 +459,7 @@ def Configuration( if ( config["type"] == "Optional[list[akkudoktoreos.prediction.pvforecast.PVForecastPlaneSetting]]" + and not config["deprecated"] ): # Special configuration for PV planes rows.append( @@ -482,6 +485,7 @@ def Configuration( config["value"], config["default"], config["description"], + config["deprecated"], update_error, update_value, update_open, diff --git a/src/akkudoktoreos/server/dash/demo.py b/src/akkudoktoreos/server/dash/demo.py index 34d8bf2..b7a0c06 100644 --- a/src/akkudoktoreos/server/dash/demo.py +++ b/src/akkudoktoreos/server/dash/demo.py @@ -8,7 +8,6 @@ from bokeh.models import ColumnDataSource, LinearAxis, Range1d from bokeh.plotting import figure from monsterui.franken import FT, Grid, P -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.core.pydantic import PydanticDateTimeDataFrame from akkudoktoreos.server.dash.bokeh import Bokeh @@ -17,8 +16,6 @@ FILE_DEMOCONFIG = DIR_DEMODATA.joinpath("democonfig.json") if not FILE_DEMOCONFIG.exists(): raise ValueError(f"File does not exist: {FILE_DEMOCONFIG}") -logger = get_logger(__name__) - # bar width for 1 hour bars (time given in millseconds) BAR_WIDTH_1HOUR = 1000 * 60 * 60 @@ -76,25 +73,37 @@ def DemoElectricityPriceForecast(predictions: pd.DataFrame, config: dict) -> FT: return Bokeh(plot) -def DemoWeatherTempAir(predictions: pd.DataFrame, config: dict) -> FT: +def DemoWeatherTempAirHumidity(predictions: pd.DataFrame, config: dict) -> FT: source = ColumnDataSource(predictions) provider = config["weather"]["provider"] plot = figure( x_axis_type="datetime", - y_range=Range1d( - predictions["weather_temp_air"].min() - 1.0, predictions["weather_temp_air"].max() + 1.0 - ), - title=f"Air Temperature Prediction ({provider})", + title=f"Air Temperature and Humidity Prediction ({provider})", x_axis_label="Datetime", y_axis_label="Temperature [°C]", sizing_mode="stretch_width", height=400, ) + # Add secondary y-axis for humidity + plot.extra_y_ranges["humidity"] = Range1d(start=-5, end=105) + y2_axis = LinearAxis(y_range_name="humidity", axis_label="Relative Humidity [%]") + y2_axis.axis_label_text_color = "green" + plot.add_layout(y2_axis, "left") + plot.line( "date_time", "weather_temp_air", source=source, legend_label="Air Temperature", color="blue" ) + plot.line( + "date_time", + "weather_relative_humidity", + source=source, + legend_label="Relative Humidity [%]", + color="green", + y_range_name="humidity", + ) + return Bokeh(plot) @@ -150,7 +159,10 @@ def DemoLoad(predictions: pd.DataFrame, config: dict) -> FT: sizing_mode="stretch_width", height=400, ) - plot.extra_y_ranges["stddev"] = Range1d(0, 1000) + # Add secondary y-axis for stddev + stddev_min = predictions["load_std"].min() + stddev_max = predictions["load_std"].max() + plot.extra_y_ranges["stddev"] = Range1d(start=stddev_min - 5, end=stddev_max + 5) y2_axis = LinearAxis(y_range_name="stddev", axis_label="Load Standard Deviation [W]") y2_axis.axis_label_text_color = "green" plot.add_layout(y2_axis, "left") @@ -230,6 +242,7 @@ def Demo(eos_host: str, eos_port: Union[str, int]) -> str: "keys": [ "pvforecast_ac_power", "elecprice_marketprice_kwh", + "weather_relative_humidity", "weather_temp_air", "weather_ghi", "weather_dni", @@ -260,7 +273,7 @@ def Demo(eos_host: str, eos_port: Union[str, int]) -> str: return Grid( DemoPVForecast(predictions, democonfig), DemoElectricityPriceForecast(predictions, democonfig), - DemoWeatherTempAir(predictions, democonfig), + DemoWeatherTempAirHumidity(predictions, democonfig), DemoWeatherIrradiance(predictions, democonfig), DemoLoad(predictions, democonfig), cols_max=2, diff --git a/src/akkudoktoreos/server/dash/footer.py b/src/akkudoktoreos/server/dash/footer.py index 97b66b0..bbfdf6f 100644 --- a/src/akkudoktoreos/server/dash/footer.py +++ b/src/akkudoktoreos/server/dash/footer.py @@ -1,14 +1,13 @@ from typing import Optional, Union import requests +from loguru import logger from monsterui.daisy import Loading, LoadingT from monsterui.franken import A, ButtonT, DivFullySpaced, P from requests.exceptions import RequestException from akkudoktoreos.config.config import get_config -from akkudoktoreos.core.logging import get_logger -logger = get_logger(__name__) config_eos = get_config() diff --git a/src/akkudoktoreos/server/eos.py b/src/akkudoktoreos/server/eos.py index 6335a10..9dede18 100755 --- a/src/akkudoktoreos/server/eos.py +++ b/src/akkudoktoreos/server/eos.py @@ -25,11 +25,13 @@ from fastapi.responses import ( RedirectResponse, Response, ) +from loguru import logger from akkudoktoreos.config.config import ConfigEOS, SettingsEOS, get_config from akkudoktoreos.core.cache import CacheFileStore from akkudoktoreos.core.ems import get_ems -from akkudoktoreos.core.logging import get_logger +from akkudoktoreos.core.logabc import LOGGING_LEVELS +from akkudoktoreos.core.logging import read_file_log, track_logging_config from akkudoktoreos.core.pydantic import ( PydanticBaseModel, PydanticDateTimeData, @@ -56,7 +58,6 @@ from akkudoktoreos.server.server import ( ) from akkudoktoreos.utils.datetimeutil import to_datetime, to_duration -logger = get_logger(__name__) config_eos = get_config() measurement_eos = get_measurement() prediction_eos = get_prediction() @@ -66,6 +67,14 @@ ems_eos = get_ems() args = None +# ---------------------- +# Logging configuration +# ---------------------- + +logger.remove() +track_logging_config(config_eos, "logging", None, None) +config_eos.track_nested_value("/logging", track_logging_config) + # ---------------------- # EOSdash server startup # ---------------------- @@ -177,18 +186,32 @@ def cache_save() -> dict: return CacheFileStore().save_store() -@repeat_every(seconds=float(config_eos.cache.cleanup_interval)) +def cache_cleanup_on_exception(e: Exception) -> None: + logger.error("Cache cleanup task caught an exception: {}", e, exc_info=True) + + +@repeat_every( + seconds=float(config_eos.cache.cleanup_interval), + on_exception=cache_cleanup_on_exception, +) def cache_cleanup_task() -> None: """Repeating task to clear cache from expired cache files.""" + logger.debug("Clear cache") cache_clear() +def energy_management_on_exception(e: Exception) -> None: + logger.error("Energy management task caught an exception: {}", e, exc_info=True) + + @repeat_every( seconds=10, wait_first=config_eos.ems.startup_delay, + on_exception=energy_management_on_exception, ) def energy_management_task() -> None: """Repeating task for energy management.""" + logger.debug("Check EMS run") ems_eos.manage_energy() @@ -219,6 +242,7 @@ async def server_shutdown_task() -> None: os.kill(pid, signal.SIGTERM) # type: ignore[attr-defined,unused-ignore] logger.info(f"🚀 EOS terminated, PID {pid}") + sys.exit(0) @asynccontextmanager @@ -544,6 +568,52 @@ def fastapi_config_get_key( raise HTTPException(status_code=400, detail=str(e)) +@app.get("/v1/logging/log", tags=["logging"]) +async def fastapi_logging_get_log( + limit: int = Query(100, description="Maximum number of log entries to return."), + level: Optional[str] = Query(None, description="Filter by log level (e.g., INFO, ERROR)."), + contains: Optional[str] = Query(None, description="Filter logs containing this substring."), + regex: Optional[str] = Query(None, description="Filter logs by matching regex in message."), + from_time: Optional[str] = Query( + None, description="Start time (ISO format) for filtering logs." + ), + to_time: Optional[str] = Query(None, description="End time (ISO format) for filtering logs."), + tail: bool = Query(False, description="If True, returns the most recent lines (tail mode)."), +) -> JSONResponse: + """Get structured log entries from the EOS log file. + + Filters and returns log entries based on the specified query parameters. The log + file is expected to contain newline-delimited JSON entries. + + Args: + limit (int): Maximum number of entries to return. + level (Optional[str]): Filter logs by severity level (e.g., DEBUG, INFO). + contains (Optional[str]): Return only logs that include this string in the message. + regex (Optional[str]): Return logs that match this regular expression in the message. + from_time (Optional[str]): ISO 8601 timestamp to filter logs not older than this. + to_time (Optional[str]): ISO 8601 timestamp to filter logs not newer than this. + tail (bool): If True, fetch the most recent log entries (like `tail`). + + Returns: + JSONResponse: A JSON list of log entries. + """ + log_path = config_eos.logging.file_path + try: + logs = read_file_log( + log_path=log_path, + limit=limit, + level=level, + contains=contains, + regex=regex, + from_time=from_time, + to_time=to_time, + tail=tail, + ) + return JSONResponse(content=logs) + except Exception as e: + return JSONResponse(content={"error": str(e)}, status_code=500) + + @app.get("/v1/measurement/keys", tags=["measurement"]) def fastapi_measurement_keys_get() -> list[str]: """Get a list of available measurement keys.""" @@ -1245,45 +1315,46 @@ Did you want to connect to EOSdash? return RedirectResponse(url="/docs", status_code=303) -def run_eos(host: str, port: int, log_level: str, access_log: bool, reload: bool) -> None: +def run_eos(host: str, port: int, log_level: str, reload: bool) -> None: """Run the EOS server with the specified configurations. - This function starts the EOS server using the Uvicorn ASGI server. It accepts - arguments for the host, port, log level, access log, and reload options. The - log level is converted to lowercase to ensure compatibility with Uvicorn's - expected log level format. If an error occurs while attempting to bind the - server to the specified host and port, an error message is logged and the - application exits. + Starts the EOS server using the Uvicorn ASGI server. Logs an error and exits if + binding to the host and port fails. - Parameters: - host (str): The hostname to bind the server to. - port (int): The port number to bind the server to. - log_level (str): The log level for the server. Options include "critical", "error", - "warning", "info", "debug", and "trace". - access_log (bool): Whether to enable or disable the access log. Set to True to enable. - reload (bool): Whether to enable or disable auto-reload. Set to True for development. + Args: + host (str): Hostname to bind the server to. + port (int): Port number to bind the server to. + log_level (str): Log level for the server. One of + "critical", "error", "warning", "info", "debug", or "trace". + reload (bool): Enable or disable auto-reload. True for development. Returns: - None + None """ # Make hostname Windows friendly if host == "0.0.0.0" and os.name == "nt": # noqa: S104 host = "localhost" + # Setup console logging level using nested value + # - triggers logging configuration by track_logging_config + if log_level.upper() in LOGGING_LEVELS: + config_eos.set_nested_value("logging/console_level", log_level.upper()) + # Wait for EOS port to be free - e.g. in case of restart wait_for_port_free(port, timeout=120, waiting_app_name="EOS") try: + # Let uvicorn run the fastAPI app uvicorn.run( "akkudoktoreos.server.eos:app", host=host, port=port, - log_level=log_level.lower(), # Convert log_level to lowercase - access_log=access_log, + log_level="info", + access_log=True, reload=reload, ) except Exception as e: - logger.error(f"Could not bind to host {host}:{port}. Error: {e}") + logger.exception("Failed to start uvicorn server.") raise e @@ -1298,7 +1369,7 @@ def main() -> None: Command-line Arguments: --host (str): Host for the EOS server (default: value from config). --port (int): Port for the EOS server (default: value from config). - --log_level (str): Log level for the server. Options: "critical", "error", "warning", "info", "debug", "trace" (default: "info"). + --log_level (str): Log level for the server console. Options: "critical", "error", "warning", "info", "debug", "trace" (default: "info"). --access_log (bool): Enable or disable access log. Options: True or False (default: False). --reload (bool): Enable or disable auto-reload. Useful for development. Options: True or False (default: False). """ @@ -1322,14 +1393,8 @@ def main() -> None: parser.add_argument( "--log_level", type=str, - default="info", - help='Log level for the server. Options: "critical", "error", "warning", "info", "debug", "trace" (default: "info")', - ) - parser.add_argument( - "--access_log", - type=bool, - default=False, - help="Enable or disable access log. Options: True or False (default: True)", + default="none", + help='Log level for the server console. Options: "critical", "error", "warning", "info", "debug", "trace" (default: "none")', ) parser.add_argument( "--reload", @@ -1344,7 +1409,7 @@ def main() -> None: port = args.port if args.port else 8503 try: - run_eos(host, port, args.log_level, args.access_log, args.reload) + run_eos(host, port, args.log_level, args.reload) except: sys.exit(1) diff --git a/src/akkudoktoreos/server/eosdash.py b/src/akkudoktoreos/server/eosdash.py index e290479..82a8663 100644 --- a/src/akkudoktoreos/server/eosdash.py +++ b/src/akkudoktoreos/server/eosdash.py @@ -8,10 +8,10 @@ from typing import Optional import psutil import uvicorn from fasthtml.common import FileResponse, JSONResponse +from loguru import logger from monsterui.core import FastHTML, Theme from akkudoktoreos.config.config import get_config -from akkudoktoreos.core.logging import get_logger # Pages from akkudoktoreos.server.dash.admin import Admin @@ -23,7 +23,6 @@ from akkudoktoreos.server.dash.footer import Footer from akkudoktoreos.server.dash.hello import Hello from akkudoktoreos.server.server import get_default_host, wait_for_port_free -logger = get_logger(__name__) config_eos = get_config() # The favicon for EOSdash diff --git a/src/akkudoktoreos/server/server.py b/src/akkudoktoreos/server/server.py index 8578589..ba695ac 100644 --- a/src/akkudoktoreos/server/server.py +++ b/src/akkudoktoreos/server/server.py @@ -6,12 +6,10 @@ import time from typing import Optional, Union import psutil +from loguru import logger from pydantic import Field, IPvAnyAddress, field_validator from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.logging import get_logger - -logger = get_logger(__name__) def get_default_host() -> str: diff --git a/src/akkudoktoreos/utils/datetimeutil.py b/src/akkudoktoreos/utils/datetimeutil.py index eb57e63..3f853a1 100644 --- a/src/akkudoktoreos/utils/datetimeutil.py +++ b/src/akkudoktoreos/utils/datetimeutil.py @@ -27,13 +27,11 @@ from datetime import date, datetime, timedelta from typing import Any, List, Literal, Optional, Tuple, Union, overload import pendulum +from loguru import logger from pendulum import Date, DateTime, Duration from pendulum.tz.timezone import Timezone from timezonefinder import TimezoneFinder -from akkudoktoreos.core.logging import get_logger - -logger = get_logger(__name__) MAX_DURATION_STRING_LENGTH = 350 @@ -154,22 +152,22 @@ def to_datetime( fmt_tz = f"{fmt} z" dt_tz = f"{date_input} {in_timezone}" dt = pendulum.from_format(dt_tz, fmt_tz) - logger.debug( + logger.trace( f"Str Fmt converted: {dt}, tz={dt.tz} from {date_input}, tz={in_timezone}" ) break except ValueError as e: - logger.debug(f"{date_input}, {fmt}, {e}") + logger.trace(f"{date_input}, {fmt}, {e}") dt = None else: # DateTime input with timezone info try: dt = pendulum.parse(date_input) - logger.debug( + logger.trace( f"Pendulum Fmt converted: {dt}, tz={dt.tz} from {date_input}, tz={in_timezone}" ) except pendulum.parsing.exceptions.ParserError as e: - logger.debug(f"Date string {date_input} does not match any Pendulum formats: {e}") + logger.trace(f"Date string {date_input} does not match any Pendulum formats: {e}") dt = None if dt is None: # Some special values @@ -181,7 +179,7 @@ def to_datetime( timestamp = float(date_input) dt = pendulum.from_timestamp(timestamp, tz="UTC") except (ValueError, TypeError) as e: - logger.debug(f"Date string {date_input} does not match timestamp format: {e}") + logger.trace(f"Date string {date_input} does not match timestamp format: {e}") dt = None if dt is None: raise ValueError(f"Date string {date_input} does not match any known formats.") @@ -202,7 +200,7 @@ def to_datetime( # Represent in target timezone dt_in_tz = dt.in_timezone(in_timezone) - logger.debug( + logger.trace( f"\nTimezone adapted to: {in_timezone}\nfrom: {dt} tz={dt.timezone}\nto: {dt_in_tz} tz={dt_in_tz.tz}" ) dt = dt_in_tz @@ -277,7 +275,7 @@ def to_duration( duration = pendulum.parse(input_value) return duration - duration.start_of("day") except pendulum.parsing.exceptions.ParserError as e: - logger.debug(f"Invalid Pendulum time string format '{input_value}': {e}") + logger.trace(f"Invalid Pendulum time string format '{input_value}': {e}") # Handle strings like "2 days 5 hours 30 minutes" total_seconds = 0 diff --git a/src/akkudoktoreos/utils/docs.py b/src/akkudoktoreos/utils/docs.py index a469c0b..50af4fd 100644 --- a/src/akkudoktoreos/utils/docs.py +++ b/src/akkudoktoreos/utils/docs.py @@ -35,6 +35,8 @@ def get_model_structure_from_examples( example_data: list[dict[str, Any]] = [{} for _ in range(example_max_length)] for field_name, field_info in model_class.model_fields.items(): + if field_info.deprecated: + continue for example_ix in range(example_max_length): example_data[example_ix][field_name] = get_example_or_default( field_name, field_info, example_ix diff --git a/src/akkudoktoreos/utils/utils.py b/src/akkudoktoreos/utils/utils.py index c3ecd88..f16db3a 100644 --- a/src/akkudoktoreos/utils/utils.py +++ b/src/akkudoktoreos/utils/utils.py @@ -4,9 +4,6 @@ from typing import Any import numpy as np from akkudoktoreos.config.configabc import SettingsBaseModel -from akkudoktoreos.core.logging import get_logger - -logger = get_logger(__name__) class UtilsCommonSettings(SettingsBaseModel): diff --git a/src/akkudoktoreos/utils/visualize.py b/src/akkudoktoreos/utils/visualize.py index 45fbcf2..25ed877 100644 --- a/src/akkudoktoreos/utils/visualize.py +++ b/src/akkudoktoreos/utils/visualize.py @@ -13,16 +13,17 @@ from matplotlib.backends.backend_pdf import PdfPages from akkudoktoreos.core.coreabc import ConfigMixin from akkudoktoreos.core.ems import EnergyManagement -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.optimization.genetic import OptimizationParameters from akkudoktoreos.utils.datetimeutil import to_datetime -logger = get_logger(__name__) matplotlib.use( "Agg" ) # non-interactive backend that can only write to files, backend needed to stay in main thread. +debug_visualize: bool = False + + class VisualizationReport(ConfigMixin): def __init__( self, @@ -440,6 +441,8 @@ def prepare_visualize( filename: str = "visualization_results.pdf", start_hour: int = 0, ) -> None: + global debug_visualize + report = VisualizationReport(filename) next_full_hour_date = EnergyManagement.set_start_datetime() # Group 1: @@ -642,7 +645,7 @@ def prepare_visualize( if filtered_balance.size > 0 or filtered_losses.size > 0: report.finalize_group() - if logger.level == "DEBUG" or results["fixed_seed"]: + if debug_visualize or results["fixed_seed"]: report.create_line_chart( 0, [ @@ -667,6 +670,8 @@ def prepare_visualize( def generate_example_report(filename: str = "example_report.pdf") -> None: """Generate example visualization report.""" + global debug_visualize + report = VisualizationReport(filename, "test") x_hours = 0 # Define x-axis start values (e.g., hours) @@ -738,9 +743,9 @@ def generate_example_report(filename: str = "example_report.pdf") -> None: report.finalize_group() # Finalize the third group of charts - logger.setLevel("DEBUG") # set level for example report + debug_visualize = True # set level for example report - if logger.level == "DEBUG": + if debug_visualize: report.create_line_chart( x_hours, [np.array([0.2, 0.25, 0.3, 0.35])], diff --git a/tests/conftest.py b/tests/conftest.py index b6d6d78..332812d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -16,35 +16,75 @@ import pendulum import psutil import pytest import requests +from _pytest.logging import LogCaptureFixture +from loguru import logger from xprocess import ProcessStarter, XProcess from akkudoktoreos.config.config import ConfigEOS, get_config -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.server.server import get_default_host -logger = get_logger(__name__) +# ----------------------------------------------- +# Adapt pytest logging handling to Loguru logging +# ----------------------------------------------- + +@pytest.fixture +def caplog(caplog: LogCaptureFixture): + """Propagate Loguru logs to the pytest caplog handler.""" + handler_id = logger.add( + caplog.handler, + format="{message}", + level=0, + filter=lambda record: record["level"].no >= caplog.handler.level, + enqueue=False, # Set to 'True' if your test is spawning child processes. + ) + yield caplog + try: + logger.remove(handler_id) + except: + # May already be deleted + pass + + +@pytest.fixture +def reportlog(pytestconfig): + """Propagate Loguru logs to the pytest terminal reporter.""" + logging_plugin = pytestconfig.pluginmanager.getplugin("logging-plugin") + handler_id = logger.add(logging_plugin.report_handler, format="{message}") + yield + try: + logger.remove(handler_id) + except: + # May already be deleted + pass + + +@pytest.fixture(autouse=True) +def propagate_logs(): + """Deal with the pytest --log-cli-level command-line flag. + + This option controls the standard logging logs, not loguru ones. + For this reason, we first install a PropagateHandler for compatibility. + """ + class PropagateHandler(logging.Handler): + def emit(self, record): + if logging.getLogger(record.name).isEnabledFor(record.levelno): + logging.getLogger(record.name).handle(record) + + logger.remove() + logger.add(PropagateHandler(), format="{message}") + yield @pytest.fixture() def disable_debug_logging(scope="session", autouse=True): """Automatically disable debug logging for all tests.""" - original_levels = {} - root_logger = logging.getLogger() + logger.remove() # Remove all loggers + logger.add(sys.stderr, level="INFO") # Only show INFO and above - original_levels[root_logger] = root_logger.level - root_logger.setLevel(logging.INFO) - - for logger_name, logger in logging.root.manager.loggerDict.items(): - if isinstance(logger, logging.Logger): - original_levels[logger] = logger.level - if logger.level <= logging.DEBUG: - logger.setLevel(logging.INFO) - - yield - - for logger, level in original_levels.items(): - logger.setLevel(level) +# ----------------------------------------------- +# Provide pytest options for specific test setups +# ----------------------------------------------- def pytest_addoption(parser): parser.addoption( @@ -144,6 +184,7 @@ def cfg_non_existent(request): @pytest.fixture(autouse=True) def user_cwd(config_default_dirs): + """Patch cwd provided by module pathlib.Path.cwd.""" with patch( "pathlib.Path.cwd", return_value=config_default_dirs[1], @@ -153,6 +194,7 @@ def user_cwd(config_default_dirs): @pytest.fixture(autouse=True) def user_config_dir(config_default_dirs): + """Patch user_config_dir provided by module platformdirs.""" with patch( "akkudoktoreos.config.config.user_config_dir", return_value=str(config_default_dirs[0]), @@ -162,6 +204,7 @@ def user_config_dir(config_default_dirs): @pytest.fixture(autouse=True) def user_data_dir(config_default_dirs): + """Patch user_data_dir provided by module platformdirs.""" with patch( "akkudoktoreos.config.config.user_data_dir", return_value=str(config_default_dirs[-1] / "data"), @@ -189,14 +232,18 @@ def config_eos( config_file_cwd = config_default_dirs[1] / ConfigEOS.CONFIG_FILE_NAME assert not config_file.exists() assert not config_file_cwd.exists() + config_eos = get_config() config_eos.reset_settings() assert config_file == config_eos.general.config_file_path assert config_file.exists() assert not config_file_cwd.exists() + + # Check user data directory pathes (config_default_dirs[-1] == data_default_dir_user) assert config_default_dirs[-1] / "data" == config_eos.general.data_folder_path assert config_default_dirs[-1] / "data/cache" == config_eos.cache.path() assert config_default_dirs[-1] / "data/output" == config_eos.general.data_output_path + assert config_default_dirs[-1] / "data/output/eos.log" == config_eos.logging.file_path return config_eos diff --git a/tests/test_config.py b/tests/test_config.py index 71657f5..24da024 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -4,12 +4,10 @@ from typing import Union from unittest.mock import patch import pytest +from loguru import logger from pydantic import ValidationError from akkudoktoreos.config.config import ConfigEOS, GeneralSettings -from akkudoktoreos.core.logging import get_logger - -logger = get_logger(__name__) # overwrite config_mixin fixture from conftest diff --git a/tests/test_dataabc.py b/tests/test_dataabc.py index 9902274..519c14c 100644 --- a/tests/test_dataabc.py +++ b/tests/test_dataabc.py @@ -156,7 +156,7 @@ class TestDataRecord: assert "data_value" in record_dict assert record_dict["data_value"] == 20.0 record2 = DerivedRecord.from_dict(record_dict) - assert record2 == record + assert record2.model_dump() == record.model_dump() def test_to_json(self): record = self.create_test_record(datetime(2024, 1, 3, tzinfo=timezone.utc), 10.0) @@ -165,7 +165,7 @@ class TestDataRecord: assert "data_value" in json_str assert "20.0" in json_str record2 = DerivedRecord.from_json(json_str) - assert record2 == record + assert record2.model_dump() == record.model_dump() class TestDataSequence: @@ -526,7 +526,7 @@ class TestDataSequence: data_dict = sequence.to_dict() assert isinstance(data_dict, dict) sequence_other = sequence.from_dict(data_dict) - assert sequence_other == sequence + assert sequence_other.model_dump() == sequence.model_dump() def test_to_json(self, sequence): record = self.create_test_record(datetime(2023, 11, 6), 0.8) diff --git a/tests/test_elecpriceakkudoktor.py b/tests/test_elecpriceakkudoktor.py index 2d0ee45..568777f 100644 --- a/tests/test_elecpriceakkudoktor.py +++ b/tests/test_elecpriceakkudoktor.py @@ -5,10 +5,10 @@ from unittest.mock import Mock, patch import numpy as np import pytest import requests +from loguru import logger from akkudoktoreos.core.cache import CacheFileStore from akkudoktoreos.core.ems import get_ems -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.prediction.elecpriceakkudoktor import ( AkkudoktorElecPrice, AkkudoktorElecPriceValue, @@ -22,8 +22,6 @@ FILE_TESTDATA_ELECPRICEAKKUDOKTOR_1_JSON = DIR_TESTDATA.joinpath( "elecpriceforecast_akkudoktor_1.json" ) -logger = get_logger(__name__) - @pytest.fixture def provider(monkeypatch, config_eos): @@ -94,7 +92,7 @@ def test_request_forecast(mock_get, provider, sample_akkudoktor_1_json): akkudoktor_data = provider._request_forecast() assert isinstance(akkudoktor_data, AkkudoktorElecPrice) - assert akkudoktor_data.values[0] == AkkudoktorElecPriceValue( + assert akkudoktor_data.values[0].model_dump() == AkkudoktorElecPriceValue( start_timestamp=1733785200000, end_timestamp=1733788800000, start="2024-12-09T23:00:00.000Z", @@ -102,7 +100,7 @@ def test_request_forecast(mock_get, provider, sample_akkudoktor_1_json): marketprice=92.85, unit="Eur/MWh", marketpriceEurocentPerKWh=9.29, - ) + ).model_dump() @patch("requests.get") diff --git a/tests/test_logging.py b/tests/test_logging.py index 0bb8f22..9a40903 100644 --- a/tests/test_logging.py +++ b/tests/test_logging.py @@ -1,69 +1,35 @@ """Test Module for logging Module.""" - import logging -from logging.handlers import RotatingFileHandler +import os +import sys from pathlib import Path +from unittest.mock import patch import pytest +from loguru import logger -from akkudoktoreos.core.logging import get_logger +from akkudoktoreos.core.logging import track_logging_config # ----------------------------- -# get_logger +# logsettings # ----------------------------- +class TestLoggingCommonSettings: + def teardown_method(self): + """Reset Loguru after each test to avoid handler contamination.""" + logger.remove() -def test_get_logger_console_logging(): - """Test logger creation with console logging.""" - logger = get_logger("test_logger", logging_level="DEBUG") + def test_valid_console_level_sets_logging(self, config_eos, caplog): + config_eos.track_nested_value("/logging", track_logging_config) + config_eos.set_nested_value("/logging/console_level", "INFO") + assert config_eos.get_nested_value("/logging/console_level") == "INFO" + assert config_eos.logging.console_level == "INFO" + assert any("console: INFO" in message for message in caplog.messages) - # Check logger name - assert logger.name == "test_logger" - - # Check logger level - assert logger.level == logging.DEBUG - - # Check console handler is present - assert len(logger.handlers) == 1 - assert isinstance(logger.handlers[0], logging.StreamHandler) - - -def test_get_logger_file_logging(tmpdir): - """Test logger creation with file logging.""" - log_file = Path(tmpdir).joinpath("test.log") - logger = get_logger("test_logger", log_file=str(log_file), logging_level="WARNING") - - # Check logger name - assert logger.name == "test_logger" - - # Check logger level - assert logger.level == logging.WARNING - - # Check console handler is present - assert len(logger.handlers) == 2 # One for console and one for file - assert isinstance(logger.handlers[0], logging.StreamHandler) - assert isinstance(logger.handlers[1], RotatingFileHandler) - - # Check file existence - assert log_file.exists() - - -def test_get_logger_no_file_logging(): - """Test logger creation without file logging.""" - logger = get_logger("test_logger") - - # Check logger name - assert logger.name == "test_logger" - - # Check logger level - assert logger.level == logging.INFO - - # Check no file handler is present - assert len(logger.handlers) >= 1 # First is console handler (maybe be pytest handler) - assert isinstance(logger.handlers[0], logging.StreamHandler) - - -def test_get_logger_with_invalid_level(): - """Test logger creation with an invalid logging level.""" - with pytest.raises(ValueError, match="Unknown loggin level: INVALID"): - logger = get_logger("test_logger", logging_level="INVALID") + def test_valid_console_level_calls_tracking_callback(self, config_eos): + with patch("akkudoktoreos.core.logging.track_logging_config") as mock_setup: + config_eos.track_nested_value("/logging", mock_setup) + config_eos.set_nested_value("/logging/console_level", "INFO") + assert config_eos.get_nested_value("/logging/console_level") == "INFO" + assert config_eos.logging.console_level == "INFO" + mock_setup.assert_called_once() diff --git a/tests/test_pvforecastakkudoktor.py b/tests/test_pvforecastakkudoktor.py index 97aeea5..8831030 100644 --- a/tests/test_pvforecastakkudoktor.py +++ b/tests/test_pvforecastakkudoktor.py @@ -3,9 +3,9 @@ from pathlib import Path from unittest.mock import Mock, patch import pytest +from loguru import logger from akkudoktoreos.core.ems import get_ems -from akkudoktoreos.core.logging import get_logger from akkudoktoreos.prediction.prediction import get_prediction from akkudoktoreos.prediction.pvforecastakkudoktor import ( AkkudoktorForecastHorizon, @@ -24,8 +24,6 @@ FILE_TESTDATA_PV_FORECAST_INPUT_SINGLE_PLANE = DIR_TESTDATA.joinpath( ) FILE_TESTDATA_PV_FORECAST_RESULT_1 = DIR_TESTDATA.joinpath("pv_forecast_result_1.txt") -logger = get_logger(__name__) - @pytest.fixture def sample_settings(config_eos): diff --git a/tests/test_pydantic.py b/tests/test_pydantic.py index 9b5e9cb..49f1f30 100644 --- a/tests/test_pydantic.py +++ b/tests/test_pydantic.py @@ -66,6 +66,11 @@ class TestPydanticModelNestedValueMixin: with pytest.raises(TypeError): PydanticModelNestedValueMixin._get_key_types(User, "unknown_field") + def test_get_key_types_for_instance_raises(self, user_instance): + """Test _get_key_types raises an error for an instance.""" + with pytest.raises(TypeError): + PydanticModelNestedValueMixin._get_key_types(user_instance, "unknown_field") + def test_set_nested_value_in_model(self, user_instance): """Test setting nested value in a model field (Address -> city).""" assert user_instance.addresses is None @@ -123,7 +128,7 @@ class TestPydanticModelNestedValueMixin: """Test attempting to set value for a non-existent field.""" user = User(name="John") - with pytest.raises(ValueError): + with pytest.raises(TypeError): user.set_nested_value("non_existent_field", "Some Value") def test_set_nested_value_with_invalid_type(self, user_instance): @@ -144,6 +149,91 @@ class TestPydanticModelNestedValueMixin: "The first address should be an instance of Address" ) + def test_track_nested_value_simple_callback(self, user_instance): + user_instance.set_nested_value("addresses/0/city", "NY") + assert user_instance.addresses is not None + assert user_instance.addresses[0].city == "NY" + + callback_calls = [] + def cb(model, path, old, new): + callback_calls.append((path, old, new)) + + user_instance.track_nested_value("addresses/0/city", cb) + user_instance.set_nested_value("addresses/0/city", "LA") + assert user_instance.addresses is not None + assert user_instance.addresses[0].city == "LA" + assert callback_calls == [("addresses/0/city", "NY", "LA")] + + def test_track_nested_value_prefix_triggers(self, user_instance): + user_instance.set_nested_value("addresses/0", Address(city="Berlin", postal_code="10000")) + assert user_instance.addresses is not None + assert user_instance.addresses[0].city == "Berlin" + + cb_prefix = [] + cb_exact = [] + + def cb1(model, path, old, new): + cb_prefix.append((path, old, new)) + def cb2(model, path, old, new): + cb_exact.append((path, old, new)) + + user_instance.track_nested_value("addresses/0", cb1) + user_instance.track_nested_value("addresses/0/city", cb2) + user_instance.set_nested_value("addresses/0/city", "Munich") + assert user_instance.addresses is not None + assert user_instance.addresses[0].city == "Munich" + + # Both callbacks should be triggered + assert cb_prefix == [("addresses/0/city", "Berlin", "Munich")] + assert cb_exact == [("addresses/0/city", "Berlin", "Munich")] + + def test_track_nested_value_multiple_callbacks_same_path(self, user_instance): + user_instance.set_nested_value("addresses/0/city", "Berlin") + calls1 = [] + calls2 = [] + + user_instance.track_nested_value("addresses/0/city", lambda lib, path, o, n: calls1.append((path, o, n))) + user_instance.track_nested_value("addresses/0/city", lambda lib, path, o, n: calls2.append((path, o, n))) + user_instance.set_nested_value("addresses/0/city", "Stuttgart") + + assert calls1 == [("addresses/0/city", "Berlin", "Stuttgart")] + assert calls2 == [("addresses/0/city", "Berlin", "Stuttgart")] + + def test_track_nested_value_invalid_path_raises(self, user_instance): + with pytest.raises(ValueError) as excinfo: + user_instance.track_nested_value("unknown_field", lambda model, path, o, n: None) + assert "is invalid" in str(excinfo.value) + + with pytest.raises(ValueError) as excinfo: + user_instance.track_nested_value("unknown_field/0/city", lambda model, path, o, n: None) + assert "is invalid" in str(excinfo.value) + + def test_track_nested_value_list_and_dict_path(self): + class Book(PydanticBaseModel): + title: str + + class Library(PydanticBaseModel): + books: list[Book] + meta: dict[str, str] = {} + + lib = Library(books=[Book(title="A")], meta={"location": "center"}) + assert lib.meta["location"] == "center" + calls = [] + + # For list, only root attribute structure is checked, not indices + lib.track_nested_value("books/0/title", lambda lib, path, o, n: calls.append((path, o, n))) + lib.set_nested_value("books/0/title", "B") + assert lib.books[0].title == "B" + assert calls == [("books/0/title", "A", "B")] + + # For dict, only root attribute structure is checked + meta_calls = [] + lib.track_nested_value("meta/location", lambda lib, path, o, n: meta_calls.append((path, o, n))) + assert lib.meta["location"] == "center" + lib.set_nested_value("meta/location", "north") + assert lib.meta["location"] == "north" + assert meta_calls == [("meta/location", "center", "north")] + class TestPydanticBaseModel: def test_valid_pendulum_datetime(self):