From a5c4f62002b94e3e62a897dba81546f4da44c46b Mon Sep 17 00:00:00 2001 From: Vlad Iftime Date: Tue, 7 Jan 2025 21:38:28 +0100 Subject: [PATCH 01/14] Add OMBCInstruction class and initial structure for OMBC modules --- src/s2python/ombc/ombc_instruction.py | 19 +++++++++++++++++++ src/s2python/ombc/ombc_operation_mode.py | 0 src/s2python/ombc/ombc_status.py | 0 src/s2python/ombc/ombc_system_description.py | 0 src/s2python/ombc/ombc_timer_status.py | 0 5 files changed, 19 insertions(+) create mode 100644 src/s2python/ombc/ombc_instruction.py create mode 100644 src/s2python/ombc/ombc_operation_mode.py create mode 100644 src/s2python/ombc/ombc_status.py create mode 100644 src/s2python/ombc/ombc_system_description.py create mode 100644 src/s2python/ombc/ombc_timer_status.py diff --git a/src/s2python/ombc/ombc_instruction.py b/src/s2python/ombc/ombc_instruction.py new file mode 100644 index 0000000..dc4d760 --- /dev/null +++ b/src/s2python/ombc/ombc_instruction.py @@ -0,0 +1,19 @@ +import uuid + +from s2python.generated.gen_s2 import OMBCInstruction as GenOMBCInstruction +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + +@catch_and_convert_exceptions +class OMBCInstruction(GenOMBCInstruction, S2Message["OMBCInstruction"]): + model_config = GenOMBCInstruction.model_config + model_config["validate_assignment"] = True + + id: uuid.UUID = GenOMBCInstruction.model_fields["id"] # type: ignore[assignment] + message_id: uuid.UUID = GenOMBCInstruction.model_fields["message_id"] # type: ignore[assignment] + abnormal_condition: bool = GenOMBCInstruction.model_fields["abnormal_condition"] # type: ignore[assignment] + operation_mode_factor: float = GenOMBCInstruction.model_fields["operation_mode_factor"] # type: ignore[assignment] + operation_mode_id: uuid.UUID = GenOMBCInstruction.model_fields["operation_mode_id"] # type: ignore[assignment] + diff --git a/src/s2python/ombc/ombc_operation_mode.py b/src/s2python/ombc/ombc_operation_mode.py new file mode 100644 index 0000000..e69de29 diff --git a/src/s2python/ombc/ombc_status.py b/src/s2python/ombc/ombc_status.py new file mode 100644 index 0000000..e69de29 diff --git a/src/s2python/ombc/ombc_system_description.py b/src/s2python/ombc/ombc_system_description.py new file mode 100644 index 0000000..e69de29 diff --git a/src/s2python/ombc/ombc_timer_status.py b/src/s2python/ombc/ombc_timer_status.py new file mode 100644 index 0000000..e69de29 From d6de2ba2ad2c06884a675ec5c0a9e98da65a3450 Mon Sep 17 00:00:00 2001 From: Vlad Iftime Date: Tue, 7 Jan 2025 21:55:50 +0100 Subject: [PATCH 02/14] Add OMBC classes: Instruction, Status, OperationMode, SystemDescription, and TimerStatus --- src/s2python/ombc/__init__.py | 3 +++ src/s2python/ombc/ombc_instruction.py | 2 +- src/s2python/ombc/ombc_operation_mode.py | 21 ++++++++++++++++ src/s2python/ombc/ombc_status.py | 17 +++++++++++++ src/s2python/ombc/ombc_system_description.py | 25 ++++++++++++++++++++ src/s2python/ombc/ombc_timer_status.py | 17 +++++++++++++ 6 files changed, 84 insertions(+), 1 deletion(-) create mode 100644 src/s2python/ombc/__init__.py diff --git a/src/s2python/ombc/__init__.py b/src/s2python/ombc/__init__.py new file mode 100644 index 0000000..32aa3c1 --- /dev/null +++ b/src/s2python/ombc/__init__.py @@ -0,0 +1,3 @@ +from s2python.ombc.ombc_instruction import OMBCInstruction +from s2python.ombc.ombc_status import OMBCStatus +from s2python.ombc.ombc_system_description import OMBCSystemDescription diff --git a/src/s2python/ombc/ombc_instruction.py b/src/s2python/ombc/ombc_instruction.py index dc4d760..8dd76b2 100644 --- a/src/s2python/ombc/ombc_instruction.py +++ b/src/s2python/ombc/ombc_instruction.py @@ -6,6 +6,7 @@ S2Message, ) + @catch_and_convert_exceptions class OMBCInstruction(GenOMBCInstruction, S2Message["OMBCInstruction"]): model_config = GenOMBCInstruction.model_config @@ -16,4 +17,3 @@ class OMBCInstruction(GenOMBCInstruction, S2Message["OMBCInstruction"]): abnormal_condition: bool = GenOMBCInstruction.model_fields["abnormal_condition"] # type: ignore[assignment] operation_mode_factor: float = GenOMBCInstruction.model_fields["operation_mode_factor"] # type: ignore[assignment] operation_mode_id: uuid.UUID = GenOMBCInstruction.model_fields["operation_mode_id"] # type: ignore[assignment] - diff --git a/src/s2python/ombc/ombc_operation_mode.py b/src/s2python/ombc/ombc_operation_mode.py index e69de29..75d3d9d 100644 --- a/src/s2python/ombc/ombc_operation_mode.py +++ b/src/s2python/ombc/ombc_operation_mode.py @@ -0,0 +1,21 @@ +from typing import List +import uuid + +from s2python.generated.gen_s2 import OMBCOperationMode as GenOMBCOperationMode +from s2python.common.power_range import PowerRange + + +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class OMBCOperationMode(GenOMBCOperationMode, S2Message["OMBCOperationMode"]): + model_config = GenOMBCOperationMode.model_config + model_config["validate_assignment"] = True + + id: uuid.UUID = GenOMBCOperationMode.model_fields["id"] # type: ignore[assignment] + power_ranges: List[PowerRange] = GenOMBCOperationMode.model_fields["power_ranges"] # type: ignore[assignment] + abnormal_condition_only: bool = GenOMBCOperationMode.model_fields["abnormal_condition_only"] # type: ignore[assignment] diff --git a/src/s2python/ombc/ombc_status.py b/src/s2python/ombc/ombc_status.py index e69de29..89b282a 100644 --- a/src/s2python/ombc/ombc_status.py +++ b/src/s2python/ombc/ombc_status.py @@ -0,0 +1,17 @@ +import uuid + +from s2python.generated.gen_s2 import OMBCStatus as GenOMBCStatus + +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class OMBCStatus(GenOMBCStatus, S2Message["OMBCStatus"]): + model_config = GenOMBCStatus.model_config + model_config["validate_assignment"] = True + + message_id: uuid.UUID = GenOMBCStatus.model_fields["message_id"] # type: ignore[assignment] + operation_mode_factor: float = GenOMBCStatus.model_fields["operation_mode_factor"] # type: ignore[assignment] diff --git a/src/s2python/ombc/ombc_system_description.py b/src/s2python/ombc/ombc_system_description.py index e69de29..aa9c69e 100644 --- a/src/s2python/ombc/ombc_system_description.py +++ b/src/s2python/ombc/ombc_system_description.py @@ -0,0 +1,25 @@ +from typing import List +import uuid + +from s2python.generated.gen_s2 import OMBCSystemDescription as GenOMBCSystemDescription +from s2python.ombc.ombc_operation_mode import OMBCOperationMode +from s2python.common.transition import Transition +from s2python.common.timer import Timer + +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class OMBCSystemDescription( + GenOMBCSystemDescription, S2Message["OMBCSystemDescription"] +): + model_config = GenOMBCSystemDescription.model_config + model_config["validate_assignment"] = True + + message_id: uuid.UUID = GenOMBCSystemDescription.model_fields["message_id"] # type: ignore[assignment] + operation_modes: List[OMBCOperationMode] = GenOMBCSystemDescription.model_fields["operation_modes"] # type: ignore[assignment] + transitions: List[Transition] = GenOMBCSystemDescription.model_fields["transitions"] # type: ignore[assignment] + timers: List[Timer] = GenOMBCSystemDescription.model_fields["timers"] # type: ignore[assignment] diff --git a/src/s2python/ombc/ombc_timer_status.py b/src/s2python/ombc/ombc_timer_status.py index e69de29..3fa35ed 100644 --- a/src/s2python/ombc/ombc_timer_status.py +++ b/src/s2python/ombc/ombc_timer_status.py @@ -0,0 +1,17 @@ +from uuid import UUID + +from s2python.generated.gen_s2 import OMBCTimerStatus as GenOMBCTimerStatus + +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class OMBCTimerStatus(GenOMBCTimerStatus, S2Message["OMBCTimerStatus"]): + model_config = GenOMBCTimerStatus.model_config + model_config["validate_assignment"] = True + + message_id: UUID = GenOMBCTimerStatus.model_fields["message_id"] # type: ignore[assignment] + timer_id: UUID = GenOMBCTimerStatus.model_fields["timer_id"] # type: ignore[assignment] From 5d528541bab9e7e764cedde50942f8f858e052d2 Mon Sep 17 00:00:00 2001 From: Vlad Iftime Date: Tue, 7 Jan 2025 23:15:15 +0100 Subject: [PATCH 03/14] fixed lines too long --- build/lib/s2python/__init__.py | 10 + build/lib/s2python/common/__init__.py | 32 + build/lib/s2python/common/duration.py | 22 + build/lib/s2python/common/handshake.py | 15 + .../lib/s2python/common/handshake_response.py | 15 + .../common/instruction_status_update.py | 18 + build/lib/s2python/common/number_range.py | 22 + build/lib/s2python/common/power_forecast.py | 18 + .../s2python/common/power_forecast_element.py | 20 + .../s2python/common/power_forecast_value.py | 11 + .../lib/s2python/common/power_measurement.py | 18 + build/lib/s2python/common/power_range.py | 22 + build/lib/s2python/common/power_value.py | 11 + build/lib/s2python/common/reception_status.py | 15 + .../common/resource_manager_details.py | 25 + build/lib/s2python/common/revoke_object.py | 16 + build/lib/s2python/common/role.py | 11 + .../s2python/common/select_control_type.py | 15 + build/lib/s2python/common/session_request.py | 15 + build/lib/s2python/common/support.py | 27 + build/lib/s2python/common/timer.py | 17 + build/lib/s2python/common/transition.py | 24 + build/lib/s2python/frbc/__init__.py | 17 + .../frbc/frbc_actuator_description.py | 143 ++ .../lib/s2python/frbc/frbc_actuator_status.py | 23 + .../frbc/frbc_fill_level_target_profile.py | 24 + .../frbc_fill_level_target_profile_element.py | 34 + build/lib/s2python/frbc/frbc_instruction.py | 18 + .../s2python/frbc/frbc_leakage_behaviour.py | 20 + .../frbc/frbc_leakage_behaviour_element.py | 30 + .../lib/s2python/frbc/frbc_operation_mode.py | 42 + .../frbc/frbc_operation_mode_element.py | 27 + .../s2python/frbc/frbc_storage_description.py | 18 + .../lib/s2python/frbc/frbc_storage_status.py | 15 + .../s2python/frbc/frbc_system_description.py | 22 + build/lib/s2python/frbc/frbc_timer_status.py | 17 + .../lib/s2python/frbc/frbc_usage_forecast.py | 18 + .../frbc/frbc_usage_forecast_element.py | 17 + build/lib/s2python/frbc/rm.py | 0 build/lib/s2python/generated/__init__.py | 0 build/lib/s2python/generated/gen_s2.py | 1611 +++++++++++++++++ build/lib/s2python/py.typed | 0 .../lib/s2python/reception_status_awaiter.py | 60 + build/lib/s2python/s2_connection.py | 526 ++++++ build/lib/s2python/s2_control_type.py | 56 + build/lib/s2python/s2_parser.py | 113 ++ build/lib/s2python/s2_validation_error.py | 13 + build/lib/s2python/utils.py | 8 + build/lib/s2python/validate_values_mixin.py | 70 + build/lib/s2python/version.py | 3 + src/s2python/ombc/ombc_operation_mode.py | 8 +- src/s2python/ombc/ombc_system_description.py | 4 +- 52 files changed, 3353 insertions(+), 3 deletions(-) create mode 100644 build/lib/s2python/__init__.py create mode 100644 build/lib/s2python/common/__init__.py create mode 100644 build/lib/s2python/common/duration.py create mode 100644 build/lib/s2python/common/handshake.py create mode 100644 build/lib/s2python/common/handshake_response.py create mode 100644 build/lib/s2python/common/instruction_status_update.py create mode 100644 build/lib/s2python/common/number_range.py create mode 100644 build/lib/s2python/common/power_forecast.py create mode 100644 build/lib/s2python/common/power_forecast_element.py create mode 100644 build/lib/s2python/common/power_forecast_value.py create mode 100644 build/lib/s2python/common/power_measurement.py create mode 100644 build/lib/s2python/common/power_range.py create mode 100644 build/lib/s2python/common/power_value.py create mode 100644 build/lib/s2python/common/reception_status.py create mode 100644 build/lib/s2python/common/resource_manager_details.py create mode 100644 build/lib/s2python/common/revoke_object.py create mode 100644 build/lib/s2python/common/role.py create mode 100644 build/lib/s2python/common/select_control_type.py create mode 100644 build/lib/s2python/common/session_request.py create mode 100644 build/lib/s2python/common/support.py create mode 100644 build/lib/s2python/common/timer.py create mode 100644 build/lib/s2python/common/transition.py create mode 100644 build/lib/s2python/frbc/__init__.py create mode 100644 build/lib/s2python/frbc/frbc_actuator_description.py create mode 100644 build/lib/s2python/frbc/frbc_actuator_status.py create mode 100644 build/lib/s2python/frbc/frbc_fill_level_target_profile.py create mode 100644 build/lib/s2python/frbc/frbc_fill_level_target_profile_element.py create mode 100644 build/lib/s2python/frbc/frbc_instruction.py create mode 100644 build/lib/s2python/frbc/frbc_leakage_behaviour.py create mode 100644 build/lib/s2python/frbc/frbc_leakage_behaviour_element.py create mode 100644 build/lib/s2python/frbc/frbc_operation_mode.py create mode 100644 build/lib/s2python/frbc/frbc_operation_mode_element.py create mode 100644 build/lib/s2python/frbc/frbc_storage_description.py create mode 100644 build/lib/s2python/frbc/frbc_storage_status.py create mode 100644 build/lib/s2python/frbc/frbc_system_description.py create mode 100644 build/lib/s2python/frbc/frbc_timer_status.py create mode 100644 build/lib/s2python/frbc/frbc_usage_forecast.py create mode 100644 build/lib/s2python/frbc/frbc_usage_forecast_element.py create mode 100644 build/lib/s2python/frbc/rm.py create mode 100644 build/lib/s2python/generated/__init__.py create mode 100644 build/lib/s2python/generated/gen_s2.py create mode 100644 build/lib/s2python/py.typed create mode 100644 build/lib/s2python/reception_status_awaiter.py create mode 100644 build/lib/s2python/s2_connection.py create mode 100644 build/lib/s2python/s2_control_type.py create mode 100644 build/lib/s2python/s2_parser.py create mode 100644 build/lib/s2python/s2_validation_error.py create mode 100644 build/lib/s2python/utils.py create mode 100644 build/lib/s2python/validate_values_mixin.py create mode 100644 build/lib/s2python/version.py diff --git a/build/lib/s2python/__init__.py b/build/lib/s2python/__init__.py new file mode 100644 index 0000000..0ab0a42 --- /dev/null +++ b/build/lib/s2python/__init__.py @@ -0,0 +1,10 @@ +from importlib.metadata import PackageNotFoundError, version # pragma: no cover + +try: + # Change here if project is renamed and does not equal the package name + dist_name = "s2-python" # pylint: disable=invalid-name + __version__ = version(dist_name) +except PackageNotFoundError: # pragma: no cover + __version__ = "unknown" +finally: + del version, PackageNotFoundError diff --git a/build/lib/s2python/common/__init__.py b/build/lib/s2python/common/__init__.py new file mode 100644 index 0000000..806de7e --- /dev/null +++ b/build/lib/s2python/common/__init__.py @@ -0,0 +1,32 @@ +from s2python.generated.gen_s2 import ( + RoleType, + Currency, + CommodityQuantity, + Commodity, + InstructionStatus, + ReceptionStatusValues, + EnergyManagementRole, + SessionRequestType, + ControlType, + RevokableObjects, +) + +from s2python.common.duration import Duration +from s2python.common.role import Role +from s2python.common.handshake import Handshake +from s2python.common.handshake_response import HandshakeResponse +from s2python.common.instruction_status_update import InstructionStatusUpdate +from s2python.common.number_range import NumberRange +from s2python.common.power_forecast_value import PowerForecastValue +from s2python.common.power_forecast_element import PowerForecastElement +from s2python.common.power_forecast import PowerForecast +from s2python.common.power_value import PowerValue +from s2python.common.power_measurement import PowerMeasurement +from s2python.common.power_range import PowerRange +from s2python.common.reception_status import ReceptionStatus +from s2python.common.resource_manager_details import ResourceManagerDetails +from s2python.common.revoke_object import RevokeObject +from s2python.common.select_control_type import SelectControlType +from s2python.common.session_request import SessionRequest +from s2python.common.timer import Timer +from s2python.common.transition import Transition diff --git a/build/lib/s2python/common/duration.py b/build/lib/s2python/common/duration.py new file mode 100644 index 0000000..65663c0 --- /dev/null +++ b/build/lib/s2python/common/duration.py @@ -0,0 +1,22 @@ +from datetime import timedelta +import math + +from s2python.generated.gen_s2 import Duration as GenDuration +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class Duration(GenDuration, S2Message["Duration"]): + def to_timedelta(self) -> timedelta: + return timedelta(milliseconds=self.root) + + @staticmethod + def from_timedelta(duration: timedelta) -> "Duration": + return Duration(root=math.ceil(duration.total_seconds() * 1000)) + + @staticmethod + def from_milliseconds(milliseconds: int) -> "Duration": + return Duration(root=milliseconds) diff --git a/build/lib/s2python/common/handshake.py b/build/lib/s2python/common/handshake.py new file mode 100644 index 0000000..c068150 --- /dev/null +++ b/build/lib/s2python/common/handshake.py @@ -0,0 +1,15 @@ +import uuid + +from s2python.generated.gen_s2 import Handshake as GenHandshake +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class Handshake(GenHandshake, S2Message["Handshake"]): + model_config = GenHandshake.model_config + model_config["validate_assignment"] = True + + message_id: uuid.UUID = GenHandshake.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/handshake_response.py b/build/lib/s2python/common/handshake_response.py new file mode 100644 index 0000000..fcc2eb5 --- /dev/null +++ b/build/lib/s2python/common/handshake_response.py @@ -0,0 +1,15 @@ +import uuid + +from s2python.generated.gen_s2 import HandshakeResponse as GenHandshakeResponse +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class HandshakeResponse(GenHandshakeResponse, S2Message["HandshakeResponse"]): + model_config = GenHandshakeResponse.model_config + model_config["validate_assignment"] = True + + message_id: uuid.UUID = GenHandshakeResponse.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/instruction_status_update.py b/build/lib/s2python/common/instruction_status_update.py new file mode 100644 index 0000000..5a8c45f --- /dev/null +++ b/build/lib/s2python/common/instruction_status_update.py @@ -0,0 +1,18 @@ +import uuid + +from s2python.generated.gen_s2 import ( + InstructionStatusUpdate as GenInstructionStatusUpdate, +) +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class InstructionStatusUpdate(GenInstructionStatusUpdate, S2Message["InstructionStatusUpdate"]): + model_config = GenInstructionStatusUpdate.model_config + model_config["validate_assignment"] = True + + message_id: uuid.UUID = GenInstructionStatusUpdate.model_fields["message_id"] # type: ignore[assignment] + instruction_id: uuid.UUID = GenInstructionStatusUpdate.model_fields["instruction_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/number_range.py b/build/lib/s2python/common/number_range.py new file mode 100644 index 0000000..070b74a --- /dev/null +++ b/build/lib/s2python/common/number_range.py @@ -0,0 +1,22 @@ +from typing import Any + +from s2python.validate_values_mixin import S2Message, catch_and_convert_exceptions +from s2python.generated.gen_s2 import NumberRange as GenNumberRange + + +@catch_and_convert_exceptions +class NumberRange(GenNumberRange, S2Message["NumberRange"]): + model_config = GenNumberRange.model_config + model_config["validate_assignment"] = True + + def __hash__(self) -> int: + return hash(f"{self.start_of_range}|{self.end_of_range}") + + def __eq__(self, other: Any) -> bool: + if isinstance(other, NumberRange): + return ( + self.start_of_range == other.start_of_range + and self.end_of_range == other.end_of_range + ) + + return False diff --git a/build/lib/s2python/common/power_forecast.py b/build/lib/s2python/common/power_forecast.py new file mode 100644 index 0000000..31c595d --- /dev/null +++ b/build/lib/s2python/common/power_forecast.py @@ -0,0 +1,18 @@ +from typing import List +import uuid + +from s2python.common.power_forecast_element import PowerForecastElement +from s2python.generated.gen_s2 import PowerForecast as GenPowerForecast +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class PowerForecast(GenPowerForecast, S2Message["PowerForecast"]): + model_config = GenPowerForecast.model_config + model_config["validate_assignment"] = True + + message_id: uuid.UUID = GenPowerForecast.model_fields["message_id"] # type: ignore[assignment] + elements: List[PowerForecastElement] = GenPowerForecast.model_fields["elements"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/power_forecast_element.py b/build/lib/s2python/common/power_forecast_element.py new file mode 100644 index 0000000..10460f7 --- /dev/null +++ b/build/lib/s2python/common/power_forecast_element.py @@ -0,0 +1,20 @@ +from typing import List + +from s2python.generated.gen_s2 import PowerForecastElement as GenPowerForecastElement +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) +from s2python.common.duration import Duration +from s2python.common.power_forecast_value import PowerForecastValue + + +@catch_and_convert_exceptions +class PowerForecastElement(GenPowerForecastElement, S2Message["PowerForecastElement"]): + model_config = GenPowerForecastElement.model_config + model_config["validate_assignment"] = True + + duration: Duration = GenPowerForecastElement.model_fields["duration"] # type: ignore[assignment] + power_values: List[PowerForecastValue] = GenPowerForecastElement.model_fields[ + "power_values" + ] # type: ignore[assignment] diff --git a/build/lib/s2python/common/power_forecast_value.py b/build/lib/s2python/common/power_forecast_value.py new file mode 100644 index 0000000..3ee2cc3 --- /dev/null +++ b/build/lib/s2python/common/power_forecast_value.py @@ -0,0 +1,11 @@ +from s2python.generated.gen_s2 import PowerForecastValue as GenPowerForecastValue +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class PowerForecastValue(GenPowerForecastValue, S2Message["PowerForecastValue"]): + model_config = GenPowerForecastValue.model_config + model_config["validate_assignment"] = True diff --git a/build/lib/s2python/common/power_measurement.py b/build/lib/s2python/common/power_measurement.py new file mode 100644 index 0000000..27896c9 --- /dev/null +++ b/build/lib/s2python/common/power_measurement.py @@ -0,0 +1,18 @@ +from typing import List +import uuid + +from s2python.common.power_value import PowerValue +from s2python.generated.gen_s2 import PowerMeasurement as GenPowerMeasurement +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class PowerMeasurement(GenPowerMeasurement, S2Message["PowerMeasurement"]): + model_config = GenPowerMeasurement.model_config + model_config["validate_assignment"] = True + + message_id: uuid.UUID = GenPowerMeasurement.model_fields["message_id"] # type: ignore[assignment] + values: List[PowerValue] = GenPowerMeasurement.model_fields["values"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/power_range.py b/build/lib/s2python/common/power_range.py new file mode 100644 index 0000000..4ca1ec8 --- /dev/null +++ b/build/lib/s2python/common/power_range.py @@ -0,0 +1,22 @@ +from typing_extensions import Self + +from pydantic import model_validator + +from s2python.generated.gen_s2 import PowerRange as GenPowerRange +from s2python.validate_values_mixin import ( + S2Message, + catch_and_convert_exceptions, +) + + +@catch_and_convert_exceptions +class PowerRange(GenPowerRange, S2Message["PowerRange"]): + model_config = GenPowerRange.model_config + model_config["validate_assignment"] = True + + @model_validator(mode="after") + def validate_start_end_order(self) -> Self: + if self.start_of_range > self.end_of_range: + raise ValueError(self, "start_of_range should not be higher than end_of_range") + + return self diff --git a/build/lib/s2python/common/power_value.py b/build/lib/s2python/common/power_value.py new file mode 100644 index 0000000..c623627 --- /dev/null +++ b/build/lib/s2python/common/power_value.py @@ -0,0 +1,11 @@ +from s2python.generated.gen_s2 import PowerValue as GenPowerValue +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class PowerValue(GenPowerValue, S2Message["PowerValue"]): + model_config = GenPowerValue.model_config + model_config["validate_assignment"] = True diff --git a/build/lib/s2python/common/reception_status.py b/build/lib/s2python/common/reception_status.py new file mode 100644 index 0000000..a759897 --- /dev/null +++ b/build/lib/s2python/common/reception_status.py @@ -0,0 +1,15 @@ +import uuid + +from s2python.generated.gen_s2 import ReceptionStatus as GenReceptionStatus +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class ReceptionStatus(GenReceptionStatus, S2Message["ReceptionStatus"]): + model_config = GenReceptionStatus.model_config + model_config["validate_assignment"] = True + + subject_message_id: uuid.UUID = GenReceptionStatus.model_fields["subject_message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/resource_manager_details.py b/build/lib/s2python/common/resource_manager_details.py new file mode 100644 index 0000000..82ce844 --- /dev/null +++ b/build/lib/s2python/common/resource_manager_details.py @@ -0,0 +1,25 @@ +from typing import List +import uuid + +from s2python.common.duration import Duration +from s2python.common.role import Role +from s2python.generated.gen_s2 import ( + ResourceManagerDetails as GenResourceManagerDetails, +) +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class ResourceManagerDetails(GenResourceManagerDetails, S2Message["ResourceManagerDetails"]): + model_config = GenResourceManagerDetails.model_config + model_config["validate_assignment"] = True + + instruction_processing_delay: Duration = GenResourceManagerDetails.model_fields[ + "instruction_processing_delay" + ] # type: ignore[assignment] + message_id: uuid.UUID = GenResourceManagerDetails.model_fields["message_id"] # type: ignore[assignment] + resource_id: uuid.UUID = GenResourceManagerDetails.model_fields["resource_id"] # type: ignore[assignment] + roles: List[Role] = GenResourceManagerDetails.model_fields["roles"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/revoke_object.py b/build/lib/s2python/common/revoke_object.py new file mode 100644 index 0000000..d133c79 --- /dev/null +++ b/build/lib/s2python/common/revoke_object.py @@ -0,0 +1,16 @@ +import uuid + +from s2python.generated.gen_s2 import RevokeObject as GenRevokeObject +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class RevokeObject(GenRevokeObject, S2Message["RevokeObject"]): + model_config = GenRevokeObject.model_config + model_config["validate_assignment"] = True + + message_id: uuid.UUID = GenRevokeObject.model_fields["message_id"] # type: ignore[assignment] + object_id: uuid.UUID = GenRevokeObject.model_fields["object_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/role.py b/build/lib/s2python/common/role.py new file mode 100644 index 0000000..4a3d3ef --- /dev/null +++ b/build/lib/s2python/common/role.py @@ -0,0 +1,11 @@ +from s2python.generated.gen_s2 import Role as GenRole +from s2python.validate_values_mixin import ( + S2Message, + catch_and_convert_exceptions, +) + + +@catch_and_convert_exceptions +class Role(GenRole, S2Message["Role"]): + model_config = GenRole.model_config + model_config["validate_assignment"] = True diff --git a/build/lib/s2python/common/select_control_type.py b/build/lib/s2python/common/select_control_type.py new file mode 100644 index 0000000..5f02954 --- /dev/null +++ b/build/lib/s2python/common/select_control_type.py @@ -0,0 +1,15 @@ +import uuid + +from s2python.generated.gen_s2 import SelectControlType as GenSelectControlType +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class SelectControlType(GenSelectControlType, S2Message["SelectControlType"]): + model_config = GenSelectControlType.model_config + model_config["validate_assignment"] = True + + message_id: uuid.UUID = GenSelectControlType.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/session_request.py b/build/lib/s2python/common/session_request.py new file mode 100644 index 0000000..f962427 --- /dev/null +++ b/build/lib/s2python/common/session_request.py @@ -0,0 +1,15 @@ +import uuid + +from s2python.generated.gen_s2 import SessionRequest as GenSessionRequest +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class SessionRequest(GenSessionRequest, S2Message["SessionRequest"]): + model_config = GenSessionRequest.model_config + model_config["validate_assignment"] = True + + message_id: uuid.UUID = GenSessionRequest.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/support.py b/build/lib/s2python/common/support.py new file mode 100644 index 0000000..027f65b --- /dev/null +++ b/build/lib/s2python/common/support.py @@ -0,0 +1,27 @@ +from s2python.common import CommodityQuantity, Commodity + + +def commodity_has_quantity(commodity: "Commodity", quantity: CommodityQuantity) -> bool: + if commodity == Commodity.HEAT: + result = quantity in [ + CommodityQuantity.HEAT_THERMAL_POWER, + CommodityQuantity.HEAT_TEMPERATURE, + CommodityQuantity.HEAT_FLOW_RATE, + ] + elif commodity == Commodity.ELECTRICITY: + result = quantity in [ + CommodityQuantity.ELECTRIC_POWER_3_PHASE_SYMMETRIC, + CommodityQuantity.ELECTRIC_POWER_L1, + CommodityQuantity.ELECTRIC_POWER_L2, + CommodityQuantity.ELECTRIC_POWER_L3, + ] + elif commodity == Commodity.GAS: + result = quantity in [CommodityQuantity.NATURAL_GAS_FLOW_RATE] + elif commodity == Commodity.OIL: + result = quantity in [CommodityQuantity.OIL_FLOW_RATE] + else: + raise RuntimeError( + f"Unsupported commodity {commodity}. Missing implementation." + ) + + return result diff --git a/build/lib/s2python/common/timer.py b/build/lib/s2python/common/timer.py new file mode 100644 index 0000000..3811082 --- /dev/null +++ b/build/lib/s2python/common/timer.py @@ -0,0 +1,17 @@ +import uuid + +from s2python.common.duration import Duration +from s2python.generated.gen_s2 import Timer as GenTimer +from s2python.validate_values_mixin import ( + S2Message, + catch_and_convert_exceptions, +) + + +@catch_and_convert_exceptions +class Timer(GenTimer, S2Message["Timer"]): + model_config = GenTimer.model_config + model_config["validate_assignment"] = True + + id: uuid.UUID = GenTimer.model_fields["id"] # type: ignore[assignment] + duration: Duration = GenTimer.model_fields["duration"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/transition.py b/build/lib/s2python/common/transition.py new file mode 100644 index 0000000..e1e1a25 --- /dev/null +++ b/build/lib/s2python/common/transition.py @@ -0,0 +1,24 @@ +import uuid +from typing import Optional, List + +from s2python.common.duration import Duration +from s2python.generated.gen_s2 import Transition as GenTransition +from s2python.validate_values_mixin import ( + S2Message, + catch_and_convert_exceptions, +) + + +@catch_and_convert_exceptions +class Transition(GenTransition, S2Message["Transition"]): + model_config = GenTransition.model_config + model_config["validate_assignment"] = True + + id: uuid.UUID = GenTransition.model_fields["id"] # type: ignore[assignment] + from_: uuid.UUID = GenTransition.model_fields["from_"] # type: ignore[assignment] + to: uuid.UUID = GenTransition.model_fields["to"] # type: ignore[assignment] + start_timers: List[uuid.UUID] = GenTransition.model_fields["start_timers"] # type: ignore[assignment] + blocking_timers: List[uuid.UUID] = GenTransition.model_fields["blocking_timers"] # type: ignore[assignment] + transition_duration: Optional[Duration] = GenTransition.model_fields[ + "transition_duration" + ] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/__init__.py b/build/lib/s2python/frbc/__init__.py new file mode 100644 index 0000000..da3d5bc --- /dev/null +++ b/build/lib/s2python/frbc/__init__.py @@ -0,0 +1,17 @@ +from s2python.frbc.frbc_fill_level_target_profile_element import ( + FRBCFillLevelTargetProfileElement, +) +from s2python.frbc.frbc_fill_level_target_profile import FRBCFillLevelTargetProfile +from s2python.frbc.frbc_instruction import FRBCInstruction +from s2python.frbc.frbc_leakage_behaviour_element import FRBCLeakageBehaviourElement +from s2python.frbc.frbc_leakage_behaviour import FRBCLeakageBehaviour +from s2python.frbc.frbc_usage_forecast_element import FRBCUsageForecastElement +from s2python.frbc.frbc_usage_forecast import FRBCUsageForecast +from s2python.frbc.frbc_operation_mode_element import FRBCOperationModeElement +from s2python.frbc.frbc_operation_mode import FRBCOperationMode +from s2python.frbc.frbc_actuator_description import FRBCActuatorDescription +from s2python.frbc.frbc_actuator_status import FRBCActuatorStatus +from s2python.frbc.frbc_storage_description import FRBCStorageDescription +from s2python.frbc.frbc_storage_status import FRBCStorageStatus +from s2python.frbc.frbc_system_description import FRBCSystemDescription +from s2python.frbc.frbc_timer_status import FRBCTimerStatus diff --git a/build/lib/s2python/frbc/frbc_actuator_description.py b/build/lib/s2python/frbc/frbc_actuator_description.py new file mode 100644 index 0000000..08afce6 --- /dev/null +++ b/build/lib/s2python/frbc/frbc_actuator_description.py @@ -0,0 +1,143 @@ +import uuid + +from typing import List +from typing_extensions import Self + +from pydantic import model_validator + +from s2python.common import Transition, Timer, Commodity +from s2python.common.support import commodity_has_quantity +from s2python.frbc.frbc_operation_mode import FRBCOperationMode +from s2python.generated.gen_s2 import ( + FRBCActuatorDescription as GenFRBCActuatorDescription, +) +from s2python.validate_values_mixin import ( + S2Message, + catch_and_convert_exceptions, +) + + +@catch_and_convert_exceptions +class FRBCActuatorDescription(GenFRBCActuatorDescription, S2Message["FRBCActuatorDescription"]): + model_config = GenFRBCActuatorDescription.model_config + model_config["validate_assignment"] = True + + id: uuid.UUID = GenFRBCActuatorDescription.model_fields["id"] # type: ignore[assignment] + operation_modes: List[FRBCOperationMode] = GenFRBCActuatorDescription.model_fields[ + "operation_modes" + ] # type: ignore[assignment] + transitions: List[Transition] = GenFRBCActuatorDescription.model_fields["transitions"] # type: ignore[assignment] + timers: List[Timer] = GenFRBCActuatorDescription.model_fields["timers"] # type: ignore[assignment] + supported_commodities: List[Commodity] = GenFRBCActuatorDescription.model_fields[ + "supported_commodities" + ] # type: ignore[assignment] + + @model_validator(mode="after") + def validate_timers_in_transitions(self) -> Self: + timers_by_id = {timer.id: timer for timer in self.timers} + transition: Transition + for transition in self.transitions: + for start_timer_id in transition.start_timers: + if start_timer_id not in timers_by_id: + raise ValueError( + self, + f"{start_timer_id} was referenced as start timer in transition " + f"{transition.id} but was not defined in 'timers'.", + ) + + for blocking_timer_id in transition.blocking_timers: + if blocking_timer_id not in timers_by_id: + raise ValueError( + self, + f"{blocking_timer_id} was referenced as blocking timer in transition " + f"{transition.id} but was not defined in 'timers'.", + ) + + return self + + @model_validator(mode="after") + def validate_timers_unique_ids(self) -> Self: + ids = [] + timer: Timer + for timer in self.timers: + if timer.id in ids: + raise ValueError(self, f"Id {timer.id} was found multiple times in 'timers'.") + ids.append(timer.id) + + return self + + @model_validator(mode="after") + def validate_operation_modes_in_transitions(self) -> Self: + operation_mode_by_id = {operation_mode.id: operation_mode for operation_mode in self.operation_modes} + transition: Transition + for transition in self.transitions: + if transition.from_ not in operation_mode_by_id: + raise ValueError( + self, + f"Operation mode {transition.from_} was referenced as 'from' in transition " + f"{transition.id} but was not defined in 'operation_modes'.", + ) + + if transition.to not in operation_mode_by_id: + raise ValueError( + self, + f"Operation mode {transition.to} was referenced as 'to' in transition " + f"{transition.id} but was not defined in 'operation_modes'.", + ) + + return self + + @model_validator(mode="after") + def validate_operation_modes_unique_ids(self) -> Self: + ids = [] + operation_mode: FRBCOperationMode + for operation_mode in self.operation_modes: + if operation_mode.id in ids: + raise ValueError( + self, + f"Id {operation_mode.id} was found multiple times in 'operation_modes'.", + ) + ids.append(operation_mode.id) + + return self + + @model_validator(mode="after") + def validate_operation_mode_elements_have_all_supported_commodities(self) -> Self: + supported_commodities = self.supported_commodities + operation_mode: FRBCOperationMode + for operation_mode in self.operation_modes: + for operation_mode_element in operation_mode.elements: + for commodity in supported_commodities: + power_ranges_for_commodity = [ + power_range + for power_range in operation_mode_element.power_ranges + if commodity_has_quantity(commodity, power_range.commodity_quantity) + ] + + if len(power_ranges_for_commodity) > 1: + raise ValueError( + self, + f"Multiple power ranges defined for commodity {commodity} in operation " + f"mode {operation_mode.id} and element with fill_level_range " + f"{operation_mode_element.fill_level_range}", + ) + if not power_ranges_for_commodity: + raise ValueError( + self, + f"No power ranges defined for commodity {commodity} in operation " + f"mode {operation_mode.id} and element with fill_level_range " + f"{operation_mode_element.fill_level_range}", + ) + return self + + @model_validator(mode="after") + def validate_unique_supported_commodities(self) -> Self: + supported_commodities: List[Commodity] = self.supported_commodities + + for supported_commodity in supported_commodities: + if supported_commodities.count(supported_commodity) > 1: + raise ValueError( + self, + f"Found duplicate {supported_commodity} commodity in 'supported_commodities'", + ) + return self diff --git a/build/lib/s2python/frbc/frbc_actuator_status.py b/build/lib/s2python/frbc/frbc_actuator_status.py new file mode 100644 index 0000000..585a23d --- /dev/null +++ b/build/lib/s2python/frbc/frbc_actuator_status.py @@ -0,0 +1,23 @@ +from typing import Optional +import uuid + +from s2python.generated.gen_s2 import FRBCActuatorStatus as GenFRBCActuatorStatus +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class FRBCActuatorStatus(GenFRBCActuatorStatus, S2Message["FRBCActuatorStatus"]): + model_config = GenFRBCActuatorStatus.model_config + model_config["validate_assignment"] = True + + active_operation_mode_id: uuid.UUID = GenFRBCActuatorStatus.model_fields[ + "active_operation_mode_id" + ] # type: ignore[assignment] + actuator_id: uuid.UUID = GenFRBCActuatorStatus.model_fields["actuator_id"] # type: ignore[assignment] + message_id: uuid.UUID = GenFRBCActuatorStatus.model_fields["message_id"] # type: ignore[assignment] + previous_operation_mode_id: Optional[uuid.UUID] = GenFRBCActuatorStatus.model_fields[ + "previous_operation_mode_id" + ] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_fill_level_target_profile.py b/build/lib/s2python/frbc/frbc_fill_level_target_profile.py new file mode 100644 index 0000000..38ef83b --- /dev/null +++ b/build/lib/s2python/frbc/frbc_fill_level_target_profile.py @@ -0,0 +1,24 @@ +from typing import List +import uuid + +from s2python.frbc.frbc_fill_level_target_profile_element import ( + FRBCFillLevelTargetProfileElement, +) +from s2python.generated.gen_s2 import ( + FRBCFillLevelTargetProfile as GenFRBCFillLevelTargetProfile, +) +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class FRBCFillLevelTargetProfile(GenFRBCFillLevelTargetProfile, S2Message["FRBCFillLevelTargetProfile"]): + model_config = GenFRBCFillLevelTargetProfile.model_config + model_config["validate_assignment"] = True + + elements: List[FRBCFillLevelTargetProfileElement] = GenFRBCFillLevelTargetProfile.model_fields[ + "elements" + ] # type: ignore[assignment] + message_id: uuid.UUID = GenFRBCFillLevelTargetProfile.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_fill_level_target_profile_element.py b/build/lib/s2python/frbc/frbc_fill_level_target_profile_element.py new file mode 100644 index 0000000..cdb7d84 --- /dev/null +++ b/build/lib/s2python/frbc/frbc_fill_level_target_profile_element.py @@ -0,0 +1,34 @@ +# pylint: disable=duplicate-code + +from typing_extensions import Self + +from pydantic import model_validator + +from s2python.common import Duration, NumberRange +from s2python.generated.gen_s2 import ( + FRBCFillLevelTargetProfileElement as GenFRBCFillLevelTargetProfileElement, +) +from s2python.validate_values_mixin import catch_and_convert_exceptions, S2Message + + +@catch_and_convert_exceptions +class FRBCFillLevelTargetProfileElement( + GenFRBCFillLevelTargetProfileElement, S2Message["FRBCFillLevelTargetProfileElement"] +): + model_config = GenFRBCFillLevelTargetProfileElement.model_config + model_config["validate_assignment"] = True + + duration: Duration = GenFRBCFillLevelTargetProfileElement.model_fields["duration"] # type: ignore[assignment] + fill_level_range: NumberRange = GenFRBCFillLevelTargetProfileElement.model_fields[ + "fill_level_range" + ] # type: ignore[assignment] + + @model_validator(mode="after") + def validate_start_end_order(self) -> Self: + if self.fill_level_range.start_of_range > self.fill_level_range.end_of_range: + raise ValueError( + self, + "start_of_range should not be higher than end_of_range for the fill_level_range", + ) + + return self diff --git a/build/lib/s2python/frbc/frbc_instruction.py b/build/lib/s2python/frbc/frbc_instruction.py new file mode 100644 index 0000000..584cfba --- /dev/null +++ b/build/lib/s2python/frbc/frbc_instruction.py @@ -0,0 +1,18 @@ +import uuid + +from s2python.generated.gen_s2 import FRBCInstruction as GenFRBCInstruction +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class FRBCInstruction(GenFRBCInstruction, S2Message["FRBCInstruction"]): + model_config = GenFRBCInstruction.model_config + model_config["validate_assignment"] = True + + actuator_id: uuid.UUID = GenFRBCInstruction.model_fields["actuator_id"] # type: ignore[assignment] + id: uuid.UUID = GenFRBCInstruction.model_fields["id"] # type: ignore[assignment] + message_id: uuid.UUID = GenFRBCInstruction.model_fields["message_id"] # type: ignore[assignment] + operation_mode: uuid.UUID = GenFRBCInstruction.model_fields["operation_mode"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_leakage_behaviour.py b/build/lib/s2python/frbc/frbc_leakage_behaviour.py new file mode 100644 index 0000000..fda7d3b --- /dev/null +++ b/build/lib/s2python/frbc/frbc_leakage_behaviour.py @@ -0,0 +1,20 @@ +from typing import List +import uuid + +from s2python.frbc.frbc_leakage_behaviour_element import FRBCLeakageBehaviourElement +from s2python.generated.gen_s2 import FRBCLeakageBehaviour as GenFRBCLeakageBehaviour +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class FRBCLeakageBehaviour(GenFRBCLeakageBehaviour, S2Message["FRBCLeakageBehaviour"]): + model_config = GenFRBCLeakageBehaviour.model_config + model_config["validate_assignment"] = True + + elements: List[FRBCLeakageBehaviourElement] = GenFRBCLeakageBehaviour.model_fields[ + "elements" + ] # type: ignore[assignment] + message_id: uuid.UUID = GenFRBCLeakageBehaviour.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_leakage_behaviour_element.py b/build/lib/s2python/frbc/frbc_leakage_behaviour_element.py new file mode 100644 index 0000000..b9ca2eb --- /dev/null +++ b/build/lib/s2python/frbc/frbc_leakage_behaviour_element.py @@ -0,0 +1,30 @@ +# pylint: disable=duplicate-code + +from pydantic import model_validator +from typing_extensions import Self + +from s2python.common import NumberRange +from s2python.generated.gen_s2 import FRBCLeakageBehaviourElement as GenFRBCLeakageBehaviourElement +from s2python.validate_values_mixin import catch_and_convert_exceptions, S2Message + + +@catch_and_convert_exceptions +class FRBCLeakageBehaviourElement( + GenFRBCLeakageBehaviourElement, S2Message["FRBCLeakageBehaviourElement"] +): + model_config = GenFRBCLeakageBehaviourElement.model_config + model_config["validate_assignment"] = True + + fill_level_range: NumberRange = GenFRBCLeakageBehaviourElement.model_fields[ + "fill_level_range" + ] # type: ignore[assignment] + + @model_validator(mode="after") + def validate_start_end_order(self) -> Self: + if self.fill_level_range.start_of_range > self.fill_level_range.end_of_range: + raise ValueError( + self, + "start_of_range should not be higher than end_of_range for the fill_level_range", + ) + + return self diff --git a/build/lib/s2python/frbc/frbc_operation_mode.py b/build/lib/s2python/frbc/frbc_operation_mode.py new file mode 100644 index 0000000..c6758ad --- /dev/null +++ b/build/lib/s2python/frbc/frbc_operation_mode.py @@ -0,0 +1,42 @@ +# from itertools import pairwise +import uuid +from typing import List, Dict +from typing_extensions import Self + +from pydantic import model_validator + +from s2python.common import NumberRange +from s2python.frbc.frbc_operation_mode_element import FRBCOperationModeElement +from s2python.generated.gen_s2 import FRBCOperationMode as GenFRBCOperationMode +from s2python.validate_values_mixin import ( + S2Message, + catch_and_convert_exceptions, +) +from s2python.utils import pairwise + + +@catch_and_convert_exceptions +class FRBCOperationMode(GenFRBCOperationMode, S2Message["FRBCOperationMode"]): + model_config = GenFRBCOperationMode.model_config + model_config["validate_assignment"] = True + + id: uuid.UUID = GenFRBCOperationMode.model_fields["id"] # type: ignore[assignment] + elements: List[FRBCOperationModeElement] = GenFRBCOperationMode.model_fields["elements"] # type: ignore[assignment] + + @model_validator(mode="after") + def validate_contiguous_fill_levels_operation_mode_elements(self) -> Self: + elements_by_fill_level_range: Dict[NumberRange, FRBCOperationModeElement] + elements_by_fill_level_range = {element.fill_level_range: element for element in self.elements} + + sorted_fill_level_ranges: List[NumberRange] + sorted_fill_level_ranges = list(elements_by_fill_level_range.keys()) + sorted_fill_level_ranges.sort(key=lambda r: r.start_of_range) + + for current_fill_level_range, next_fill_level_range in pairwise(sorted_fill_level_ranges): + if current_fill_level_range.end_of_range != next_fill_level_range.start_of_range: + raise ValueError( + self, + f"Elements with fill level ranges {current_fill_level_range} and " + f"{next_fill_level_range} are closest match to each other but not contiguous.", + ) + return self diff --git a/build/lib/s2python/frbc/frbc_operation_mode_element.py b/build/lib/s2python/frbc/frbc_operation_mode_element.py new file mode 100644 index 0000000..d154d11 --- /dev/null +++ b/build/lib/s2python/frbc/frbc_operation_mode_element.py @@ -0,0 +1,27 @@ +from typing import Optional, List + +from s2python.common import NumberRange, PowerRange +from s2python.generated.gen_s2 import ( + FRBCOperationModeElement as GenFRBCOperationModeElement, +) +from s2python.validate_values_mixin import ( + S2Message, + catch_and_convert_exceptions, +) + + +@catch_and_convert_exceptions +class FRBCOperationModeElement(GenFRBCOperationModeElement, S2Message["FRBCOperationModeElement"]): + model_config = GenFRBCOperationModeElement.model_config + model_config["validate_assignment"] = True + + fill_level_range: NumberRange = GenFRBCOperationModeElement.model_fields[ + "fill_level_range" + ] # type: ignore[assignment] + fill_rate: NumberRange = GenFRBCOperationModeElement.model_fields["fill_rate"] # type: ignore[assignment] + power_ranges: List[PowerRange] = GenFRBCOperationModeElement.model_fields[ + "power_ranges" + ] # type: ignore[assignment] + running_costs: Optional[NumberRange] = GenFRBCOperationModeElement.model_fields[ + "running_costs" + ] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_storage_description.py b/build/lib/s2python/frbc/frbc_storage_description.py new file mode 100644 index 0000000..eb141b8 --- /dev/null +++ b/build/lib/s2python/frbc/frbc_storage_description.py @@ -0,0 +1,18 @@ +from s2python.common import NumberRange +from s2python.generated.gen_s2 import ( + FRBCStorageDescription as GenFRBCStorageDescription, +) +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class FRBCStorageDescription(GenFRBCStorageDescription, S2Message["FRBCStorageDescription"]): + model_config = GenFRBCStorageDescription.model_config + model_config["validate_assignment"] = True + + fill_level_range: NumberRange = GenFRBCStorageDescription.model_fields[ + "fill_level_range" + ] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_storage_status.py b/build/lib/s2python/frbc/frbc_storage_status.py new file mode 100644 index 0000000..7940b79 --- /dev/null +++ b/build/lib/s2python/frbc/frbc_storage_status.py @@ -0,0 +1,15 @@ +import uuid + +from s2python.generated.gen_s2 import FRBCStorageStatus as GenFRBCStorageStatus +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class FRBCStorageStatus(GenFRBCStorageStatus, S2Message["FRBCStorageStatus"]): + model_config = GenFRBCStorageStatus.model_config + model_config["validate_assignment"] = True + + message_id: uuid.UUID = GenFRBCStorageStatus.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_system_description.py b/build/lib/s2python/frbc/frbc_system_description.py new file mode 100644 index 0000000..2eb5899 --- /dev/null +++ b/build/lib/s2python/frbc/frbc_system_description.py @@ -0,0 +1,22 @@ +from typing import List +import uuid + +from s2python.generated.gen_s2 import FRBCSystemDescription as GenFRBCSystemDescription +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) +from s2python.frbc.frbc_actuator_description import FRBCActuatorDescription +from s2python.frbc.frbc_storage_description import FRBCStorageDescription + + +@catch_and_convert_exceptions +class FRBCSystemDescription(GenFRBCSystemDescription, S2Message["FRBCSystemDescription"]): + model_config = GenFRBCSystemDescription.model_config + model_config["validate_assignment"] = True + + actuators: List[FRBCActuatorDescription] = GenFRBCSystemDescription.model_fields[ + "actuators" + ] # type: ignore[assignment] + message_id: uuid.UUID = GenFRBCSystemDescription.model_fields["message_id"] # type: ignore[assignment] + storage: FRBCStorageDescription = GenFRBCSystemDescription.model_fields["storage"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_timer_status.py b/build/lib/s2python/frbc/frbc_timer_status.py new file mode 100644 index 0000000..80c86d6 --- /dev/null +++ b/build/lib/s2python/frbc/frbc_timer_status.py @@ -0,0 +1,17 @@ +import uuid + +from s2python.generated.gen_s2 import FRBCTimerStatus as GenFRBCTimerStatus +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class FRBCTimerStatus(GenFRBCTimerStatus, S2Message["FRBCTimerStatus"]): + model_config = GenFRBCTimerStatus.model_config + model_config["validate_assignment"] = True + + actuator_id: uuid.UUID = GenFRBCTimerStatus.model_fields["actuator_id"] # type: ignore[assignment] + message_id: uuid.UUID = GenFRBCTimerStatus.model_fields["message_id"] # type: ignore[assignment] + timer_id: uuid.UUID = GenFRBCTimerStatus.model_fields["timer_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_usage_forecast.py b/build/lib/s2python/frbc/frbc_usage_forecast.py new file mode 100644 index 0000000..f71fda4 --- /dev/null +++ b/build/lib/s2python/frbc/frbc_usage_forecast.py @@ -0,0 +1,18 @@ +from typing import List +import uuid + +from s2python.generated.gen_s2 import FRBCUsageForecast as GenFRBCUsageForecast +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) +from s2python.frbc.frbc_usage_forecast_element import FRBCUsageForecastElement + + +@catch_and_convert_exceptions +class FRBCUsageForecast(GenFRBCUsageForecast, S2Message["FRBCUsageForecast"]): + model_config = GenFRBCUsageForecast.model_config + model_config["validate_assignment"] = True + + elements: List[FRBCUsageForecastElement] = GenFRBCUsageForecast.model_fields["elements"] # type: ignore[assignment] + message_id: uuid.UUID = GenFRBCUsageForecast.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_usage_forecast_element.py b/build/lib/s2python/frbc/frbc_usage_forecast_element.py new file mode 100644 index 0000000..370c04e --- /dev/null +++ b/build/lib/s2python/frbc/frbc_usage_forecast_element.py @@ -0,0 +1,17 @@ +from s2python.common import Duration + +from s2python.generated.gen_s2 import ( + FRBCUsageForecastElement as GenFRBCUsageForecastElement, +) +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2Message, +) + + +@catch_and_convert_exceptions +class FRBCUsageForecastElement(GenFRBCUsageForecastElement, S2Message["FRBCUsageForecastElement"]): + model_config = GenFRBCUsageForecastElement.model_config + model_config["validate_assignment"] = True + + duration: Duration = GenFRBCUsageForecastElement.model_fields["duration"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/rm.py b/build/lib/s2python/frbc/rm.py new file mode 100644 index 0000000..e69de29 diff --git a/build/lib/s2python/generated/__init__.py b/build/lib/s2python/generated/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/build/lib/s2python/generated/gen_s2.py b/build/lib/s2python/generated/gen_s2.py new file mode 100644 index 0000000..fbdc15d --- /dev/null +++ b/build/lib/s2python/generated/gen_s2.py @@ -0,0 +1,1611 @@ +# generated by datamodel-codegen: +# filename: openapi.yml +# timestamp: 2024-07-29T10:18:52+00:00 + +from __future__ import annotations + +from enum import Enum +from typing import List, Optional + +from pydantic import ( + AwareDatetime, + BaseModel, + ConfigDict, + Field, + RootModel, + conint, + constr, +) +from typing_extensions import Literal + + +class Duration(RootModel[conint(ge=0)]): + root: conint(ge=0) = Field(..., description='Duration in milliseconds') + + +class ID(RootModel[constr(pattern=r'[a-zA-Z0-9\-_:]{2,64}')]): + root: constr(pattern=r'[a-zA-Z0-9\-_:]{2,64}') = Field(..., description='UUID') + + +class Currency(Enum): + AED = 'AED' + ANG = 'ANG' + AUD = 'AUD' + CHE = 'CHE' + CHF = 'CHF' + CHW = 'CHW' + EUR = 'EUR' + GBP = 'GBP' + LBP = 'LBP' + LKR = 'LKR' + LRD = 'LRD' + LSL = 'LSL' + LYD = 'LYD' + MAD = 'MAD' + MDL = 'MDL' + MGA = 'MGA' + MKD = 'MKD' + MMK = 'MMK' + MNT = 'MNT' + MOP = 'MOP' + MRO = 'MRO' + MUR = 'MUR' + MVR = 'MVR' + MWK = 'MWK' + MXN = 'MXN' + MXV = 'MXV' + MYR = 'MYR' + MZN = 'MZN' + NAD = 'NAD' + NGN = 'NGN' + NIO = 'NIO' + NOK = 'NOK' + NPR = 'NPR' + NZD = 'NZD' + OMR = 'OMR' + PAB = 'PAB' + PEN = 'PEN' + PGK = 'PGK' + PHP = 'PHP' + PKR = 'PKR' + PLN = 'PLN' + PYG = 'PYG' + QAR = 'QAR' + RON = 'RON' + RSD = 'RSD' + RUB = 'RUB' + RWF = 'RWF' + SAR = 'SAR' + SBD = 'SBD' + SCR = 'SCR' + SDG = 'SDG' + SEK = 'SEK' + SGD = 'SGD' + SHP = 'SHP' + SLL = 'SLL' + SOS = 'SOS' + SRD = 'SRD' + SSP = 'SSP' + STD = 'STD' + SYP = 'SYP' + SZL = 'SZL' + THB = 'THB' + TJS = 'TJS' + TMT = 'TMT' + TND = 'TND' + TOP = 'TOP' + TRY = 'TRY' + TTD = 'TTD' + TWD = 'TWD' + TZS = 'TZS' + UAH = 'UAH' + UGX = 'UGX' + USD = 'USD' + USN = 'USN' + UYI = 'UYI' + UYU = 'UYU' + UZS = 'UZS' + VEF = 'VEF' + VND = 'VND' + VUV = 'VUV' + WST = 'WST' + XAG = 'XAG' + XAU = 'XAU' + XBA = 'XBA' + XBB = 'XBB' + XBC = 'XBC' + XBD = 'XBD' + XCD = 'XCD' + XOF = 'XOF' + XPD = 'XPD' + XPF = 'XPF' + XPT = 'XPT' + XSU = 'XSU' + XTS = 'XTS' + XUA = 'XUA' + XXX = 'XXX' + YER = 'YER' + ZAR = 'ZAR' + ZMW = 'ZMW' + ZWL = 'ZWL' + + +class SessionRequestType(Enum): + RECONNECT = 'RECONNECT' + TERMINATE = 'TERMINATE' + + +class RevokableObjects(Enum): + PEBC_PowerConstraints = 'PEBC.PowerConstraints' + PEBC_EnergyConstraint = 'PEBC.EnergyConstraint' + PEBC_Instruction = 'PEBC.Instruction' + PPBC_PowerProfileDefinition = 'PPBC.PowerProfileDefinition' + PPBC_ScheduleInstruction = 'PPBC.ScheduleInstruction' + PPBC_StartInterruptionInstruction = 'PPBC.StartInterruptionInstruction' + PPBC_EndInterruptionInstruction = 'PPBC.EndInterruptionInstruction' + OMBC_SystemDescription = 'OMBC.SystemDescription' + OMBC_Instruction = 'OMBC.Instruction' + FRBC_SystemDescription = 'FRBC.SystemDescription' + FRBC_Instruction = 'FRBC.Instruction' + DDBC_SystemDescription = 'DDBC.SystemDescription' + DDBC_Instruction = 'DDBC.Instruction' + + +class EnergyManagementRole(Enum): + CEM = 'CEM' + RM = 'RM' + + +class ReceptionStatusValues(Enum): + INVALID_DATA = 'INVALID_DATA' + INVALID_MESSAGE = 'INVALID_MESSAGE' + INVALID_CONTENT = 'INVALID_CONTENT' + TEMPORARY_ERROR = 'TEMPORARY_ERROR' + PERMANENT_ERROR = 'PERMANENT_ERROR' + OK = 'OK' + + +class NumberRange(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + start_of_range: float = Field( + ..., description='Number that defines the start of the range' + ) + end_of_range: float = Field( + ..., description='Number that defines the end of the range' + ) + + +class Transition(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + id: ID = Field( + ..., + description='ID of the Transition. Must be unique in the scope of the OMBC.SystemDescription, FRBC.ActuatorDescription or DDBC.ActuatorDescription in which it is used.', + ) + from_: ID = Field( + ..., + alias='from', + description='ID of the OperationMode (exact type differs per ControlType) that should be switched from.', + ) + to: ID = Field( + ..., + description='ID of the OperationMode (exact type differs per ControlType) that will be switched to.', + ) + start_timers: List[ID] = Field( + ..., + description='List of IDs of Timers that will be (re)started when this transition is initiated', + max_length=1000, + min_length=0, + ) + blocking_timers: List[ID] = Field( + ..., + description='List of IDs of Timers that block this Transition from initiating while at least one of these Timers is not yet finished', + max_length=1000, + min_length=0, + ) + transition_costs: Optional[float] = Field( + None, + description='Absolute costs for going through this Transition in the currency as described in the ResourceManagerDetails.', + ) + transition_duration: Optional[Duration] = Field( + None, + description='Indicates the time between the initiation of this Transition, and the time at which the device behaves according to the Operation Mode which is defined in the ‘to’ data element. When no value is provided it is assumed the transition duration is negligible.', + ) + abnormal_condition_only: bool = Field( + ..., + description='Indicates if this Transition may only be used during an abnormal condition (see Clause )', + ) + + +class Timer(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + id: ID = Field( + ..., + description='ID of the Timer. Must be unique in the scope of the OMBC.SystemDescription, FRBC.ActuatorDescription or DDBC.ActuatorDescription in which it is used.', + ) + diagnostic_label: Optional[str] = Field( + None, + description='Human readable name/description of the Timer. This element is only intended for diagnostic purposes and not for HMI applications.', + ) + duration: Duration = Field( + ..., + description='The time it takes for the Timer to finish after it has been started', + ) + + +class PEBCPowerEnvelopeElement(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + duration: Duration = Field(..., description='The duration of the element') + upper_limit: float = Field( + ..., + description='Upper power limit according to the commodity_quantity of the containing PEBC.PowerEnvelope. The lower_limit must be smaller or equal to the upper_limit. The Resource Manager is requested to keep the power values for the given commodity quantity equal to or below the upper_limit. The upper_limit shall be in accordance with the constraints provided by the Resource Manager through any PEBC.AllowedLimitRange with limit_type UPPER_LIMIT.', + ) + lower_limit: float = Field( + ..., + description='Lower power limit according to the commodity_quantity of the containing PEBC.PowerEnvelope. The lower_limit must be smaller or equal to the upper_limit. The Resource Manager is requested to keep the power values for the given commodity quantity equal to or above the lower_limit. The lower_limit shall be in accordance with the constraints provided by the Resource Manager through any PEBC.AllowedLimitRange with limit_type LOWER_LIMIT.', + ) + + +class FRBCStorageDescription(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + diagnostic_label: Optional[str] = Field( + None, + description='Human readable name/description of the storage (e.g. hot water buffer or battery). This element is only intended for diagnostic purposes and not for HMI applications.', + ) + fill_level_label: Optional[str] = Field( + None, + description='Human readable description of the (physical) units associated with the fill_level (e.g. degrees Celsius or percentage state of charge). This element is only intended for diagnostic purposes and not for HMI applications.', + ) + provides_leakage_behaviour: bool = Field( + ..., + description='Indicates whether the Storage could provide details of power leakage behaviour through the FRBC.LeakageBehaviour.', + ) + provides_fill_level_target_profile: bool = Field( + ..., + description='Indicates whether the Storage could provide a target profile for the fill level through the FRBC.FillLevelTargetProfile.', + ) + provides_usage_forecast: bool = Field( + ..., + description='Indicates whether the Storage could provide a UsageForecast through the FRBC.UsageForecast.', + ) + fill_level_range: NumberRange = Field( + ..., + description='The range in which the fill_level should remain. It is expected of the CEM to keep the fill_level within this range. When the fill_level is not within this range, the Resource Manager can ignore instructions from the CEM (except during abnormal conditions). ', + ) + + +class FRBCLeakageBehaviourElement(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + fill_level_range: NumberRange = Field( + ..., + description='The fill level range for which this FRBC.LeakageBehaviourElement applies. The start of the range must be less than the end of the range.', + ) + leakage_rate: float = Field( + ..., + description='Indicates how fast the momentary fill level will decrease per second due to leakage within the given range of the fill level. A positive value indicates that the fill level decreases over time due to leakage.', + ) + + +class FRBCUsageForecastElement(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + duration: Duration = Field( + ..., description='Indicator for how long the given usage_rate is valid.' + ) + usage_rate_upper_limit: Optional[float] = Field( + None, + description='The upper limit of the range with a 100 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', + ) + usage_rate_upper_95PPR: Optional[float] = Field( + None, + description='The upper limit of the range with a 95 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', + ) + usage_rate_upper_68PPR: Optional[float] = Field( + None, + description='The upper limit of the range with a 68 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', + ) + usage_rate_expected: float = Field( + ..., + description='The most likely value for the usage rate; the expected increase or decrease of the fill_level per second. A positive value indicates that the fill level will decrease due to usage.', + ) + usage_rate_lower_68PPR: Optional[float] = Field( + None, + description='The lower limit of the range with a 68 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', + ) + usage_rate_lower_95PPR: Optional[float] = Field( + None, + description='The lower limit of the range with a 95 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', + ) + usage_rate_lower_limit: Optional[float] = Field( + None, + description='The lower limit of the range with a 100 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', + ) + + +class FRBCFillLevelTargetProfileElement(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + duration: Duration = Field(..., description='The duration of the element.') + fill_level_range: NumberRange = Field( + ..., + description='The target range in which the fill_level must be for the time period during which the element is active. The start of the range must be smaller or equal to the end of the range. The CEM must take best-effort actions to proactively achieve this target.', + ) + + +class DDBCAverageDemandRateForecastElement(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + duration: Duration = Field(..., description='Duration of the element') + demand_rate_upper_limit: Optional[float] = Field( + None, + description='The upper limit of the range with a 100 % probability that the demand rate is within that range', + ) + demand_rate_upper_95PPR: Optional[float] = Field( + None, + description='The upper limit of the range with a 95 % probability that the demand rate is within that range', + ) + demand_rate_upper_68PPR: Optional[float] = Field( + None, + description='The upper limit of the range with a 68 % probability that the demand rate is within that range', + ) + demand_rate_expected: float = Field( + ..., + description='The most likely value for the demand rate; the expected increase or decrease of the fill_level per second', + ) + demand_rate_lower_68PPR: Optional[float] = Field( + None, + description='The lower limit of the range with a 68 % probability that the demand rate is within that range', + ) + demand_rate_lower_95PPR: Optional[float] = Field( + None, + description='The lower limit of the range with a 95 % probability that the demand rate is within that range', + ) + demand_rate_lower_limit: Optional[float] = Field( + None, + description='The lower limit of the range with a 100 % probability that the demand rate is within that range', + ) + + +class RoleType(Enum): + ENERGY_PRODUCER = 'ENERGY_PRODUCER' + ENERGY_CONSUMER = 'ENERGY_CONSUMER' + ENERGY_STORAGE = 'ENERGY_STORAGE' + + +class Commodity(Enum): + GAS = 'GAS' + HEAT = 'HEAT' + ELECTRICITY = 'ELECTRICITY' + OIL = 'OIL' + + +class CommodityQuantity(Enum): + ELECTRIC_POWER_L1 = 'ELECTRIC.POWER.L1' + ELECTRIC_POWER_L2 = 'ELECTRIC.POWER.L2' + ELECTRIC_POWER_L3 = 'ELECTRIC.POWER.L3' + ELECTRIC_POWER_3_PHASE_SYMMETRIC = 'ELECTRIC.POWER.3_PHASE_SYMMETRIC' + NATURAL_GAS_FLOW_RATE = 'NATURAL_GAS.FLOW_RATE' + HYDROGEN_FLOW_RATE = 'HYDROGEN.FLOW_RATE' + HEAT_TEMPERATURE = 'HEAT.TEMPERATURE' + HEAT_FLOW_RATE = 'HEAT.FLOW_RATE' + HEAT_THERMAL_POWER = 'HEAT.THERMAL_POWER' + OIL_FLOW_RATE = 'OIL.FLOW_RATE' + + +class InstructionStatus(Enum): + NEW = 'NEW' + ACCEPTED = 'ACCEPTED' + REJECTED = 'REJECTED' + REVOKED = 'REVOKED' + STARTED = 'STARTED' + SUCCEEDED = 'SUCCEEDED' + ABORTED = 'ABORTED' + + +class ControlType(Enum): + POWER_ENVELOPE_BASED_CONTROL = 'POWER_ENVELOPE_BASED_CONTROL' + POWER_PROFILE_BASED_CONTROL = 'POWER_PROFILE_BASED_CONTROL' + OPERATION_MODE_BASED_CONTROL = 'OPERATION_MODE_BASED_CONTROL' + FILL_RATE_BASED_CONTROL = 'FILL_RATE_BASED_CONTROL' + DEMAND_DRIVEN_BASED_CONTROL = 'DEMAND_DRIVEN_BASED_CONTROL' + NOT_CONTROLABLE = 'NOT_CONTROLABLE' + NO_SELECTION = 'NO_SELECTION' + + +class PEBCPowerEnvelopeLimitType(Enum): + UPPER_LIMIT = 'UPPER_LIMIT' + LOWER_LIMIT = 'LOWER_LIMIT' + + +class PEBCPowerEnvelopeConsequenceType(Enum): + VANISH = 'VANISH' + DEFER = 'DEFER' + + +class PPBCPowerSequenceStatus(Enum): + NOT_SCHEDULED = 'NOT_SCHEDULED' + SCHEDULED = 'SCHEDULED' + EXECUTING = 'EXECUTING' + INTERRUPTED = 'INTERRUPTED' + FINISHED = 'FINISHED' + ABORTED = 'ABORTED' + + +class OMBCTimerStatus(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['OMBC.TimerStatus'] = 'OMBC.TimerStatus' + message_id: ID + timer_id: ID = Field(..., description='The ID of the timer this message refers to') + finished_at: AwareDatetime = Field( + ..., + description='Indicates when the Timer will be finished. If the DateTimeStamp is in the future, the timer is not yet finished. If the DateTimeStamp is in the past, the timer is finished. If the timer was never started, the value can be an arbitrary DateTimeStamp in the past.', + ) + + +class FRBCTimerStatus(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['FRBC.TimerStatus'] = 'FRBC.TimerStatus' + message_id: ID + timer_id: ID = Field(..., description='The ID of the timer this message refers to') + actuator_id: ID = Field( + ..., description='The ID of the actuator the timer belongs to' + ) + finished_at: AwareDatetime = Field( + ..., + description='Indicates when the Timer will be finished. If the DateTimeStamp is in the future, the timer is not yet finished. If the DateTimeStamp is in the past, the timer is finished. If the timer was never started, the value can be an arbitrary DateTimeStamp in the past.', + ) + + +class DDBCTimerStatus(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['DDBC.TimerStatus'] = 'DDBC.TimerStatus' + message_id: ID + timer_id: ID = Field(..., description='The ID of the timer this message refers to') + actuator_id: ID = Field( + ..., description='The ID of the actuator the timer belongs to' + ) + finished_at: AwareDatetime = Field( + ..., + description='Indicates when the Timer will be finished. If the DateTimeStamp is in the future, the timer is not yet finished. If the DateTimeStamp is in the past, the timer is finished. If the timer was never started, the value can be an arbitrary DateTimeStamp in the past.', + ) + + +class SelectControlType(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['SelectControlType'] = 'SelectControlType' + message_id: ID + control_type: ControlType = Field( + ..., + description='The ControlType to activate. Must be one of the available ControlTypes as defined in the ResourceManagerDetails', + ) + + +class SessionRequest(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['SessionRequest'] = 'SessionRequest' + message_id: ID + request: SessionRequestType = Field(..., description='The type of request') + diagnostic_label: Optional[str] = Field( + None, + description='Optional field for a human readible descirption for debugging purposes', + ) + + +class RevokeObject(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['RevokeObject'] = 'RevokeObject' + message_id: ID + object_type: RevokableObjects = Field( + ..., description='The type of object that needs to be revoked' + ) + object_id: ID = Field(..., description='The ID of object that needs to be revoked') + + +class Handshake(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['Handshake'] = 'Handshake' + message_id: ID + role: EnergyManagementRole = Field( + ..., description='The role of the sender of this message' + ) + supported_protocol_versions: Optional[List[str]] = Field( + None, + description='Protocol versions supported by the sender of this message. This field is mandatory for the RM, but optional for the CEM.', + min_length=1, + ) + + +class HandshakeResponse(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['HandshakeResponse'] = 'HandshakeResponse' + message_id: ID + selected_protocol_version: str = Field( + ..., description='The protocol version the CEM selected for this session' + ) + + +class ReceptionStatus(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['ReceptionStatus'] = 'ReceptionStatus' + subject_message_id: ID = Field( + ..., description='The message this ReceptionStatus refers to' + ) + status: ReceptionStatusValues = Field( + ..., description='Enumeration of status values' + ) + diagnostic_label: Optional[str] = Field( + None, + description='Diagnostic label that can be used to provide additional information for debugging. However, not for HMI purposes.', + ) + + +class InstructionStatusUpdate(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['InstructionStatusUpdate'] = 'InstructionStatusUpdate' + message_id: ID + instruction_id: ID = Field( + ..., description='ID of this instruction (as provided by the CEM) ' + ) + status_type: InstructionStatus = Field( + ..., description='Present status of this instruction.' + ) + timestamp: AwareDatetime = Field( + ..., description='Timestamp when status_type has changed the last time.' + ) + + +class PEBCEnergyConstraint(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['PEBC.EnergyConstraint'] = 'PEBC.EnergyConstraint' + message_id: ID + id: ID = Field( + ..., + description='Identifier of this PEBC.EnergyConstraints. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + ) + valid_from: AwareDatetime = Field( + ..., + description='Moment this PEBC.EnergyConstraints information starts to be valid', + ) + valid_until: AwareDatetime = Field( + ..., + description='Moment until this PEBC.EnergyConstraints information is valid.', + ) + upper_average_power: float = Field( + ..., + description='Upper average power within the time period given by valid_from and valid_until. If the duration is multiplied with this power value, then the associated upper energy content can be derived. This is the highest amount of energy the resource will consume during that period of time. The Power Envelope created by the CEM must allow at least this much energy consumption (in case the number is positive). Must be greater than or equal to lower_average_power, and can be negative in case of energy production.', + ) + lower_average_power: float = Field( + ..., + description='Lower average power within the time period given by valid_from and valid_until. If the duration is multiplied with this power value, then the associated lower energy content can be derived. This is the lowest amount of energy the resource will consume during that period of time. The Power Envelope created by the CEM must allow at least this much energy production (in case the number is negative). Must be greater than or equal to lower_average_power, and can be negative in case of energy production.', + ) + commodity_quantity: CommodityQuantity = Field( + ..., + description='Type of power quantity which applies to upper_average_power and lower_average_power', + ) + + +class PPBCScheduleInstruction(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['PPBC.ScheduleInstruction'] = 'PPBC.ScheduleInstruction' + message_id: ID + id: ID = Field( + ..., + description='ID of the Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + ) + power_profile_id: ID = Field( + ..., + description='ID of the PPBC.PowerProfileDefinition of which the PPBC.PowerSequence is being selected and scheduled by the CEM.', + ) + sequence_container_id: ID = Field( + ..., + description='ID of the PPBC.PowerSequnceContainer of which the PPBC.PowerSequence is being selected and scheduled by the CEM.', + ) + power_sequence_id: ID = Field( + ..., + description='ID of the PPBC.PowerSequence that is being selected and scheduled by the CEM.', + ) + execution_time: AwareDatetime = Field( + ..., + description='Indicates the moment the PPBC.PowerSequence shall start. When the specified execution time is in the past, execution must start as soon as possible.', + ) + abnormal_condition: bool = Field( + ..., + description='Indicates if this is an instruction during an abnormal condition', + ) + + +class PPBCStartInterruptionInstruction(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['PPBC.StartInterruptionInstruction'] = ( + 'PPBC.StartInterruptionInstruction' + ) + message_id: ID + id: ID = Field( + ..., + description='ID of the Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + ) + power_profile_id: ID = Field( + ..., + description='ID of the PPBC.PowerProfileDefinition of which the PPBC.PowerSequence is being interrupted by the CEM.', + ) + sequence_container_id: ID = Field( + ..., + description='ID of the PPBC.PowerSequnceContainer of which the PPBC.PowerSequence is being interrupted by the CEM.', + ) + power_sequence_id: ID = Field( + ..., description='ID of the PPBC.PowerSequence that the CEM wants to interrupt.' + ) + execution_time: AwareDatetime = Field( + ..., + description='Indicates the moment the PPBC.PowerSequence shall be interrupted. When the specified execution time is in the past, execution must start as soon as possible.', + ) + abnormal_condition: bool = Field( + ..., + description='Indicates if this is an instruction during an abnormal condition', + ) + + +class PPBCEndInterruptionInstruction(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['PPBC.EndInterruptionInstruction'] = ( + 'PPBC.EndInterruptionInstruction' + ) + message_id: ID + id: ID = Field( + ..., + description='ID of the Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + ) + power_profile_id: ID = Field( + ..., + description='ID of the PPBC.PowerProfileDefinition of which the PPBC.PowerSequence interruption is being ended by the CEM.', + ) + sequence_container_id: ID = Field( + ..., + description='ID of the PPBC.PowerSequnceContainer of which the PPBC.PowerSequence interruption is being ended by the CEM.', + ) + power_sequence_id: ID = Field( + ..., + description='ID of the PPBC.PowerSequence for which the CEM wants to end the interruption.', + ) + execution_time: AwareDatetime = Field( + ..., + description='Indicates the moment PPBC.PowerSequence interruption shall end. When the specified execution time is in the past, execution must start as soon as possible.', + ) + abnormal_condition: bool = Field( + ..., + description='Indicates if this is an instruction during an abnormal condition', + ) + + +class OMBCStatus(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['OMBC.Status'] = 'OMBC.Status' + message_id: ID + active_operation_mode_id: ID = Field( + ..., description='ID of the active OMBC.OperationMode.' + ) + operation_mode_factor: float = Field( + ..., + description='The number indicates the factor with which the OMBC.OperationMode should be configured. The factor should be greater than or equal than 0 and less or equal to 1.', + ) + previous_operation_mode_id: Optional[ID] = Field( + None, + description='ID of the OMBC.OperationMode that was previously active. This value shall always be provided, unless the active OMBC.OperationMode is the first OMBC.OperationMode the Resource Manager is aware of.', + ) + transition_timestamp: Optional[AwareDatetime] = Field( + None, + description='Time at which the transition from the previous OMBC.OperationMode to the active OMBC.OperationMode was initiated. This value shall always be provided, unless the active OMBC.OperationMode is the first OMBC.OperationMode the Resource Manager is aware of.', + ) + + +class OMBCInstruction(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['OMBC.Instruction'] = 'OMBC.Instruction' + message_id: ID + id: ID = Field( + ..., + description='ID of the instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + ) + execution_time: AwareDatetime = Field( + ..., + description='Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.', + ) + operation_mode_id: ID = Field( + ..., description='ID of the OMBC.OperationMode that should be activated' + ) + operation_mode_factor: float = Field( + ..., + description='The number indicates the factor with which the OMBC.OperationMode should be configured. The factor should be greater than or equal than 0 and less or equal to 1.', + ) + abnormal_condition: bool = Field( + ..., + description='Indicates if this is an instruction during an abnormal condition', + ) + + +class FRBCActuatorStatus(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['FRBC.ActuatorStatus'] = 'FRBC.ActuatorStatus' + message_id: ID + actuator_id: ID = Field( + ..., description='ID of the actuator this messages refers to' + ) + active_operation_mode_id: ID = Field( + ..., description='ID of the FRBC.OperationMode that is presently active.' + ) + operation_mode_factor: float = Field( + ..., + description='The number indicates the factor with which the FRBC.OperationMode is configured. The factor should be greater than or equal than 0 and less or equal to 1.', + ) + previous_operation_mode_id: Optional[ID] = Field( + None, + description='ID of the FRBC.OperationMode that was active before the present one. This value shall always be provided, unless the active FRBC.OperationMode is the first FRBC.OperationMode the Resource Manager is aware of.', + ) + transition_timestamp: Optional[AwareDatetime] = Field( + None, + description='Time at which the transition from the previous FRBC.OperationMode to the active FRBC.OperationMode was initiated. This value shall always be provided, unless the active FRBC.OperationMode is the first FRBC.OperationMode the Resource Manager is aware of.', + ) + + +class FRBCStorageStatus(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['FRBC.StorageStatus'] = 'FRBC.StorageStatus' + message_id: ID + present_fill_level: float = Field( + ..., description='Present fill level of the Storage' + ) + + +class FRBCLeakageBehaviour(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['FRBC.LeakageBehaviour'] = 'FRBC.LeakageBehaviour' + message_id: ID + valid_from: AwareDatetime = Field( + ..., + description='Moment this FRBC.LeakageBehaviour starts to be valid. If the FRBC.LeakageBehaviour is immediately valid, the DateTimeStamp should be now or in the past.', + ) + elements: List[FRBCLeakageBehaviourElement] = Field( + ..., + description='List of elements that model the leakage behaviour of the buffer. The fill_level_ranges of the elements must be contiguous.', + max_length=288, + min_length=1, + ) + + +class FRBCInstruction(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['FRBC.Instruction'] = 'FRBC.Instruction' + message_id: ID + id: ID = Field( + ..., + description='ID of the instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + ) + actuator_id: ID = Field( + ..., description='ID of the actuator this instruction belongs to.' + ) + operation_mode: ID = Field( + ..., description='ID of the FRBC.OperationMode that should be activated.' + ) + operation_mode_factor: float = Field( + ..., + description='The number indicates the factor with which the FRBC.OperationMode should be configured. The factor should be greater than or equal to 0 and less or equal to 1.', + ) + execution_time: AwareDatetime = Field( + ..., + description='Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.', + ) + abnormal_condition: bool = Field( + ..., + description='Indicates if this is an instruction during an abnormal condition.', + ) + + +class FRBCUsageForecast(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['FRBC.UsageForecast'] = 'FRBC.UsageForecast' + message_id: ID + start_time: AwareDatetime = Field( + ..., description='Time at which the FRBC.UsageForecast starts.' + ) + elements: List[FRBCUsageForecastElement] = Field( + ..., + description='Further elements that model the profile. There shall be at least one element. Elements must be placed in chronological order.', + max_length=288, + min_length=1, + ) + + +class FRBCFillLevelTargetProfile(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['FRBC.FillLevelTargetProfile'] = 'FRBC.FillLevelTargetProfile' + message_id: ID + start_time: AwareDatetime = Field( + ..., description='Time at which the FRBC.FillLevelTargetProfile starts.' + ) + elements: List[FRBCFillLevelTargetProfileElement] = Field( + ..., + description='List of different fill levels that have to be targeted within a given duration. There shall be at least one element. Elements must be placed in chronological order.', + max_length=288, + min_length=1, + ) + + +class DDBCActuatorStatus(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['DDBC.ActuatorStatus'] = 'DDBC.ActuatorStatus' + message_id: ID + actuator_id: ID = Field( + ..., description='ID of the actuator this messages refers to' + ) + active_operation_mode_id: ID = Field( + ..., + description='The operation mode that is presently active for this actuator.', + ) + operation_mode_factor: float = Field( + ..., + description='The number indicates the factor with which the DDBC.OperationMode is configured. The factor should be greater than or equal to 0 and less or equal to 1.', + ) + previous_operation_mode_id: Optional[ID] = Field( + None, + description='ID of the DDBC,OperationMode that was active before the present one. This value shall always be provided, unless the active DDBC.OperationMode is the first DDBC.OperationMode the Resource Manager is aware of.', + ) + transition_timestamp: Optional[AwareDatetime] = Field( + None, + description='Time at which the transition from the previous DDBC.OperationMode to the active DDBC.OperationMode was initiated. This value shall always be provided, unless the active DDBC.OperationMode is the first DDBC.OperationMode the Resource Manager is aware of.', + ) + + +class DDBCInstruction(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['DDBC.Instruction'] = 'DDBC.Instruction' + message_id: ID + id: ID = Field( + ..., + description='Identifier of this DDBC.Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + ) + execution_time: AwareDatetime = Field( + ..., + description='Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.', + ) + abnormal_condition: bool = Field( + ..., + description='Indicates if this is an instruction during an abnormal condition', + ) + actuator_id: ID = Field( + ..., description='ID of the actuator this Instruction belongs to.' + ) + operation_mode_id: ID = Field(..., description='ID of the DDBC.OperationMode') + operation_mode_factor: float = Field( + ..., + description='The number indicates the factor with which the OMBC.OperationMode should be configured. The factor should be greater than or equal to 0 and less or equal to 1.', + ) + + +class DDBCAverageDemandRateForecast(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['DDBC.AverageDemandRateForecast'] = ( + 'DDBC.AverageDemandRateForecast' + ) + message_id: ID + start_time: AwareDatetime = Field(..., description='Start time of the profile.') + elements: List[DDBCAverageDemandRateForecastElement] = Field( + ..., + description='Elements of the profile. Elements must be placed in chronological order.', + max_length=288, + min_length=1, + ) + + +class PowerValue(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + commodity_quantity: CommodityQuantity = Field( + ..., description='The power quantity the value refers to' + ) + value: float = Field( + ..., + description='Power value expressed in the unit associated with the CommodityQuantity', + ) + + +class PowerForecastValue(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + value_upper_limit: Optional[float] = Field( + None, + description='The upper boundary of the range with 100 % certainty the power value is in it', + ) + value_upper_95PPR: Optional[float] = Field( + None, + description='The upper boundary of the range with 95 % certainty the power value is in it', + ) + value_upper_68PPR: Optional[float] = Field( + None, + description='The upper boundary of the range with 68 % certainty the power value is in it', + ) + value_expected: float = Field(..., description='The expected power value.') + value_lower_68PPR: Optional[float] = Field( + None, + description='The lower boundary of the range with 68 % certainty the power value is in it', + ) + value_lower_95PPR: Optional[float] = Field( + None, + description='The lower boundary of the range with 95 % certainty the power value is in it', + ) + value_lower_limit: Optional[float] = Field( + None, + description='The lower boundary of the range with 100 % certainty the power value is in it', + ) + commodity_quantity: CommodityQuantity = Field( + ..., description='The power quantity the value refers to' + ) + + +class PowerRange(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + start_of_range: float = Field( + ..., description='Power value that defines the start of the range.' + ) + end_of_range: float = Field( + ..., description='Power value that defines the end of the range.' + ) + commodity_quantity: CommodityQuantity = Field( + ..., description='The power quantity the values refer to' + ) + + +class Role(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + role: RoleType = Field( + ..., description='Role type of the Resource Manager for the given commodity' + ) + commodity: Commodity = Field(..., description='Commodity the role refers to.') + + +class PowerForecastElement(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + duration: Duration = Field(..., description='Duration of the PowerForecastElement') + power_values: List[PowerForecastValue] = Field( + ..., + description='The values of power that are expected for the given period of time. There shall be at least one PowerForecastValue, and at most one PowerForecastValue per CommodityQuantity.', + max_length=10, + min_length=1, + ) + + +class PEBCAllowedLimitRange(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + commodity_quantity: CommodityQuantity = Field( + ..., description='Type of power quantity this PEBC.AllowedLimitRange applies to' + ) + limit_type: PEBCPowerEnvelopeLimitType = Field( + ..., + description='Indicates if this ranges applies to the upper limit or the lower limit', + ) + range_boundary: NumberRange = Field( + ..., + description='Boundaries of the power range of this PEBC.AllowedLimitRange. The CEM is allowed to choose values within this range for the power envelope for the limit as described in limit_type. The start of the range shall be smaller or equal than the end of the range. ', + ) + abnormal_condition_only: bool = Field( + ..., + description='Indicates if this PEBC.AllowedLimitRange may only be used during an abnormal condition', + ) + + +class PEBCPowerEnvelope(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + id: ID = Field( + ..., + description='Identifier of this PEBC.PowerEnvelope. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + ) + commodity_quantity: CommodityQuantity = Field( + ..., description='Type of power quantity this PEBC.PowerEnvelope applies to' + ) + power_envelope_elements: List[PEBCPowerEnvelopeElement] = Field( + ..., + description='The elements of this PEBC.PowerEnvelope. Shall contain at least one element. Elements must be placed in chronological order.', + max_length=288, + min_length=1, + ) + + +class PPBCPowerSequenceElement(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + duration: Duration = Field( + ..., description='Duration of the PPBC.PowerSequenceElement.' + ) + power_values: List[PowerForecastValue] = Field( + ..., + description='The value of power and deviations for the given duration. The array should contain at least one PowerForecastValue and at most one PowerForecastValue per CommodityQuantity.', + max_length=10, + min_length=1, + ) + + +class PPBCPowerSequenceContainerStatus(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + power_profile_id: ID = Field( + ..., + description='ID of the PPBC.PowerProfileDefinition of which the data element ‘sequence_container_id’ refers to. ', + ) + sequence_container_id: ID = Field( + ..., + description='ID of the PPBC.PowerSequenceContainer this PPBC.PowerSequenceContainerStatus provides information about.', + ) + selected_sequence_id: Optional[ID] = Field( + None, + description='ID of selected PPBC.PowerSequence. When no ID is given, no sequence was selected yet.', + ) + progress: Optional[Duration] = Field( + None, + description='Time that has passed since the selected sequence has started. A value must be provided, unless no sequence has been selected or the selected sequence hasn’t started yet.', + ) + status: PPBCPowerSequenceStatus = Field( + ..., description='Status of the selected PPBC.PowerSequence' + ) + + +class OMBCOperationMode(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + id: ID = Field( + ..., + description='ID of the OBMC.OperationMode. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + ) + diagnostic_label: Optional[str] = Field( + None, + description='Human readable name/description of the OMBC.OperationMode. This element is only intended for diagnostic purposes and not for HMI applications.', + ) + power_ranges: List[PowerRange] = Field( + ..., + description='The power produced or consumed by this operation mode. The start of each PowerRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1. In the array there must be at least one PowerRange, and at most one PowerRange per CommodityQuantity.', + max_length=10, + min_length=1, + ) + running_costs: Optional[NumberRange] = Field( + None, + description='Additional costs per second (e.g. wear, services) associated with this operation mode in the currency defined by the ResourceManagerDetails , excluding the commodity cost. The range is expressing uncertainty and is not linked to the operation_mode_factor.', + ) + abnormal_condition_only: bool = Field( + ..., + description='Indicates if this OMBC.OperationMode may only be used during an abnormal condition.', + ) + + +class FRBCOperationModeElement(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + fill_level_range: NumberRange = Field( + ..., + description='The range of the fill level for which this FRBC.OperationModeElement applies. The start of the NumberRange shall be smaller than the end of the NumberRange.', + ) + fill_rate: NumberRange = Field( + ..., + description='Indicates the change in fill_level per second. The lower_boundary of the NumberRange is associated with an operation_mode_factor of 0, the upper_boundary is associated with an operation_mode_factor of 1. ', + ) + power_ranges: List[PowerRange] = Field( + ..., + description='The power produced or consumed by this operation mode. The start of each PowerRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1. In the array there must be at least one PowerRange, and at most one PowerRange per CommodityQuantity.', + max_length=10, + min_length=1, + ) + running_costs: Optional[NumberRange] = Field( + None, + description='Additional costs per second (e.g. wear, services) associated with this operation mode in the currency defined by the ResourceManagerDetails, excluding the commodity cost. The range is expressing uncertainty and is not linked to the operation_mode_factor.', + ) + + +class DDBCOperationMode(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + Id: ID = Field( + ..., + description='ID of this operation mode. Must be unique in the scope of the DDBC.ActuatorDescription in which it is used.', + ) + diagnostic_label: Optional[str] = Field( + None, + description='Human readable name/description of the DDBC.OperationMode. This element is only intended for diagnostic purposes and not for HMI applications.', + ) + power_ranges: List[PowerRange] = Field( + ..., + description='The power produced or consumed by this operation mode. The start of each PowerRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1. In the array there must be at least one PowerRange, and at most one PowerRange per CommodityQuantity.', + max_length=10, + min_length=1, + ) + supply_range: NumberRange = Field( + ..., + description='The supply rate this DDBC.OperationMode can deliver for the CEM to match the demand rate. The start of the NumberRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1.', + ) + running_costs: Optional[NumberRange] = Field( + None, + description='Additional costs per second (e.g. wear, services) associated with this operation mode in the currency defined by the ResourceManagerDetails, excluding the commodity cost. The range is expressing uncertainty and is not linked to the operation_mode_factor.', + ) + abnormal_condition_only: bool = Field( + ..., + description='Indicates if this DDBC.OperationMode may only be used during an abnormal condition.', + ) + + +class ResourceManagerDetails(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['ResourceManagerDetails'] = 'ResourceManagerDetails' + message_id: ID + resource_id: ID = Field( + ..., + description='Identifier of the Resource Manager. Must be unique within the scope of the CEM.', + ) + name: Optional[str] = Field(None, description='Human readable name given by user') + roles: List[Role] = Field( + ..., + description='Each Resource Manager provides one or more energy Roles', + max_length=3, + min_length=1, + ) + manufacturer: Optional[str] = Field(None, description='Name of Manufacturer') + model: Optional[str] = Field( + None, + description='Name of the model of the device (provided by the manufacturer)', + ) + serial_number: Optional[str] = Field( + None, description='Serial number of the device (provided by the manufacturer)' + ) + firmware_version: Optional[str] = Field( + None, + description='Version identifier of the firmware used in the device (provided by the manufacturer)', + ) + instruction_processing_delay: Duration = Field( + ..., + description='The average time the combination of Resource Manager and HBES/BACS/SASS or (Smart) device needs to process and execute an instruction', + ) + available_control_types: List[ControlType] = Field( + ..., + description='The control types supported by this Resource Manager.', + max_length=5, + min_length=1, + ) + currency: Optional[Currency] = Field( + None, + description='Currency to be used for all information regarding costs. Mandatory if cost information is published.', + ) + provides_forecast: bool = Field( + ..., + description='Indicates whether the ResourceManager is able to provide PowerForecasts', + ) + provides_power_measurement_types: List[CommodityQuantity] = Field( + ..., + description='Array of all CommodityQuantities that this Resource Manager can provide measurements for. ', + max_length=10, + min_length=1, + ) + + +class PowerMeasurement(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['PowerMeasurement'] = 'PowerMeasurement' + message_id: ID + measurement_timestamp: AwareDatetime = Field( + ..., description='Timestamp when PowerValues were measured.' + ) + values: List[PowerValue] = Field( + ..., + description='Array of measured PowerValues. Must contain at least one item and at most one item per ‘commodity_quantity’ (defined inside the PowerValue).', + max_length=10, + min_length=1, + ) + + +class PowerForecast(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['PowerForecast'] = 'PowerForecast' + message_id: ID + start_time: AwareDatetime = Field( + ..., description='Start time of time period that is covered by the profile.' + ) + elements: List[PowerForecastElement] = Field( + ..., + description='Elements of which this forecast consists. Contains at least one element. Elements must be placed in chronological order.', + max_length=288, + min_length=1, + ) + + +class PEBCPowerConstraints(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['PEBC.PowerConstraints'] = 'PEBC.PowerConstraints' + message_id: ID + id: ID = Field( + ..., + description='Identifier of this PEBC.PowerConstraints. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + ) + valid_from: AwareDatetime = Field( + ..., description='Moment this PEBC.PowerConstraints start to be valid' + ) + valid_until: Optional[AwareDatetime] = Field( + None, + description='Moment until this PEBC.PowerConstraints is valid. If valid_until is not present, there is no determined end time of this PEBC.PowerConstraints.', + ) + consequence_type: PEBCPowerEnvelopeConsequenceType = Field( + ..., description='Type of consequence of limiting power' + ) + allowed_limit_ranges: List[PEBCAllowedLimitRange] = Field( + ..., + description='The actual constraints. There shall be at least one PEBC.AllowedLimitRange for the UPPER_LIMIT and at least one AllowedLimitRange for the LOWER_LIMIT. It is allowed to have multiple PEBC.AllowedLimitRange objects with identical CommodityQuantities and LimitTypes.', + max_length=100, + min_length=2, + ) + + +class PEBCInstruction(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['PEBC.Instruction'] = 'PEBC.Instruction' + message_id: ID + id: ID = Field( + ..., + description='Identifier of this PEBC.Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + ) + execution_time: AwareDatetime = Field( + ..., + description='Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.', + ) + abnormal_condition: bool = Field( + ..., + description='Indicates if this is an instruction during an abnormal condition.', + ) + power_constraints_id: ID = Field( + ..., + description='Identifier of the PEBC.PowerConstraints this PEBC.Instruction was based on.', + ) + power_envelopes: List[PEBCPowerEnvelope] = Field( + ..., + description='The PEBC.PowerEnvelope(s) that should be followed by the Resource Manager. There shall be at least one PEBC.PowerEnvelope, but at most one PEBC.PowerEnvelope for each CommodityQuantity.', + max_length=10, + min_length=1, + ) + + +class PPBCPowerProfileStatus(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['PPBC.PowerProfileStatus'] = 'PPBC.PowerProfileStatus' + message_id: ID + sequence_container_status: List[PPBCPowerSequenceContainerStatus] = Field( + ..., + description='Array with status information for all PPBC.PowerSequenceContainers in the PPBC.PowerProfileDefinition.', + max_length=1000, + min_length=1, + ) + + +class OMBCSystemDescription(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['OMBC.SystemDescription'] = 'OMBC.SystemDescription' + message_id: ID + valid_from: AwareDatetime = Field( + ..., + description='Moment this OMBC.SystemDescription starts to be valid. If the system description is immediately valid, the DateTimeStamp should be now or in the past.', + ) + operation_modes: List[OMBCOperationMode] = Field( + ..., + description='OMBC.OperationModes available for the CEM in order to coordinate the device behaviour.', + max_length=100, + min_length=1, + ) + transitions: List[Transition] = Field( + ..., + description='Possible transitions to switch from one OMBC.OperationMode to another.', + max_length=1000, + min_length=0, + ) + timers: List[Timer] = Field( + ..., + description='Timers that control when certain transitions can be made.', + max_length=1000, + min_length=0, + ) + + +class PPBCPowerSequence(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + id: ID = Field( + ..., + description='ID of the PPBC.PowerSequence. Must be unique in the scope of the PPBC.PowerSequnceContainer in which it is used.', + ) + elements: List[PPBCPowerSequenceElement] = Field( + ..., + description='List of PPBC.PowerSequenceElements. Shall contain at least one element. Elements must be placed in chronological order.', + max_length=288, + min_length=1, + ) + is_interruptible: bool = Field( + ..., + description='Indicates whether the option of pausing a sequence is available.', + ) + max_pause_before: Optional[Duration] = Field( + None, + description='The maximum duration for which a device can be paused between the end of the previous running sequence and the start of this one', + ) + abnormal_condition_only: bool = Field( + ..., + description='Indicates if this PPBC.PowerSequence may only be used during an abnormal condition', + ) + + +class FRBCOperationMode(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + id: ID = Field( + ..., + description='ID of the FRBC.OperationMode. Must be unique in the scope of the FRBC.ActuatorDescription in which it is used.', + ) + diagnostic_label: Optional[str] = Field( + None, + description='Human readable name/description of the FRBC.OperationMode. This element is only intended for diagnostic purposes and not for HMI applications.', + ) + elements: List[FRBCOperationModeElement] = Field( + ..., + description='List of FRBC.OperationModeElements, which describe the properties of this FRBC.OperationMode depending on the fill_level. The fill_level_ranges of the items in the Array must be contiguous.', + max_length=100, + min_length=1, + ) + abnormal_condition_only: bool = Field( + ..., + description='Indicates if this FRBC.OperationMode may only be used during an abnormal condition', + ) + + +class DDBCActuatorDescription(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + id: ID = Field( + ..., + description='ID of this DDBC.ActuatorDescription. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + ) + diagnostic_label: Optional[str] = Field( + None, + description='Human readable name/description of the actuator. This element is only intended for diagnostic purposes and not for HMI applications.', + ) + supported_commodites: List[Commodity] = Field( + ..., + description='Commodities supported by the operation modes of this actuator. There shall be at least one commodity', + max_length=4, + min_length=1, + ) + operation_modes: List[DDBCOperationMode] = Field( + ..., + description='List of all Operation Modes that are available for this actuator. There shall be at least one DDBC.OperationMode.', + max_length=100, + min_length=1, + ) + transitions: List[Transition] = Field( + ..., + description='List of Transitions between Operation Modes. Shall contain at least one Transition.', + max_length=1000, + min_length=0, + ) + timers: List[Timer] = Field( + ..., + description='List of Timers associated with Transitions for this Actuator. Can be empty.', + max_length=1000, + min_length=0, + ) + + +class DDBCSystemDescription(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['DDBC.SystemDescription'] = 'DDBC.SystemDescription' + message_id: ID + valid_from: AwareDatetime = Field( + ..., + description='Moment this DDBC.SystemDescription starts to be valid. If the system description is immediately valid, the DateTimeStamp should be now or in the past.', + ) + actuators: List[DDBCActuatorDescription] = Field( + ..., + description='List of all available actuators in the system. Must contain at least one DDBC.ActuatorAggregated.', + max_length=10, + min_length=1, + ) + present_demand_rate: NumberRange = Field( + ..., description='Present demand rate that needs to be satisfied by the system' + ) + provides_average_demand_rate_forecast: bool = Field( + ..., + description='Indicates whether the Resource Manager could provide a demand rate forecast through the DDBC.AverageDemandRateForecast.', + ) + + +class PPBCPowerSequenceContainer(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + id: ID = Field( + ..., + description='ID of the PPBC.PowerSequenceContainer. Must be unique in the scope of the PPBC.PowerProfileDefinition in which it is used.', + ) + power_sequences: List[PPBCPowerSequence] = Field( + ..., + description='List of alternative Sequences where one could be chosen by the CEM', + max_length=288, + min_length=1, + ) + + +class FRBCActuatorDescription(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + id: ID = Field( + ..., + description='ID of the Actuator. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + ) + diagnostic_label: Optional[str] = Field( + None, + description='Human readable name/description for the actuator. This element is only intended for diagnostic purposes and not for HMI applications.', + ) + supported_commodities: List[Commodity] = Field( + ..., + description='List of all supported Commodities.', + max_length=4, + min_length=1, + ) + operation_modes: List[FRBCOperationMode] = Field( + ..., + description='Provided FRBC.OperationModes associated with this actuator', + max_length=100, + min_length=1, + ) + transitions: List[Transition] = Field( + ..., + description='Possible transitions between FRBC.OperationModes associated with this actuator.', + max_length=1000, + min_length=0, + ) + timers: List[Timer] = Field( + ..., + description='List of Timers associated with this actuator', + max_length=1000, + min_length=0, + ) + + +class PPBCPowerProfileDefinition(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['PPBC.PowerProfileDefinition'] = 'PPBC.PowerProfileDefinition' + message_id: ID + id: ID = Field( + ..., + description='ID of the PPBC.PowerProfileDefinition. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + ) + start_time: AwareDatetime = Field( + ..., + description='Indicates the first possible time the first PPBC.PowerSequence could start', + ) + end_time: AwareDatetime = Field( + ..., + description='Indicates when the last PPBC.PowerSequence shall be finished at the latest', + ) + power_sequences_containers: List[PPBCPowerSequenceContainer] = Field( + ..., + description='The PPBC.PowerSequenceContainers that make up this PPBC.PowerProfileDefinition. There shall be at least one PPBC.PowerSequenceContainer that includes at least one PPBC.PowerSequence. PPBC.PowerSequenceContainers must be placed in chronological order.', + max_length=1000, + min_length=1, + ) + + +class FRBCSystemDescription(BaseModel): + model_config = ConfigDict( + extra='forbid', + ) + message_type: Literal['FRBC.SystemDescription'] = 'FRBC.SystemDescription' + message_id: ID + valid_from: AwareDatetime = Field( + ..., + description='Moment this FRBC.SystemDescription starts to be valid. If the system description is immediately valid, the DateTimeStamp should be now or in the past.', + ) + actuators: List[FRBCActuatorDescription] = Field( + ..., description='Details of all Actuators.', max_length=10, min_length=1 + ) + storage: FRBCStorageDescription = Field(..., description='Details of the storage.') diff --git a/build/lib/s2python/py.typed b/build/lib/s2python/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/build/lib/s2python/reception_status_awaiter.py b/build/lib/s2python/reception_status_awaiter.py new file mode 100644 index 0000000..5c4bd42 --- /dev/null +++ b/build/lib/s2python/reception_status_awaiter.py @@ -0,0 +1,60 @@ +"""ReceptationStatusAwaiter class which notifies any coroutine waiting for a certain reception status message. + +Copied from +https://github.com/flexiblepower/s2-analyzer/blob/main/backend/s2_analyzer_backend/reception_status_awaiter.py under +Apache2 license on 31-08-2024. +""" + +import asyncio +import uuid +from typing import Dict + +from s2python.common import ReceptionStatus + + +class ReceptionStatusAwaiter: + received: Dict[uuid.UUID, ReceptionStatus] + awaiting: Dict[uuid.UUID, asyncio.Event] + + def __init__(self) -> None: + self.received = {} + self.awaiting = {} + + async def wait_for_reception_status( + self, message_id: uuid.UUID, timeout_reception_status: float + ) -> ReceptionStatus: + if message_id in self.received: + reception_status = self.received[message_id] + else: + if message_id in self.awaiting: + received_event = self.awaiting[message_id] + else: + received_event = asyncio.Event() + self.awaiting[message_id] = received_event + + await asyncio.wait_for(received_event.wait(), timeout_reception_status) + reception_status = self.received[message_id] + + if message_id in self.awaiting: + del self.awaiting[message_id] + + return reception_status + + async def receive_reception_status(self, reception_status: ReceptionStatus) -> None: + if not isinstance(reception_status, ReceptionStatus): + raise RuntimeError( + f"Expected a ReceptionStatus but received message {reception_status}" + ) + + if reception_status.subject_message_id in self.received: + raise RuntimeError( + f"ReceptationStatus for message_subject_id {reception_status.subject_message_id} has already " + f"been received!" + ) + + self.received[reception_status.subject_message_id] = reception_status + awaiting = self.awaiting.get(reception_status.subject_message_id) + + if awaiting: + awaiting.set() + del self.awaiting[reception_status.subject_message_id] diff --git a/build/lib/s2python/s2_connection.py b/build/lib/s2python/s2_connection.py new file mode 100644 index 0000000..188ecc7 --- /dev/null +++ b/build/lib/s2python/s2_connection.py @@ -0,0 +1,526 @@ +import asyncio +import json +import logging +import time +import threading +import uuid +from dataclasses import dataclass +from typing import Optional, List, Type, Dict, Callable, Awaitable, Union + +import websockets +from websockets.asyncio.client import ClientConnection as WSConnection, connect as ws_connect + +from s2python.common import ( + ReceptionStatusValues, + ReceptionStatus, + Handshake, + EnergyManagementRole, + Role, + HandshakeResponse, + ResourceManagerDetails, + Duration, + Currency, + SelectControlType, +) +from s2python.generated.gen_s2 import CommodityQuantity +from s2python.reception_status_awaiter import ReceptionStatusAwaiter +from s2python.s2_control_type import S2ControlType +from s2python.s2_parser import S2Parser +from s2python.s2_validation_error import S2ValidationError +from s2python.validate_values_mixin import S2Message +from s2python.version import S2_VERSION + +logger = logging.getLogger("s2python") + + +@dataclass +class AssetDetails: # pylint: disable=too-many-instance-attributes + resource_id: str + + provides_forecast: bool + provides_power_measurements: List[CommodityQuantity] + + instruction_processing_delay: Duration + roles: List[Role] + currency: Optional[Currency] = None + + name: Optional[str] = None + manufacturer: Optional[str] = None + model: Optional[str] = None + firmware_version: Optional[str] = None + serial_number: Optional[str] = None + + def to_resource_manager_details( + self, control_types: List[S2ControlType] + ) -> ResourceManagerDetails: + return ResourceManagerDetails( + available_control_types=[ + control_type.get_protocol_control_type() for control_type in control_types + ], + currency=self.currency, + firmware_version=self.firmware_version, + instruction_processing_delay=self.instruction_processing_delay, + manufacturer=self.manufacturer, + message_id=uuid.uuid4(), + model=self.model, + name=self.name, + provides_forecast=self.provides_forecast, + provides_power_measurement_types=self.provides_power_measurements, + resource_id=self.resource_id, + roles=self.roles, + serial_number=self.serial_number, + ) + + +S2MessageHandler = Union[ + Callable[["S2Connection", S2Message, Callable[[], None]], None], + Callable[["S2Connection", S2Message, Awaitable[None]], Awaitable[None]], +] + + +class SendOkay: + status_is_send: threading.Event + connection: "S2Connection" + subject_message_id: uuid.UUID + + def __init__(self, connection: "S2Connection", subject_message_id: uuid.UUID): + self.status_is_send = threading.Event() + self.connection = connection + self.subject_message_id = subject_message_id + + async def run_async(self) -> None: + self.status_is_send.set() + + await self.connection.respond_with_reception_status( + subject_message_id=str(self.subject_message_id), + status=ReceptionStatusValues.OK, + diagnostic_label="Processed okay.", + ) + + def run_sync(self) -> None: + self.status_is_send.set() + + self.connection.respond_with_reception_status_sync( + subject_message_id=str(self.subject_message_id), + status=ReceptionStatusValues.OK, + diagnostic_label="Processed okay.", + ) + + async def ensure_send_async(self, type_msg: Type[S2Message]) -> None: + if not self.status_is_send.is_set(): + logger.warning( + "Handler for message %s %s did not call send_okay / function to send the ReceptionStatus. " + "Sending it now.", + type_msg, + self.subject_message_id, + ) + await self.run_async() + + def ensure_send_sync(self, type_msg: Type[S2Message]) -> None: + if not self.status_is_send.is_set(): + logger.warning( + "Handler for message %s %s did not call send_okay / function to send the ReceptionStatus. " + "Sending it now.", + type_msg, + self.subject_message_id, + ) + self.run_sync() + + +class MessageHandlers: + handlers: Dict[Type[S2Message], S2MessageHandler] + + def __init__(self) -> None: + self.handlers = {} + + async def handle_message(self, connection: "S2Connection", msg: S2Message) -> None: + """Handle the S2 message using the registered handler. + + :param connection: The S2 conncetion the `msg` is received from. + :param msg: The S2 message + """ + handler = self.handlers.get(type(msg)) + if handler is not None: + send_okay = SendOkay(connection, msg.message_id) # type: ignore[attr-defined] + + try: + if asyncio.iscoroutinefunction(handler): + await handler(connection, msg, send_okay.run_async()) # type: ignore[arg-type] + await send_okay.ensure_send_async(type(msg)) + else: + + def do_message() -> None: + handler(connection, msg, send_okay.run_sync) # type: ignore[arg-type] + send_okay.ensure_send_sync(type(msg)) + + eventloop = asyncio.get_event_loop() + await eventloop.run_in_executor(executor=None, func=do_message) + except Exception: + if not send_okay.status_is_send.is_set(): + await connection.respond_with_reception_status( + subject_message_id=str(msg.message_id), # type: ignore[attr-defined] + status=ReceptionStatusValues.PERMANENT_ERROR, + diagnostic_label=f"While processing message {msg.message_id} " # type: ignore[attr-defined] + f"an unrecoverable error occurred.", + ) + raise + else: + logger.warning( + "Received a message of type %s but no handler is registered. Ignoring the message.", + type(msg), + ) + + def register_handler(self, msg_type: Type[S2Message], handler: S2MessageHandler) -> None: + """Register a coroutine function or a normal function as the handler for a specific S2 message type. + + :param msg_type: The S2 message type to attach the handler to. + :param handler: The function (asynchronuous or normal) which should handle the S2 message. + """ + self.handlers[msg_type] = handler + + +class S2Connection: # pylint: disable=too-many-instance-attributes + url: str + reconnect: bool + reception_status_awaiter: ReceptionStatusAwaiter + ws: Optional[WSConnection] + s2_parser: S2Parser + control_types: List[S2ControlType] + role: EnergyManagementRole + asset_details: AssetDetails + + _thread: threading.Thread + + _handlers: MessageHandlers + _current_control_type: Optional[S2ControlType] + _received_messages: asyncio.Queue + + _eventloop: asyncio.AbstractEventLoop + _stop_event: asyncio.Event + _restart_connection_event: asyncio.Event + + def __init__( # pylint: disable=too-many-arguments + self, + url: str, + role: EnergyManagementRole, + control_types: List[S2ControlType], + asset_details: AssetDetails, + reconnect: bool = False, + ) -> None: + self.url = url + self.reconnect = reconnect + self.reception_status_awaiter = ReceptionStatusAwaiter() + self.ws = None + self.s2_parser = S2Parser() + + self._handlers = MessageHandlers() + self._current_control_type = None + + self._eventloop = asyncio.new_event_loop() + + self.control_types = control_types + self.role = role + self.asset_details = asset_details + + self._handlers.register_handler(SelectControlType, self.handle_select_control_type_as_rm) + self._handlers.register_handler(Handshake, self.handle_handshake) + self._handlers.register_handler(HandshakeResponse, self.handle_handshake_response_as_rm) + + def start_as_rm(self) -> None: + self._run_eventloop(self._run_as_rm()) + + def _run_eventloop(self, main_task: Awaitable[None]) -> None: + self._thread = threading.current_thread() + logger.debug("Starting eventloop") + try: + self._eventloop.run_until_complete(main_task) + except asyncio.CancelledError: + pass + logger.debug("S2 connection thread has stopped.") + + def stop(self) -> None: + """Stops the S2 connection. + + Note: Ensure this method is called from a different thread than the thread running the S2 connection. + Otherwise it will block waiting on the coroutine _do_stop to terminate successfully but it can't run + the coroutine. A `RuntimeError` will be raised to prevent the indefinite block. + """ + if threading.current_thread() == self._thread: + raise RuntimeError( + "Do not call stop from the thread running the S2 connection. This results in an " + "infinite block!" + ) + if self._eventloop.is_running(): + asyncio.run_coroutine_threadsafe(self._do_stop(), self._eventloop).result() + self._thread.join() + logger.info("Stopped the S2 connection.") + + async def _do_stop(self) -> None: + logger.info("Will stop the S2 connection.") + self._stop_event.set() + + async def _run_as_rm(self) -> None: + logger.debug("Connecting as S2 resource manager.") + + self._stop_event = asyncio.Event() + + first_run = True + + while (first_run or self.reconnect) and not self._stop_event.is_set(): + first_run = False + self._restart_connection_event = asyncio.Event() + await self._connect_and_run() + time.sleep(1) + + logger.debug("Finished S2 connection eventloop.") + + async def _connect_and_run(self) -> None: + self._received_messages = asyncio.Queue() + await self._connect_ws() + if self.ws: + + async def wait_till_stop() -> None: + await self._stop_event.wait() + + async def wait_till_connection_restart() -> None: + await self._restart_connection_event.wait() + + background_tasks = [ + self._eventloop.create_task(self._receive_messages()), + self._eventloop.create_task(wait_till_stop()), + self._eventloop.create_task(self._connect_as_rm()), + self._eventloop.create_task(wait_till_connection_restart()), + ] + + (done, pending) = await asyncio.wait( + background_tasks, return_when=asyncio.FIRST_COMPLETED + ) + if self._current_control_type: + self._current_control_type.deactivate(self) + self._current_control_type = None + + for task in done: + try: + await task + except asyncio.CancelledError: + pass + except (websockets.ConnectionClosedError, websockets.ConnectionClosedOK): + logger.info("The other party closed the websocket connection.") + + for task in pending: + try: + task.cancel() + await task + except asyncio.CancelledError: + pass + + await self.ws.close() + await self.ws.wait_closed() + + async def _connect_ws(self) -> None: + try: + self.ws = await ws_connect(uri=self.url) + except (EOFError, OSError) as e: + logger.info("Could not connect due to: %s", str(e)) + + async def _connect_as_rm(self) -> None: + await self.send_msg_and_await_reception_status_async( + Handshake( + message_id=uuid.uuid4(), role=self.role, supported_protocol_versions=[S2_VERSION] + ) + ) + logger.debug("Send handshake to CEM. Expecting Handshake and HandshakeResponse from CEM.") + + await self._handle_received_messages() + + async def handle_handshake( + self, _: "S2Connection", message: S2Message, send_okay: Awaitable[None] + ) -> None: + if not isinstance(message, Handshake): + logger.error( + "Handler for Handshake received a message of the wrong type: %s", type(message) + ) + return + + logger.debug( + "%s supports S2 protocol versions: %s", + message.role, + message.supported_protocol_versions, + ) + await send_okay + + async def handle_handshake_response_as_rm( + self, _: "S2Connection", message: S2Message, send_okay: Awaitable[None] + ) -> None: + if not isinstance(message, HandshakeResponse): + logger.error( + "Handler for HandshakeResponse received a message of the wrong type: %s", + type(message), + ) + return + + logger.debug("Received HandshakeResponse %s", message.to_json()) + + logger.debug("CEM selected to use version %s", message.selected_protocol_version) + await send_okay + logger.debug("Handshake complete. Sending first ResourceManagerDetails.") + + await self.send_msg_and_await_reception_status_async( + self.asset_details.to_resource_manager_details(self.control_types) + ) + + async def handle_select_control_type_as_rm( + self, _: "S2Connection", message: S2Message, send_okay: Awaitable[None] + ) -> None: + if not isinstance(message, SelectControlType): + logger.error( + "Handler for SelectControlType received a message of the wrong type: %s", + type(message), + ) + return + + await send_okay + + logger.debug("CEM selected control type %s. Activating control type.", message.control_type) + + control_types_by_protocol_name = { + c.get_protocol_control_type(): c for c in self.control_types + } + selected_control_type: Optional[S2ControlType] = control_types_by_protocol_name.get( + message.control_type + ) + + if self._current_control_type is not None: + await self._eventloop.run_in_executor(None, self._current_control_type.deactivate, self) + + self._current_control_type = selected_control_type + + if self._current_control_type is not None: + await self._eventloop.run_in_executor(None, self._current_control_type.activate, self) + self._current_control_type.register_handlers(self._handlers) + + async def _receive_messages(self) -> None: + """Receives all incoming messages in the form of a generator. + + Will also receive the ReceptionStatus messages but instead of yielding these messages, they are routed + to any calls of `send_msg_and_await_reception_status`. + """ + if self.ws is None: + raise RuntimeError( + "Cannot receive messages if websocket connection is not yet established." + ) + + logger.info("S2 connection has started to receive messages.") + + async for message in self.ws: + try: + s2_msg: S2Message = self.s2_parser.parse_as_any_message(message) + except json.JSONDecodeError: + await self._send_and_forget( + ReceptionStatus( + subject_message_id="00000000-0000-0000-0000-000000000000", + status=ReceptionStatusValues.INVALID_DATA, + diagnostic_label="Not valid json.", + ) + ) + except S2ValidationError as e: + json_msg = json.loads(message) + message_id = json_msg.get("message_id") + if message_id: + await self.respond_with_reception_status( + subject_message_id=message_id, + status=ReceptionStatusValues.INVALID_MESSAGE, + diagnostic_label=str(e), + ) + else: + await self.respond_with_reception_status( + subject_message_id="00000000-0000-0000-0000-000000000000", + status=ReceptionStatusValues.INVALID_DATA, + diagnostic_label="Message appears valid json but could not find a message_id field.", + ) + else: + logger.debug("Received message %s", s2_msg.to_json()) + + if isinstance(s2_msg, ReceptionStatus): + logger.debug( + "Message is a reception status for %s so registering in cache.", + s2_msg.subject_message_id, + ) + await self.reception_status_awaiter.receive_reception_status(s2_msg) + else: + await self._received_messages.put(s2_msg) + + async def _send_and_forget(self, s2_msg: S2Message) -> None: + if self.ws is None: + raise RuntimeError( + "Cannot send messages if websocket connection is not yet established." + ) + + json_msg = s2_msg.to_json() + logger.debug("Sending message %s", json_msg) + try: + await self.ws.send(json_msg) + except websockets.ConnectionClosedError as e: + logger.error("Unable to send message %s due to %s", s2_msg, str(e)) + self._restart_connection_event.set() + + async def respond_with_reception_status( + self, subject_message_id: str, status: ReceptionStatusValues, diagnostic_label: str + ) -> None: + logger.debug("Responding to message %s with status %s", subject_message_id, status) + await self._send_and_forget( + ReceptionStatus( + subject_message_id=subject_message_id, + status=status, + diagnostic_label=diagnostic_label, + ) + ) + + def respond_with_reception_status_sync( + self, subject_message_id: str, status: ReceptionStatusValues, diagnostic_label: str + ) -> None: + asyncio.run_coroutine_threadsafe( + self.respond_with_reception_status(subject_message_id, status, diagnostic_label), + self._eventloop, + ).result() + + async def send_msg_and_await_reception_status_async( + self, s2_msg: S2Message, timeout_reception_status: float = 5.0, raise_on_error: bool = True + ) -> ReceptionStatus: + await self._send_and_forget(s2_msg) + logger.debug( + "Waiting for ReceptionStatus for %s %s seconds", + s2_msg.message_id, # type: ignore[attr-defined] + timeout_reception_status, + ) + try: + reception_status = await self.reception_status_awaiter.wait_for_reception_status( + s2_msg.message_id, timeout_reception_status # type: ignore[attr-defined] + ) + except TimeoutError: + logger.error( + "Did not receive a reception status on time for %s", + s2_msg.message_id, # type: ignore[attr-defined] + ) + self._stop_event.set() + raise + + if reception_status.status != ReceptionStatusValues.OK and raise_on_error: + raise RuntimeError(f"ReceptionStatus was not OK but rather {reception_status.status}") + + return reception_status + + def send_msg_and_await_reception_status_sync( + self, s2_msg: S2Message, timeout_reception_status: float = 5.0, raise_on_error: bool = True + ) -> ReceptionStatus: + return asyncio.run_coroutine_threadsafe( + self.send_msg_and_await_reception_status_async( + s2_msg, timeout_reception_status, raise_on_error + ), + self._eventloop, + ).result() + + async def _handle_received_messages(self) -> None: + while True: + msg = await self._received_messages.get() + await self._handlers.handle_message(self, msg) diff --git a/build/lib/s2python/s2_control_type.py b/build/lib/s2python/s2_control_type.py new file mode 100644 index 0000000..f9a4545 --- /dev/null +++ b/build/lib/s2python/s2_control_type.py @@ -0,0 +1,56 @@ +import abc +import typing + +from s2python.common import ControlType as ProtocolControlType +from s2python.frbc import FRBCInstruction +from s2python.validate_values_mixin import S2Message + +if typing.TYPE_CHECKING: + from s2python.s2_connection import S2Connection, MessageHandlers + + +class S2ControlType(abc.ABC): + @abc.abstractmethod + def get_protocol_control_type(self) -> ProtocolControlType: ... + + @abc.abstractmethod + def register_handlers(self, handlers: "MessageHandlers") -> None: ... + + @abc.abstractmethod + def activate(self, conn: "S2Connection") -> None: ... + + @abc.abstractmethod + def deactivate(self, conn: "S2Connection") -> None: ... + + +class FRBCControlType(S2ControlType): + def get_protocol_control_type(self) -> ProtocolControlType: + return ProtocolControlType.FILL_RATE_BASED_CONTROL + + def register_handlers(self, handlers: "MessageHandlers") -> None: + handlers.register_handler(FRBCInstruction, self.handle_instruction) + + @abc.abstractmethod + def handle_instruction( + self, conn: "S2Connection", msg: S2Message, send_okay: typing.Callable[[], None] + ) -> None: ... + + @abc.abstractmethod + def activate(self, conn: "S2Connection") -> None: ... + + @abc.abstractmethod + def deactivate(self, conn: "S2Connection") -> None: ... + + +class NoControlControlType(S2ControlType): + def get_protocol_control_type(self) -> ProtocolControlType: + return ProtocolControlType.NOT_CONTROLABLE + + def register_handlers(self, handlers: "MessageHandlers") -> None: + pass + + @abc.abstractmethod + def activate(self, conn: "S2Connection") -> None: ... + + @abc.abstractmethod + def deactivate(self, conn: "S2Connection") -> None: ... diff --git a/build/lib/s2python/s2_parser.py b/build/lib/s2python/s2_parser.py new file mode 100644 index 0000000..906a286 --- /dev/null +++ b/build/lib/s2python/s2_parser.py @@ -0,0 +1,113 @@ +import json +import logging +from typing import Optional, TypeVar, Union, Type, Dict + +from s2python.common import ( + Handshake, + HandshakeResponse, + InstructionStatusUpdate, + PowerForecast, + PowerMeasurement, + ReceptionStatus, + ResourceManagerDetails, + RevokeObject, + SelectControlType, + SessionRequest, +) +from s2python.frbc import ( + FRBCActuatorStatus, + FRBCFillLevelTargetProfile, + FRBCInstruction, + FRBCLeakageBehaviour, + FRBCStorageStatus, + FRBCSystemDescription, + FRBCTimerStatus, + FRBCUsageForecast, +) +from s2python.validate_values_mixin import S2Message +from s2python.s2_validation_error import S2ValidationError + + +LOGGER = logging.getLogger(__name__) +S2MessageType = str + +M = TypeVar("M", bound=S2Message) + + +# May be generated with development_utilities/generate_s2_message_type_to_class.py +TYPE_TO_MESSAGE_CLASS: Dict[str, Type[S2Message]] = { + "FRBC.ActuatorStatus": FRBCActuatorStatus, + "FRBC.FillLevelTargetProfile": FRBCFillLevelTargetProfile, + "FRBC.Instruction": FRBCInstruction, + "FRBC.LeakageBehaviour": FRBCLeakageBehaviour, + "FRBC.StorageStatus": FRBCStorageStatus, + "FRBC.SystemDescription": FRBCSystemDescription, + "FRBC.TimerStatus": FRBCTimerStatus, + "FRBC.UsageForecast": FRBCUsageForecast, + "Handshake": Handshake, + "HandshakeResponse": HandshakeResponse, + "InstructionStatusUpdate": InstructionStatusUpdate, + "PowerForecast": PowerForecast, + "PowerMeasurement": PowerMeasurement, + "ReceptionStatus": ReceptionStatus, + "ResourceManagerDetails": ResourceManagerDetails, + "RevokeObject": RevokeObject, + "SelectControlType": SelectControlType, + "SessionRequest": SessionRequest, +} + + +class S2Parser: + @staticmethod + def _parse_json_if_required(unparsed_message: Union[dict, str, bytes]) -> dict: + if isinstance(unparsed_message, (str, bytes)): + return json.loads(unparsed_message) + return unparsed_message + + @staticmethod + def parse_as_any_message(unparsed_message: Union[dict, str, bytes]) -> S2Message: + """Parse the message as any S2 python message regardless of message type. + + :param unparsed_message: The message as a JSON-formatted string or as a json-parsed dictionary. + :raises: S2ValidationError, json.JSONDecodeError + :return: The parsed S2 message if no errors were found. + """ + message_json = S2Parser._parse_json_if_required(unparsed_message) + message_type = S2Parser.parse_message_type(message_json) + + if message_type not in TYPE_TO_MESSAGE_CLASS: + raise S2ValidationError( + None, + message_json, + f"Unable to parse {message_type} as an S2 message. Type unknown.", + None, + ) + + return TYPE_TO_MESSAGE_CLASS[message_type].model_validate(message_json) + + @staticmethod + def parse_as_message(unparsed_message: Union[dict, str, bytes], as_message: Type[M]) -> M: + """Parse the message to a specific S2 python message. + + :param unparsed_message: The message as a JSON-formatted string or as a JSON-parsed dictionary. + :param as_message: The type of message that is expected within the `message` + :raises: S2ValidationError, json.JSONDecodeError + :return: The parsed S2 message if no errors were found. + """ + message_json = S2Parser._parse_json_if_required(unparsed_message) + return as_message.from_dict(message_json) + + @staticmethod + def parse_message_type(unparsed_message: Union[dict, str, bytes]) -> Optional[S2MessageType]: + """Parse only the message type from the unparsed message. + + This is useful to call before `parse_as_message` to retrieve the message type and allows for strictly-typed + parsing. + + :param unparsed_message: The message as a JSON-formatted string or as a JSON-parsed dictionary. + :raises: json.JSONDecodeError + :return: The parsed S2 message type if no errors were found. + """ + message_json = S2Parser._parse_json_if_required(unparsed_message) + + return message_json.get("message_type") diff --git a/build/lib/s2python/s2_validation_error.py b/build/lib/s2python/s2_validation_error.py new file mode 100644 index 0000000..8ab7664 --- /dev/null +++ b/build/lib/s2python/s2_validation_error.py @@ -0,0 +1,13 @@ +from dataclasses import dataclass +from typing import Union, Type, Optional + +from pydantic import ValidationError +from pydantic.v1.error_wrappers import ValidationError as ValidationErrorV1 + + +@dataclass +class S2ValidationError(Exception): + class_: Optional[Type] + obj: object + msg: str + pydantic_validation_error: Union[ValidationErrorV1, ValidationError, TypeError, None] diff --git a/build/lib/s2python/utils.py b/build/lib/s2python/utils.py new file mode 100644 index 0000000..b4f78ed --- /dev/null +++ b/build/lib/s2python/utils.py @@ -0,0 +1,8 @@ +from typing import Generator, Tuple, List, TypeVar + +P = TypeVar("P") + + +def pairwise(arr: List[P]) -> Generator[Tuple[P, P], None, None]: + for i in range(max(len(arr) - 1, 0)): + yield arr[i], arr[i + 1] diff --git a/build/lib/s2python/validate_values_mixin.py b/build/lib/s2python/validate_values_mixin.py new file mode 100644 index 0000000..7d0d9d6 --- /dev/null +++ b/build/lib/s2python/validate_values_mixin.py @@ -0,0 +1,70 @@ +from typing import TypeVar, Generic, Type, Callable, Any, Union, AbstractSet, Mapping, List, Dict + +from pydantic import BaseModel, ValidationError # pylint: disable=no-name-in-module +from pydantic.v1.error_wrappers import display_errors # pylint: disable=no-name-in-module + +from s2python.s2_validation_error import S2ValidationError + +B_co = TypeVar("B_co", bound=BaseModel, covariant=True) + +IntStr = Union[int, str] +AbstractSetIntStr = AbstractSet[IntStr] +MappingIntStrAny = Mapping[IntStr, Any] + + +C = TypeVar("C", bound="BaseModel") + + +class S2Message(BaseModel, Generic[C]): + def to_json(self: C) -> str: + try: + return self.model_dump_json(by_alias=True, exclude_none=True) + except (ValidationError, TypeError) as e: + raise S2ValidationError( + type(self), self, "Pydantic raised a format validation error.", e + ) from e + + def to_dict(self: C) -> Dict: + return self.model_dump() + + @classmethod + def from_json(cls: Type[C], json_str: str) -> C: + gen_model: C = cls.model_validate_json(json_str) + return gen_model + + @classmethod + def from_dict(cls: Type[C], json_dict: dict) -> C: + gen_model: C = cls.model_validate(json_dict) + return gen_model + + +def convert_to_s2exception(f: Callable) -> Callable: + def inner(*args: List[Any], **kwargs: Dict[str, Any]) -> Any: + try: + return f(*args, **kwargs) + except ValidationError as e: + if isinstance(args[0], BaseModel): + class_type = type(args[0]) + args = args[1:] + else: + class_type = None + + raise S2ValidationError(class_type, args, display_errors(e.errors()), e) from e # type: ignore[arg-type] + except TypeError as e: + raise S2ValidationError(None, args, str(e), e) from e + + inner.__doc__ = f.__doc__ + inner.__annotations__ = f.__annotations__ + + return inner + + +def catch_and_convert_exceptions(input_class: Type[S2Message[B_co]]) -> Type[S2Message[B_co]]: + input_class.__init__ = convert_to_s2exception(input_class.__init__) # type: ignore[method-assign] + input_class.__setattr__ = convert_to_s2exception(input_class.__setattr__) # type: ignore[method-assign] + input_class.model_validate_json = convert_to_s2exception( # type: ignore[method-assign] + input_class.model_validate_json + ) + input_class.model_validate = convert_to_s2exception(input_class.model_validate) # type: ignore[method-assign] + + return input_class diff --git a/build/lib/s2python/version.py b/build/lib/s2python/version.py new file mode 100644 index 0000000..3789fe8 --- /dev/null +++ b/build/lib/s2python/version.py @@ -0,0 +1,3 @@ +VERSION = "0.2.0" + +S2_VERSION = "0.0.2-beta" diff --git a/src/s2python/ombc/ombc_operation_mode.py b/src/s2python/ombc/ombc_operation_mode.py index 75d3d9d..9f11438 100644 --- a/src/s2python/ombc/ombc_operation_mode.py +++ b/src/s2python/ombc/ombc_operation_mode.py @@ -17,5 +17,9 @@ class OMBCOperationMode(GenOMBCOperationMode, S2Message["OMBCOperationMode"]): model_config["validate_assignment"] = True id: uuid.UUID = GenOMBCOperationMode.model_fields["id"] # type: ignore[assignment] - power_ranges: List[PowerRange] = GenOMBCOperationMode.model_fields["power_ranges"] # type: ignore[assignment] - abnormal_condition_only: bool = GenOMBCOperationMode.model_fields["abnormal_condition_only"] # type: ignore[assignment] + power_ranges: List[PowerRange] = GenOMBCOperationMode.model_fields[ + "power_ranges" + ] # type: ignore[assignment] + abnormal_condition_only: bool = GenOMBCOperationMode.model_fields[ + "abnormal_condition_only" + ] # type: ignore[assignment] diff --git a/src/s2python/ombc/ombc_system_description.py b/src/s2python/ombc/ombc_system_description.py index aa9c69e..f2d31bd 100644 --- a/src/s2python/ombc/ombc_system_description.py +++ b/src/s2python/ombc/ombc_system_description.py @@ -20,6 +20,8 @@ class OMBCSystemDescription( model_config["validate_assignment"] = True message_id: uuid.UUID = GenOMBCSystemDescription.model_fields["message_id"] # type: ignore[assignment] - operation_modes: List[OMBCOperationMode] = GenOMBCSystemDescription.model_fields["operation_modes"] # type: ignore[assignment] + operation_modes: List[OMBCOperationMode] = GenOMBCSystemDescription.model_fields[ + "operation_modes" + ] # type: ignore[assignment] transitions: List[Transition] = GenOMBCSystemDescription.model_fields["transitions"] # type: ignore[assignment] timers: List[Timer] = GenOMBCSystemDescription.model_fields["timers"] # type: ignore[assignment] From e803e52ea0198819cf35ded722d75134ba96649c Mon Sep 17 00:00:00 2001 From: Vlad Iftime Date: Tue, 7 Jan 2025 23:16:52 +0100 Subject: [PATCH 04/14] Removed the build folder --- .gitignore | 2 + build/lib/s2python/__init__.py | 10 - build/lib/s2python/common/__init__.py | 32 - build/lib/s2python/common/duration.py | 22 - build/lib/s2python/common/handshake.py | 15 - .../lib/s2python/common/handshake_response.py | 15 - .../common/instruction_status_update.py | 18 - build/lib/s2python/common/number_range.py | 22 - build/lib/s2python/common/power_forecast.py | 18 - .../s2python/common/power_forecast_element.py | 20 - .../s2python/common/power_forecast_value.py | 11 - .../lib/s2python/common/power_measurement.py | 18 - build/lib/s2python/common/power_range.py | 22 - build/lib/s2python/common/power_value.py | 11 - build/lib/s2python/common/reception_status.py | 15 - .../common/resource_manager_details.py | 25 - build/lib/s2python/common/revoke_object.py | 16 - build/lib/s2python/common/role.py | 11 - .../s2python/common/select_control_type.py | 15 - build/lib/s2python/common/session_request.py | 15 - build/lib/s2python/common/support.py | 27 - build/lib/s2python/common/timer.py | 17 - build/lib/s2python/common/transition.py | 24 - build/lib/s2python/frbc/__init__.py | 17 - .../frbc/frbc_actuator_description.py | 143 -- .../lib/s2python/frbc/frbc_actuator_status.py | 23 - .../frbc/frbc_fill_level_target_profile.py | 24 - .../frbc_fill_level_target_profile_element.py | 34 - build/lib/s2python/frbc/frbc_instruction.py | 18 - .../s2python/frbc/frbc_leakage_behaviour.py | 20 - .../frbc/frbc_leakage_behaviour_element.py | 30 - .../lib/s2python/frbc/frbc_operation_mode.py | 42 - .../frbc/frbc_operation_mode_element.py | 27 - .../s2python/frbc/frbc_storage_description.py | 18 - .../lib/s2python/frbc/frbc_storage_status.py | 15 - .../s2python/frbc/frbc_system_description.py | 22 - build/lib/s2python/frbc/frbc_timer_status.py | 17 - .../lib/s2python/frbc/frbc_usage_forecast.py | 18 - .../frbc/frbc_usage_forecast_element.py | 17 - build/lib/s2python/frbc/rm.py | 0 build/lib/s2python/generated/__init__.py | 0 build/lib/s2python/generated/gen_s2.py | 1611 ----------------- build/lib/s2python/py.typed | 0 .../lib/s2python/reception_status_awaiter.py | 60 - build/lib/s2python/s2_connection.py | 526 ------ build/lib/s2python/s2_control_type.py | 56 - build/lib/s2python/s2_parser.py | 113 -- build/lib/s2python/s2_validation_error.py | 13 - build/lib/s2python/utils.py | 8 - build/lib/s2python/validate_values_mixin.py | 70 - build/lib/s2python/version.py | 3 - 51 files changed, 2 insertions(+), 3344 deletions(-) delete mode 100644 build/lib/s2python/__init__.py delete mode 100644 build/lib/s2python/common/__init__.py delete mode 100644 build/lib/s2python/common/duration.py delete mode 100644 build/lib/s2python/common/handshake.py delete mode 100644 build/lib/s2python/common/handshake_response.py delete mode 100644 build/lib/s2python/common/instruction_status_update.py delete mode 100644 build/lib/s2python/common/number_range.py delete mode 100644 build/lib/s2python/common/power_forecast.py delete mode 100644 build/lib/s2python/common/power_forecast_element.py delete mode 100644 build/lib/s2python/common/power_forecast_value.py delete mode 100644 build/lib/s2python/common/power_measurement.py delete mode 100644 build/lib/s2python/common/power_range.py delete mode 100644 build/lib/s2python/common/power_value.py delete mode 100644 build/lib/s2python/common/reception_status.py delete mode 100644 build/lib/s2python/common/resource_manager_details.py delete mode 100644 build/lib/s2python/common/revoke_object.py delete mode 100644 build/lib/s2python/common/role.py delete mode 100644 build/lib/s2python/common/select_control_type.py delete mode 100644 build/lib/s2python/common/session_request.py delete mode 100644 build/lib/s2python/common/support.py delete mode 100644 build/lib/s2python/common/timer.py delete mode 100644 build/lib/s2python/common/transition.py delete mode 100644 build/lib/s2python/frbc/__init__.py delete mode 100644 build/lib/s2python/frbc/frbc_actuator_description.py delete mode 100644 build/lib/s2python/frbc/frbc_actuator_status.py delete mode 100644 build/lib/s2python/frbc/frbc_fill_level_target_profile.py delete mode 100644 build/lib/s2python/frbc/frbc_fill_level_target_profile_element.py delete mode 100644 build/lib/s2python/frbc/frbc_instruction.py delete mode 100644 build/lib/s2python/frbc/frbc_leakage_behaviour.py delete mode 100644 build/lib/s2python/frbc/frbc_leakage_behaviour_element.py delete mode 100644 build/lib/s2python/frbc/frbc_operation_mode.py delete mode 100644 build/lib/s2python/frbc/frbc_operation_mode_element.py delete mode 100644 build/lib/s2python/frbc/frbc_storage_description.py delete mode 100644 build/lib/s2python/frbc/frbc_storage_status.py delete mode 100644 build/lib/s2python/frbc/frbc_system_description.py delete mode 100644 build/lib/s2python/frbc/frbc_timer_status.py delete mode 100644 build/lib/s2python/frbc/frbc_usage_forecast.py delete mode 100644 build/lib/s2python/frbc/frbc_usage_forecast_element.py delete mode 100644 build/lib/s2python/frbc/rm.py delete mode 100644 build/lib/s2python/generated/__init__.py delete mode 100644 build/lib/s2python/generated/gen_s2.py delete mode 100644 build/lib/s2python/py.typed delete mode 100644 build/lib/s2python/reception_status_awaiter.py delete mode 100644 build/lib/s2python/s2_connection.py delete mode 100644 build/lib/s2python/s2_control_type.py delete mode 100644 build/lib/s2python/s2_parser.py delete mode 100644 build/lib/s2python/s2_validation_error.py delete mode 100644 build/lib/s2python/utils.py delete mode 100644 build/lib/s2python/validate_values_mixin.py delete mode 100644 build/lib/s2python/version.py diff --git a/.gitignore b/.gitignore index 14a680a..c5ed605 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,5 @@ venv *venv* .tox/ dist/ +build/ + diff --git a/build/lib/s2python/__init__.py b/build/lib/s2python/__init__.py deleted file mode 100644 index 0ab0a42..0000000 --- a/build/lib/s2python/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -from importlib.metadata import PackageNotFoundError, version # pragma: no cover - -try: - # Change here if project is renamed and does not equal the package name - dist_name = "s2-python" # pylint: disable=invalid-name - __version__ = version(dist_name) -except PackageNotFoundError: # pragma: no cover - __version__ = "unknown" -finally: - del version, PackageNotFoundError diff --git a/build/lib/s2python/common/__init__.py b/build/lib/s2python/common/__init__.py deleted file mode 100644 index 806de7e..0000000 --- a/build/lib/s2python/common/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -from s2python.generated.gen_s2 import ( - RoleType, - Currency, - CommodityQuantity, - Commodity, - InstructionStatus, - ReceptionStatusValues, - EnergyManagementRole, - SessionRequestType, - ControlType, - RevokableObjects, -) - -from s2python.common.duration import Duration -from s2python.common.role import Role -from s2python.common.handshake import Handshake -from s2python.common.handshake_response import HandshakeResponse -from s2python.common.instruction_status_update import InstructionStatusUpdate -from s2python.common.number_range import NumberRange -from s2python.common.power_forecast_value import PowerForecastValue -from s2python.common.power_forecast_element import PowerForecastElement -from s2python.common.power_forecast import PowerForecast -from s2python.common.power_value import PowerValue -from s2python.common.power_measurement import PowerMeasurement -from s2python.common.power_range import PowerRange -from s2python.common.reception_status import ReceptionStatus -from s2python.common.resource_manager_details import ResourceManagerDetails -from s2python.common.revoke_object import RevokeObject -from s2python.common.select_control_type import SelectControlType -from s2python.common.session_request import SessionRequest -from s2python.common.timer import Timer -from s2python.common.transition import Transition diff --git a/build/lib/s2python/common/duration.py b/build/lib/s2python/common/duration.py deleted file mode 100644 index 65663c0..0000000 --- a/build/lib/s2python/common/duration.py +++ /dev/null @@ -1,22 +0,0 @@ -from datetime import timedelta -import math - -from s2python.generated.gen_s2 import Duration as GenDuration -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class Duration(GenDuration, S2Message["Duration"]): - def to_timedelta(self) -> timedelta: - return timedelta(milliseconds=self.root) - - @staticmethod - def from_timedelta(duration: timedelta) -> "Duration": - return Duration(root=math.ceil(duration.total_seconds() * 1000)) - - @staticmethod - def from_milliseconds(milliseconds: int) -> "Duration": - return Duration(root=milliseconds) diff --git a/build/lib/s2python/common/handshake.py b/build/lib/s2python/common/handshake.py deleted file mode 100644 index c068150..0000000 --- a/build/lib/s2python/common/handshake.py +++ /dev/null @@ -1,15 +0,0 @@ -import uuid - -from s2python.generated.gen_s2 import Handshake as GenHandshake -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class Handshake(GenHandshake, S2Message["Handshake"]): - model_config = GenHandshake.model_config - model_config["validate_assignment"] = True - - message_id: uuid.UUID = GenHandshake.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/handshake_response.py b/build/lib/s2python/common/handshake_response.py deleted file mode 100644 index fcc2eb5..0000000 --- a/build/lib/s2python/common/handshake_response.py +++ /dev/null @@ -1,15 +0,0 @@ -import uuid - -from s2python.generated.gen_s2 import HandshakeResponse as GenHandshakeResponse -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class HandshakeResponse(GenHandshakeResponse, S2Message["HandshakeResponse"]): - model_config = GenHandshakeResponse.model_config - model_config["validate_assignment"] = True - - message_id: uuid.UUID = GenHandshakeResponse.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/instruction_status_update.py b/build/lib/s2python/common/instruction_status_update.py deleted file mode 100644 index 5a8c45f..0000000 --- a/build/lib/s2python/common/instruction_status_update.py +++ /dev/null @@ -1,18 +0,0 @@ -import uuid - -from s2python.generated.gen_s2 import ( - InstructionStatusUpdate as GenInstructionStatusUpdate, -) -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class InstructionStatusUpdate(GenInstructionStatusUpdate, S2Message["InstructionStatusUpdate"]): - model_config = GenInstructionStatusUpdate.model_config - model_config["validate_assignment"] = True - - message_id: uuid.UUID = GenInstructionStatusUpdate.model_fields["message_id"] # type: ignore[assignment] - instruction_id: uuid.UUID = GenInstructionStatusUpdate.model_fields["instruction_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/number_range.py b/build/lib/s2python/common/number_range.py deleted file mode 100644 index 070b74a..0000000 --- a/build/lib/s2python/common/number_range.py +++ /dev/null @@ -1,22 +0,0 @@ -from typing import Any - -from s2python.validate_values_mixin import S2Message, catch_and_convert_exceptions -from s2python.generated.gen_s2 import NumberRange as GenNumberRange - - -@catch_and_convert_exceptions -class NumberRange(GenNumberRange, S2Message["NumberRange"]): - model_config = GenNumberRange.model_config - model_config["validate_assignment"] = True - - def __hash__(self) -> int: - return hash(f"{self.start_of_range}|{self.end_of_range}") - - def __eq__(self, other: Any) -> bool: - if isinstance(other, NumberRange): - return ( - self.start_of_range == other.start_of_range - and self.end_of_range == other.end_of_range - ) - - return False diff --git a/build/lib/s2python/common/power_forecast.py b/build/lib/s2python/common/power_forecast.py deleted file mode 100644 index 31c595d..0000000 --- a/build/lib/s2python/common/power_forecast.py +++ /dev/null @@ -1,18 +0,0 @@ -from typing import List -import uuid - -from s2python.common.power_forecast_element import PowerForecastElement -from s2python.generated.gen_s2 import PowerForecast as GenPowerForecast -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class PowerForecast(GenPowerForecast, S2Message["PowerForecast"]): - model_config = GenPowerForecast.model_config - model_config["validate_assignment"] = True - - message_id: uuid.UUID = GenPowerForecast.model_fields["message_id"] # type: ignore[assignment] - elements: List[PowerForecastElement] = GenPowerForecast.model_fields["elements"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/power_forecast_element.py b/build/lib/s2python/common/power_forecast_element.py deleted file mode 100644 index 10460f7..0000000 --- a/build/lib/s2python/common/power_forecast_element.py +++ /dev/null @@ -1,20 +0,0 @@ -from typing import List - -from s2python.generated.gen_s2 import PowerForecastElement as GenPowerForecastElement -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) -from s2python.common.duration import Duration -from s2python.common.power_forecast_value import PowerForecastValue - - -@catch_and_convert_exceptions -class PowerForecastElement(GenPowerForecastElement, S2Message["PowerForecastElement"]): - model_config = GenPowerForecastElement.model_config - model_config["validate_assignment"] = True - - duration: Duration = GenPowerForecastElement.model_fields["duration"] # type: ignore[assignment] - power_values: List[PowerForecastValue] = GenPowerForecastElement.model_fields[ - "power_values" - ] # type: ignore[assignment] diff --git a/build/lib/s2python/common/power_forecast_value.py b/build/lib/s2python/common/power_forecast_value.py deleted file mode 100644 index 3ee2cc3..0000000 --- a/build/lib/s2python/common/power_forecast_value.py +++ /dev/null @@ -1,11 +0,0 @@ -from s2python.generated.gen_s2 import PowerForecastValue as GenPowerForecastValue -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class PowerForecastValue(GenPowerForecastValue, S2Message["PowerForecastValue"]): - model_config = GenPowerForecastValue.model_config - model_config["validate_assignment"] = True diff --git a/build/lib/s2python/common/power_measurement.py b/build/lib/s2python/common/power_measurement.py deleted file mode 100644 index 27896c9..0000000 --- a/build/lib/s2python/common/power_measurement.py +++ /dev/null @@ -1,18 +0,0 @@ -from typing import List -import uuid - -from s2python.common.power_value import PowerValue -from s2python.generated.gen_s2 import PowerMeasurement as GenPowerMeasurement -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class PowerMeasurement(GenPowerMeasurement, S2Message["PowerMeasurement"]): - model_config = GenPowerMeasurement.model_config - model_config["validate_assignment"] = True - - message_id: uuid.UUID = GenPowerMeasurement.model_fields["message_id"] # type: ignore[assignment] - values: List[PowerValue] = GenPowerMeasurement.model_fields["values"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/power_range.py b/build/lib/s2python/common/power_range.py deleted file mode 100644 index 4ca1ec8..0000000 --- a/build/lib/s2python/common/power_range.py +++ /dev/null @@ -1,22 +0,0 @@ -from typing_extensions import Self - -from pydantic import model_validator - -from s2python.generated.gen_s2 import PowerRange as GenPowerRange -from s2python.validate_values_mixin import ( - S2Message, - catch_and_convert_exceptions, -) - - -@catch_and_convert_exceptions -class PowerRange(GenPowerRange, S2Message["PowerRange"]): - model_config = GenPowerRange.model_config - model_config["validate_assignment"] = True - - @model_validator(mode="after") - def validate_start_end_order(self) -> Self: - if self.start_of_range > self.end_of_range: - raise ValueError(self, "start_of_range should not be higher than end_of_range") - - return self diff --git a/build/lib/s2python/common/power_value.py b/build/lib/s2python/common/power_value.py deleted file mode 100644 index c623627..0000000 --- a/build/lib/s2python/common/power_value.py +++ /dev/null @@ -1,11 +0,0 @@ -from s2python.generated.gen_s2 import PowerValue as GenPowerValue -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class PowerValue(GenPowerValue, S2Message["PowerValue"]): - model_config = GenPowerValue.model_config - model_config["validate_assignment"] = True diff --git a/build/lib/s2python/common/reception_status.py b/build/lib/s2python/common/reception_status.py deleted file mode 100644 index a759897..0000000 --- a/build/lib/s2python/common/reception_status.py +++ /dev/null @@ -1,15 +0,0 @@ -import uuid - -from s2python.generated.gen_s2 import ReceptionStatus as GenReceptionStatus -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class ReceptionStatus(GenReceptionStatus, S2Message["ReceptionStatus"]): - model_config = GenReceptionStatus.model_config - model_config["validate_assignment"] = True - - subject_message_id: uuid.UUID = GenReceptionStatus.model_fields["subject_message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/resource_manager_details.py b/build/lib/s2python/common/resource_manager_details.py deleted file mode 100644 index 82ce844..0000000 --- a/build/lib/s2python/common/resource_manager_details.py +++ /dev/null @@ -1,25 +0,0 @@ -from typing import List -import uuid - -from s2python.common.duration import Duration -from s2python.common.role import Role -from s2python.generated.gen_s2 import ( - ResourceManagerDetails as GenResourceManagerDetails, -) -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class ResourceManagerDetails(GenResourceManagerDetails, S2Message["ResourceManagerDetails"]): - model_config = GenResourceManagerDetails.model_config - model_config["validate_assignment"] = True - - instruction_processing_delay: Duration = GenResourceManagerDetails.model_fields[ - "instruction_processing_delay" - ] # type: ignore[assignment] - message_id: uuid.UUID = GenResourceManagerDetails.model_fields["message_id"] # type: ignore[assignment] - resource_id: uuid.UUID = GenResourceManagerDetails.model_fields["resource_id"] # type: ignore[assignment] - roles: List[Role] = GenResourceManagerDetails.model_fields["roles"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/revoke_object.py b/build/lib/s2python/common/revoke_object.py deleted file mode 100644 index d133c79..0000000 --- a/build/lib/s2python/common/revoke_object.py +++ /dev/null @@ -1,16 +0,0 @@ -import uuid - -from s2python.generated.gen_s2 import RevokeObject as GenRevokeObject -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class RevokeObject(GenRevokeObject, S2Message["RevokeObject"]): - model_config = GenRevokeObject.model_config - model_config["validate_assignment"] = True - - message_id: uuid.UUID = GenRevokeObject.model_fields["message_id"] # type: ignore[assignment] - object_id: uuid.UUID = GenRevokeObject.model_fields["object_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/role.py b/build/lib/s2python/common/role.py deleted file mode 100644 index 4a3d3ef..0000000 --- a/build/lib/s2python/common/role.py +++ /dev/null @@ -1,11 +0,0 @@ -from s2python.generated.gen_s2 import Role as GenRole -from s2python.validate_values_mixin import ( - S2Message, - catch_and_convert_exceptions, -) - - -@catch_and_convert_exceptions -class Role(GenRole, S2Message["Role"]): - model_config = GenRole.model_config - model_config["validate_assignment"] = True diff --git a/build/lib/s2python/common/select_control_type.py b/build/lib/s2python/common/select_control_type.py deleted file mode 100644 index 5f02954..0000000 --- a/build/lib/s2python/common/select_control_type.py +++ /dev/null @@ -1,15 +0,0 @@ -import uuid - -from s2python.generated.gen_s2 import SelectControlType as GenSelectControlType -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class SelectControlType(GenSelectControlType, S2Message["SelectControlType"]): - model_config = GenSelectControlType.model_config - model_config["validate_assignment"] = True - - message_id: uuid.UUID = GenSelectControlType.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/session_request.py b/build/lib/s2python/common/session_request.py deleted file mode 100644 index f962427..0000000 --- a/build/lib/s2python/common/session_request.py +++ /dev/null @@ -1,15 +0,0 @@ -import uuid - -from s2python.generated.gen_s2 import SessionRequest as GenSessionRequest -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class SessionRequest(GenSessionRequest, S2Message["SessionRequest"]): - model_config = GenSessionRequest.model_config - model_config["validate_assignment"] = True - - message_id: uuid.UUID = GenSessionRequest.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/support.py b/build/lib/s2python/common/support.py deleted file mode 100644 index 027f65b..0000000 --- a/build/lib/s2python/common/support.py +++ /dev/null @@ -1,27 +0,0 @@ -from s2python.common import CommodityQuantity, Commodity - - -def commodity_has_quantity(commodity: "Commodity", quantity: CommodityQuantity) -> bool: - if commodity == Commodity.HEAT: - result = quantity in [ - CommodityQuantity.HEAT_THERMAL_POWER, - CommodityQuantity.HEAT_TEMPERATURE, - CommodityQuantity.HEAT_FLOW_RATE, - ] - elif commodity == Commodity.ELECTRICITY: - result = quantity in [ - CommodityQuantity.ELECTRIC_POWER_3_PHASE_SYMMETRIC, - CommodityQuantity.ELECTRIC_POWER_L1, - CommodityQuantity.ELECTRIC_POWER_L2, - CommodityQuantity.ELECTRIC_POWER_L3, - ] - elif commodity == Commodity.GAS: - result = quantity in [CommodityQuantity.NATURAL_GAS_FLOW_RATE] - elif commodity == Commodity.OIL: - result = quantity in [CommodityQuantity.OIL_FLOW_RATE] - else: - raise RuntimeError( - f"Unsupported commodity {commodity}. Missing implementation." - ) - - return result diff --git a/build/lib/s2python/common/timer.py b/build/lib/s2python/common/timer.py deleted file mode 100644 index 3811082..0000000 --- a/build/lib/s2python/common/timer.py +++ /dev/null @@ -1,17 +0,0 @@ -import uuid - -from s2python.common.duration import Duration -from s2python.generated.gen_s2 import Timer as GenTimer -from s2python.validate_values_mixin import ( - S2Message, - catch_and_convert_exceptions, -) - - -@catch_and_convert_exceptions -class Timer(GenTimer, S2Message["Timer"]): - model_config = GenTimer.model_config - model_config["validate_assignment"] = True - - id: uuid.UUID = GenTimer.model_fields["id"] # type: ignore[assignment] - duration: Duration = GenTimer.model_fields["duration"] # type: ignore[assignment] diff --git a/build/lib/s2python/common/transition.py b/build/lib/s2python/common/transition.py deleted file mode 100644 index e1e1a25..0000000 --- a/build/lib/s2python/common/transition.py +++ /dev/null @@ -1,24 +0,0 @@ -import uuid -from typing import Optional, List - -from s2python.common.duration import Duration -from s2python.generated.gen_s2 import Transition as GenTransition -from s2python.validate_values_mixin import ( - S2Message, - catch_and_convert_exceptions, -) - - -@catch_and_convert_exceptions -class Transition(GenTransition, S2Message["Transition"]): - model_config = GenTransition.model_config - model_config["validate_assignment"] = True - - id: uuid.UUID = GenTransition.model_fields["id"] # type: ignore[assignment] - from_: uuid.UUID = GenTransition.model_fields["from_"] # type: ignore[assignment] - to: uuid.UUID = GenTransition.model_fields["to"] # type: ignore[assignment] - start_timers: List[uuid.UUID] = GenTransition.model_fields["start_timers"] # type: ignore[assignment] - blocking_timers: List[uuid.UUID] = GenTransition.model_fields["blocking_timers"] # type: ignore[assignment] - transition_duration: Optional[Duration] = GenTransition.model_fields[ - "transition_duration" - ] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/__init__.py b/build/lib/s2python/frbc/__init__.py deleted file mode 100644 index da3d5bc..0000000 --- a/build/lib/s2python/frbc/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -from s2python.frbc.frbc_fill_level_target_profile_element import ( - FRBCFillLevelTargetProfileElement, -) -from s2python.frbc.frbc_fill_level_target_profile import FRBCFillLevelTargetProfile -from s2python.frbc.frbc_instruction import FRBCInstruction -from s2python.frbc.frbc_leakage_behaviour_element import FRBCLeakageBehaviourElement -from s2python.frbc.frbc_leakage_behaviour import FRBCLeakageBehaviour -from s2python.frbc.frbc_usage_forecast_element import FRBCUsageForecastElement -from s2python.frbc.frbc_usage_forecast import FRBCUsageForecast -from s2python.frbc.frbc_operation_mode_element import FRBCOperationModeElement -from s2python.frbc.frbc_operation_mode import FRBCOperationMode -from s2python.frbc.frbc_actuator_description import FRBCActuatorDescription -from s2python.frbc.frbc_actuator_status import FRBCActuatorStatus -from s2python.frbc.frbc_storage_description import FRBCStorageDescription -from s2python.frbc.frbc_storage_status import FRBCStorageStatus -from s2python.frbc.frbc_system_description import FRBCSystemDescription -from s2python.frbc.frbc_timer_status import FRBCTimerStatus diff --git a/build/lib/s2python/frbc/frbc_actuator_description.py b/build/lib/s2python/frbc/frbc_actuator_description.py deleted file mode 100644 index 08afce6..0000000 --- a/build/lib/s2python/frbc/frbc_actuator_description.py +++ /dev/null @@ -1,143 +0,0 @@ -import uuid - -from typing import List -from typing_extensions import Self - -from pydantic import model_validator - -from s2python.common import Transition, Timer, Commodity -from s2python.common.support import commodity_has_quantity -from s2python.frbc.frbc_operation_mode import FRBCOperationMode -from s2python.generated.gen_s2 import ( - FRBCActuatorDescription as GenFRBCActuatorDescription, -) -from s2python.validate_values_mixin import ( - S2Message, - catch_and_convert_exceptions, -) - - -@catch_and_convert_exceptions -class FRBCActuatorDescription(GenFRBCActuatorDescription, S2Message["FRBCActuatorDescription"]): - model_config = GenFRBCActuatorDescription.model_config - model_config["validate_assignment"] = True - - id: uuid.UUID = GenFRBCActuatorDescription.model_fields["id"] # type: ignore[assignment] - operation_modes: List[FRBCOperationMode] = GenFRBCActuatorDescription.model_fields[ - "operation_modes" - ] # type: ignore[assignment] - transitions: List[Transition] = GenFRBCActuatorDescription.model_fields["transitions"] # type: ignore[assignment] - timers: List[Timer] = GenFRBCActuatorDescription.model_fields["timers"] # type: ignore[assignment] - supported_commodities: List[Commodity] = GenFRBCActuatorDescription.model_fields[ - "supported_commodities" - ] # type: ignore[assignment] - - @model_validator(mode="after") - def validate_timers_in_transitions(self) -> Self: - timers_by_id = {timer.id: timer for timer in self.timers} - transition: Transition - for transition in self.transitions: - for start_timer_id in transition.start_timers: - if start_timer_id not in timers_by_id: - raise ValueError( - self, - f"{start_timer_id} was referenced as start timer in transition " - f"{transition.id} but was not defined in 'timers'.", - ) - - for blocking_timer_id in transition.blocking_timers: - if blocking_timer_id not in timers_by_id: - raise ValueError( - self, - f"{blocking_timer_id} was referenced as blocking timer in transition " - f"{transition.id} but was not defined in 'timers'.", - ) - - return self - - @model_validator(mode="after") - def validate_timers_unique_ids(self) -> Self: - ids = [] - timer: Timer - for timer in self.timers: - if timer.id in ids: - raise ValueError(self, f"Id {timer.id} was found multiple times in 'timers'.") - ids.append(timer.id) - - return self - - @model_validator(mode="after") - def validate_operation_modes_in_transitions(self) -> Self: - operation_mode_by_id = {operation_mode.id: operation_mode for operation_mode in self.operation_modes} - transition: Transition - for transition in self.transitions: - if transition.from_ not in operation_mode_by_id: - raise ValueError( - self, - f"Operation mode {transition.from_} was referenced as 'from' in transition " - f"{transition.id} but was not defined in 'operation_modes'.", - ) - - if transition.to not in operation_mode_by_id: - raise ValueError( - self, - f"Operation mode {transition.to} was referenced as 'to' in transition " - f"{transition.id} but was not defined in 'operation_modes'.", - ) - - return self - - @model_validator(mode="after") - def validate_operation_modes_unique_ids(self) -> Self: - ids = [] - operation_mode: FRBCOperationMode - for operation_mode in self.operation_modes: - if operation_mode.id in ids: - raise ValueError( - self, - f"Id {operation_mode.id} was found multiple times in 'operation_modes'.", - ) - ids.append(operation_mode.id) - - return self - - @model_validator(mode="after") - def validate_operation_mode_elements_have_all_supported_commodities(self) -> Self: - supported_commodities = self.supported_commodities - operation_mode: FRBCOperationMode - for operation_mode in self.operation_modes: - for operation_mode_element in operation_mode.elements: - for commodity in supported_commodities: - power_ranges_for_commodity = [ - power_range - for power_range in operation_mode_element.power_ranges - if commodity_has_quantity(commodity, power_range.commodity_quantity) - ] - - if len(power_ranges_for_commodity) > 1: - raise ValueError( - self, - f"Multiple power ranges defined for commodity {commodity} in operation " - f"mode {operation_mode.id} and element with fill_level_range " - f"{operation_mode_element.fill_level_range}", - ) - if not power_ranges_for_commodity: - raise ValueError( - self, - f"No power ranges defined for commodity {commodity} in operation " - f"mode {operation_mode.id} and element with fill_level_range " - f"{operation_mode_element.fill_level_range}", - ) - return self - - @model_validator(mode="after") - def validate_unique_supported_commodities(self) -> Self: - supported_commodities: List[Commodity] = self.supported_commodities - - for supported_commodity in supported_commodities: - if supported_commodities.count(supported_commodity) > 1: - raise ValueError( - self, - f"Found duplicate {supported_commodity} commodity in 'supported_commodities'", - ) - return self diff --git a/build/lib/s2python/frbc/frbc_actuator_status.py b/build/lib/s2python/frbc/frbc_actuator_status.py deleted file mode 100644 index 585a23d..0000000 --- a/build/lib/s2python/frbc/frbc_actuator_status.py +++ /dev/null @@ -1,23 +0,0 @@ -from typing import Optional -import uuid - -from s2python.generated.gen_s2 import FRBCActuatorStatus as GenFRBCActuatorStatus -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class FRBCActuatorStatus(GenFRBCActuatorStatus, S2Message["FRBCActuatorStatus"]): - model_config = GenFRBCActuatorStatus.model_config - model_config["validate_assignment"] = True - - active_operation_mode_id: uuid.UUID = GenFRBCActuatorStatus.model_fields[ - "active_operation_mode_id" - ] # type: ignore[assignment] - actuator_id: uuid.UUID = GenFRBCActuatorStatus.model_fields["actuator_id"] # type: ignore[assignment] - message_id: uuid.UUID = GenFRBCActuatorStatus.model_fields["message_id"] # type: ignore[assignment] - previous_operation_mode_id: Optional[uuid.UUID] = GenFRBCActuatorStatus.model_fields[ - "previous_operation_mode_id" - ] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_fill_level_target_profile.py b/build/lib/s2python/frbc/frbc_fill_level_target_profile.py deleted file mode 100644 index 38ef83b..0000000 --- a/build/lib/s2python/frbc/frbc_fill_level_target_profile.py +++ /dev/null @@ -1,24 +0,0 @@ -from typing import List -import uuid - -from s2python.frbc.frbc_fill_level_target_profile_element import ( - FRBCFillLevelTargetProfileElement, -) -from s2python.generated.gen_s2 import ( - FRBCFillLevelTargetProfile as GenFRBCFillLevelTargetProfile, -) -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class FRBCFillLevelTargetProfile(GenFRBCFillLevelTargetProfile, S2Message["FRBCFillLevelTargetProfile"]): - model_config = GenFRBCFillLevelTargetProfile.model_config - model_config["validate_assignment"] = True - - elements: List[FRBCFillLevelTargetProfileElement] = GenFRBCFillLevelTargetProfile.model_fields[ - "elements" - ] # type: ignore[assignment] - message_id: uuid.UUID = GenFRBCFillLevelTargetProfile.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_fill_level_target_profile_element.py b/build/lib/s2python/frbc/frbc_fill_level_target_profile_element.py deleted file mode 100644 index cdb7d84..0000000 --- a/build/lib/s2python/frbc/frbc_fill_level_target_profile_element.py +++ /dev/null @@ -1,34 +0,0 @@ -# pylint: disable=duplicate-code - -from typing_extensions import Self - -from pydantic import model_validator - -from s2python.common import Duration, NumberRange -from s2python.generated.gen_s2 import ( - FRBCFillLevelTargetProfileElement as GenFRBCFillLevelTargetProfileElement, -) -from s2python.validate_values_mixin import catch_and_convert_exceptions, S2Message - - -@catch_and_convert_exceptions -class FRBCFillLevelTargetProfileElement( - GenFRBCFillLevelTargetProfileElement, S2Message["FRBCFillLevelTargetProfileElement"] -): - model_config = GenFRBCFillLevelTargetProfileElement.model_config - model_config["validate_assignment"] = True - - duration: Duration = GenFRBCFillLevelTargetProfileElement.model_fields["duration"] # type: ignore[assignment] - fill_level_range: NumberRange = GenFRBCFillLevelTargetProfileElement.model_fields[ - "fill_level_range" - ] # type: ignore[assignment] - - @model_validator(mode="after") - def validate_start_end_order(self) -> Self: - if self.fill_level_range.start_of_range > self.fill_level_range.end_of_range: - raise ValueError( - self, - "start_of_range should not be higher than end_of_range for the fill_level_range", - ) - - return self diff --git a/build/lib/s2python/frbc/frbc_instruction.py b/build/lib/s2python/frbc/frbc_instruction.py deleted file mode 100644 index 584cfba..0000000 --- a/build/lib/s2python/frbc/frbc_instruction.py +++ /dev/null @@ -1,18 +0,0 @@ -import uuid - -from s2python.generated.gen_s2 import FRBCInstruction as GenFRBCInstruction -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class FRBCInstruction(GenFRBCInstruction, S2Message["FRBCInstruction"]): - model_config = GenFRBCInstruction.model_config - model_config["validate_assignment"] = True - - actuator_id: uuid.UUID = GenFRBCInstruction.model_fields["actuator_id"] # type: ignore[assignment] - id: uuid.UUID = GenFRBCInstruction.model_fields["id"] # type: ignore[assignment] - message_id: uuid.UUID = GenFRBCInstruction.model_fields["message_id"] # type: ignore[assignment] - operation_mode: uuid.UUID = GenFRBCInstruction.model_fields["operation_mode"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_leakage_behaviour.py b/build/lib/s2python/frbc/frbc_leakage_behaviour.py deleted file mode 100644 index fda7d3b..0000000 --- a/build/lib/s2python/frbc/frbc_leakage_behaviour.py +++ /dev/null @@ -1,20 +0,0 @@ -from typing import List -import uuid - -from s2python.frbc.frbc_leakage_behaviour_element import FRBCLeakageBehaviourElement -from s2python.generated.gen_s2 import FRBCLeakageBehaviour as GenFRBCLeakageBehaviour -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class FRBCLeakageBehaviour(GenFRBCLeakageBehaviour, S2Message["FRBCLeakageBehaviour"]): - model_config = GenFRBCLeakageBehaviour.model_config - model_config["validate_assignment"] = True - - elements: List[FRBCLeakageBehaviourElement] = GenFRBCLeakageBehaviour.model_fields[ - "elements" - ] # type: ignore[assignment] - message_id: uuid.UUID = GenFRBCLeakageBehaviour.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_leakage_behaviour_element.py b/build/lib/s2python/frbc/frbc_leakage_behaviour_element.py deleted file mode 100644 index b9ca2eb..0000000 --- a/build/lib/s2python/frbc/frbc_leakage_behaviour_element.py +++ /dev/null @@ -1,30 +0,0 @@ -# pylint: disable=duplicate-code - -from pydantic import model_validator -from typing_extensions import Self - -from s2python.common import NumberRange -from s2python.generated.gen_s2 import FRBCLeakageBehaviourElement as GenFRBCLeakageBehaviourElement -from s2python.validate_values_mixin import catch_and_convert_exceptions, S2Message - - -@catch_and_convert_exceptions -class FRBCLeakageBehaviourElement( - GenFRBCLeakageBehaviourElement, S2Message["FRBCLeakageBehaviourElement"] -): - model_config = GenFRBCLeakageBehaviourElement.model_config - model_config["validate_assignment"] = True - - fill_level_range: NumberRange = GenFRBCLeakageBehaviourElement.model_fields[ - "fill_level_range" - ] # type: ignore[assignment] - - @model_validator(mode="after") - def validate_start_end_order(self) -> Self: - if self.fill_level_range.start_of_range > self.fill_level_range.end_of_range: - raise ValueError( - self, - "start_of_range should not be higher than end_of_range for the fill_level_range", - ) - - return self diff --git a/build/lib/s2python/frbc/frbc_operation_mode.py b/build/lib/s2python/frbc/frbc_operation_mode.py deleted file mode 100644 index c6758ad..0000000 --- a/build/lib/s2python/frbc/frbc_operation_mode.py +++ /dev/null @@ -1,42 +0,0 @@ -# from itertools import pairwise -import uuid -from typing import List, Dict -from typing_extensions import Self - -from pydantic import model_validator - -from s2python.common import NumberRange -from s2python.frbc.frbc_operation_mode_element import FRBCOperationModeElement -from s2python.generated.gen_s2 import FRBCOperationMode as GenFRBCOperationMode -from s2python.validate_values_mixin import ( - S2Message, - catch_and_convert_exceptions, -) -from s2python.utils import pairwise - - -@catch_and_convert_exceptions -class FRBCOperationMode(GenFRBCOperationMode, S2Message["FRBCOperationMode"]): - model_config = GenFRBCOperationMode.model_config - model_config["validate_assignment"] = True - - id: uuid.UUID = GenFRBCOperationMode.model_fields["id"] # type: ignore[assignment] - elements: List[FRBCOperationModeElement] = GenFRBCOperationMode.model_fields["elements"] # type: ignore[assignment] - - @model_validator(mode="after") - def validate_contiguous_fill_levels_operation_mode_elements(self) -> Self: - elements_by_fill_level_range: Dict[NumberRange, FRBCOperationModeElement] - elements_by_fill_level_range = {element.fill_level_range: element for element in self.elements} - - sorted_fill_level_ranges: List[NumberRange] - sorted_fill_level_ranges = list(elements_by_fill_level_range.keys()) - sorted_fill_level_ranges.sort(key=lambda r: r.start_of_range) - - for current_fill_level_range, next_fill_level_range in pairwise(sorted_fill_level_ranges): - if current_fill_level_range.end_of_range != next_fill_level_range.start_of_range: - raise ValueError( - self, - f"Elements with fill level ranges {current_fill_level_range} and " - f"{next_fill_level_range} are closest match to each other but not contiguous.", - ) - return self diff --git a/build/lib/s2python/frbc/frbc_operation_mode_element.py b/build/lib/s2python/frbc/frbc_operation_mode_element.py deleted file mode 100644 index d154d11..0000000 --- a/build/lib/s2python/frbc/frbc_operation_mode_element.py +++ /dev/null @@ -1,27 +0,0 @@ -from typing import Optional, List - -from s2python.common import NumberRange, PowerRange -from s2python.generated.gen_s2 import ( - FRBCOperationModeElement as GenFRBCOperationModeElement, -) -from s2python.validate_values_mixin import ( - S2Message, - catch_and_convert_exceptions, -) - - -@catch_and_convert_exceptions -class FRBCOperationModeElement(GenFRBCOperationModeElement, S2Message["FRBCOperationModeElement"]): - model_config = GenFRBCOperationModeElement.model_config - model_config["validate_assignment"] = True - - fill_level_range: NumberRange = GenFRBCOperationModeElement.model_fields[ - "fill_level_range" - ] # type: ignore[assignment] - fill_rate: NumberRange = GenFRBCOperationModeElement.model_fields["fill_rate"] # type: ignore[assignment] - power_ranges: List[PowerRange] = GenFRBCOperationModeElement.model_fields[ - "power_ranges" - ] # type: ignore[assignment] - running_costs: Optional[NumberRange] = GenFRBCOperationModeElement.model_fields[ - "running_costs" - ] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_storage_description.py b/build/lib/s2python/frbc/frbc_storage_description.py deleted file mode 100644 index eb141b8..0000000 --- a/build/lib/s2python/frbc/frbc_storage_description.py +++ /dev/null @@ -1,18 +0,0 @@ -from s2python.common import NumberRange -from s2python.generated.gen_s2 import ( - FRBCStorageDescription as GenFRBCStorageDescription, -) -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class FRBCStorageDescription(GenFRBCStorageDescription, S2Message["FRBCStorageDescription"]): - model_config = GenFRBCStorageDescription.model_config - model_config["validate_assignment"] = True - - fill_level_range: NumberRange = GenFRBCStorageDescription.model_fields[ - "fill_level_range" - ] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_storage_status.py b/build/lib/s2python/frbc/frbc_storage_status.py deleted file mode 100644 index 7940b79..0000000 --- a/build/lib/s2python/frbc/frbc_storage_status.py +++ /dev/null @@ -1,15 +0,0 @@ -import uuid - -from s2python.generated.gen_s2 import FRBCStorageStatus as GenFRBCStorageStatus -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class FRBCStorageStatus(GenFRBCStorageStatus, S2Message["FRBCStorageStatus"]): - model_config = GenFRBCStorageStatus.model_config - model_config["validate_assignment"] = True - - message_id: uuid.UUID = GenFRBCStorageStatus.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_system_description.py b/build/lib/s2python/frbc/frbc_system_description.py deleted file mode 100644 index 2eb5899..0000000 --- a/build/lib/s2python/frbc/frbc_system_description.py +++ /dev/null @@ -1,22 +0,0 @@ -from typing import List -import uuid - -from s2python.generated.gen_s2 import FRBCSystemDescription as GenFRBCSystemDescription -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) -from s2python.frbc.frbc_actuator_description import FRBCActuatorDescription -from s2python.frbc.frbc_storage_description import FRBCStorageDescription - - -@catch_and_convert_exceptions -class FRBCSystemDescription(GenFRBCSystemDescription, S2Message["FRBCSystemDescription"]): - model_config = GenFRBCSystemDescription.model_config - model_config["validate_assignment"] = True - - actuators: List[FRBCActuatorDescription] = GenFRBCSystemDescription.model_fields[ - "actuators" - ] # type: ignore[assignment] - message_id: uuid.UUID = GenFRBCSystemDescription.model_fields["message_id"] # type: ignore[assignment] - storage: FRBCStorageDescription = GenFRBCSystemDescription.model_fields["storage"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_timer_status.py b/build/lib/s2python/frbc/frbc_timer_status.py deleted file mode 100644 index 80c86d6..0000000 --- a/build/lib/s2python/frbc/frbc_timer_status.py +++ /dev/null @@ -1,17 +0,0 @@ -import uuid - -from s2python.generated.gen_s2 import FRBCTimerStatus as GenFRBCTimerStatus -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class FRBCTimerStatus(GenFRBCTimerStatus, S2Message["FRBCTimerStatus"]): - model_config = GenFRBCTimerStatus.model_config - model_config["validate_assignment"] = True - - actuator_id: uuid.UUID = GenFRBCTimerStatus.model_fields["actuator_id"] # type: ignore[assignment] - message_id: uuid.UUID = GenFRBCTimerStatus.model_fields["message_id"] # type: ignore[assignment] - timer_id: uuid.UUID = GenFRBCTimerStatus.model_fields["timer_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_usage_forecast.py b/build/lib/s2python/frbc/frbc_usage_forecast.py deleted file mode 100644 index f71fda4..0000000 --- a/build/lib/s2python/frbc/frbc_usage_forecast.py +++ /dev/null @@ -1,18 +0,0 @@ -from typing import List -import uuid - -from s2python.generated.gen_s2 import FRBCUsageForecast as GenFRBCUsageForecast -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) -from s2python.frbc.frbc_usage_forecast_element import FRBCUsageForecastElement - - -@catch_and_convert_exceptions -class FRBCUsageForecast(GenFRBCUsageForecast, S2Message["FRBCUsageForecast"]): - model_config = GenFRBCUsageForecast.model_config - model_config["validate_assignment"] = True - - elements: List[FRBCUsageForecastElement] = GenFRBCUsageForecast.model_fields["elements"] # type: ignore[assignment] - message_id: uuid.UUID = GenFRBCUsageForecast.model_fields["message_id"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/frbc_usage_forecast_element.py b/build/lib/s2python/frbc/frbc_usage_forecast_element.py deleted file mode 100644 index 370c04e..0000000 --- a/build/lib/s2python/frbc/frbc_usage_forecast_element.py +++ /dev/null @@ -1,17 +0,0 @@ -from s2python.common import Duration - -from s2python.generated.gen_s2 import ( - FRBCUsageForecastElement as GenFRBCUsageForecastElement, -) -from s2python.validate_values_mixin import ( - catch_and_convert_exceptions, - S2Message, -) - - -@catch_and_convert_exceptions -class FRBCUsageForecastElement(GenFRBCUsageForecastElement, S2Message["FRBCUsageForecastElement"]): - model_config = GenFRBCUsageForecastElement.model_config - model_config["validate_assignment"] = True - - duration: Duration = GenFRBCUsageForecastElement.model_fields["duration"] # type: ignore[assignment] diff --git a/build/lib/s2python/frbc/rm.py b/build/lib/s2python/frbc/rm.py deleted file mode 100644 index e69de29..0000000 diff --git a/build/lib/s2python/generated/__init__.py b/build/lib/s2python/generated/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/build/lib/s2python/generated/gen_s2.py b/build/lib/s2python/generated/gen_s2.py deleted file mode 100644 index fbdc15d..0000000 --- a/build/lib/s2python/generated/gen_s2.py +++ /dev/null @@ -1,1611 +0,0 @@ -# generated by datamodel-codegen: -# filename: openapi.yml -# timestamp: 2024-07-29T10:18:52+00:00 - -from __future__ import annotations - -from enum import Enum -from typing import List, Optional - -from pydantic import ( - AwareDatetime, - BaseModel, - ConfigDict, - Field, - RootModel, - conint, - constr, -) -from typing_extensions import Literal - - -class Duration(RootModel[conint(ge=0)]): - root: conint(ge=0) = Field(..., description='Duration in milliseconds') - - -class ID(RootModel[constr(pattern=r'[a-zA-Z0-9\-_:]{2,64}')]): - root: constr(pattern=r'[a-zA-Z0-9\-_:]{2,64}') = Field(..., description='UUID') - - -class Currency(Enum): - AED = 'AED' - ANG = 'ANG' - AUD = 'AUD' - CHE = 'CHE' - CHF = 'CHF' - CHW = 'CHW' - EUR = 'EUR' - GBP = 'GBP' - LBP = 'LBP' - LKR = 'LKR' - LRD = 'LRD' - LSL = 'LSL' - LYD = 'LYD' - MAD = 'MAD' - MDL = 'MDL' - MGA = 'MGA' - MKD = 'MKD' - MMK = 'MMK' - MNT = 'MNT' - MOP = 'MOP' - MRO = 'MRO' - MUR = 'MUR' - MVR = 'MVR' - MWK = 'MWK' - MXN = 'MXN' - MXV = 'MXV' - MYR = 'MYR' - MZN = 'MZN' - NAD = 'NAD' - NGN = 'NGN' - NIO = 'NIO' - NOK = 'NOK' - NPR = 'NPR' - NZD = 'NZD' - OMR = 'OMR' - PAB = 'PAB' - PEN = 'PEN' - PGK = 'PGK' - PHP = 'PHP' - PKR = 'PKR' - PLN = 'PLN' - PYG = 'PYG' - QAR = 'QAR' - RON = 'RON' - RSD = 'RSD' - RUB = 'RUB' - RWF = 'RWF' - SAR = 'SAR' - SBD = 'SBD' - SCR = 'SCR' - SDG = 'SDG' - SEK = 'SEK' - SGD = 'SGD' - SHP = 'SHP' - SLL = 'SLL' - SOS = 'SOS' - SRD = 'SRD' - SSP = 'SSP' - STD = 'STD' - SYP = 'SYP' - SZL = 'SZL' - THB = 'THB' - TJS = 'TJS' - TMT = 'TMT' - TND = 'TND' - TOP = 'TOP' - TRY = 'TRY' - TTD = 'TTD' - TWD = 'TWD' - TZS = 'TZS' - UAH = 'UAH' - UGX = 'UGX' - USD = 'USD' - USN = 'USN' - UYI = 'UYI' - UYU = 'UYU' - UZS = 'UZS' - VEF = 'VEF' - VND = 'VND' - VUV = 'VUV' - WST = 'WST' - XAG = 'XAG' - XAU = 'XAU' - XBA = 'XBA' - XBB = 'XBB' - XBC = 'XBC' - XBD = 'XBD' - XCD = 'XCD' - XOF = 'XOF' - XPD = 'XPD' - XPF = 'XPF' - XPT = 'XPT' - XSU = 'XSU' - XTS = 'XTS' - XUA = 'XUA' - XXX = 'XXX' - YER = 'YER' - ZAR = 'ZAR' - ZMW = 'ZMW' - ZWL = 'ZWL' - - -class SessionRequestType(Enum): - RECONNECT = 'RECONNECT' - TERMINATE = 'TERMINATE' - - -class RevokableObjects(Enum): - PEBC_PowerConstraints = 'PEBC.PowerConstraints' - PEBC_EnergyConstraint = 'PEBC.EnergyConstraint' - PEBC_Instruction = 'PEBC.Instruction' - PPBC_PowerProfileDefinition = 'PPBC.PowerProfileDefinition' - PPBC_ScheduleInstruction = 'PPBC.ScheduleInstruction' - PPBC_StartInterruptionInstruction = 'PPBC.StartInterruptionInstruction' - PPBC_EndInterruptionInstruction = 'PPBC.EndInterruptionInstruction' - OMBC_SystemDescription = 'OMBC.SystemDescription' - OMBC_Instruction = 'OMBC.Instruction' - FRBC_SystemDescription = 'FRBC.SystemDescription' - FRBC_Instruction = 'FRBC.Instruction' - DDBC_SystemDescription = 'DDBC.SystemDescription' - DDBC_Instruction = 'DDBC.Instruction' - - -class EnergyManagementRole(Enum): - CEM = 'CEM' - RM = 'RM' - - -class ReceptionStatusValues(Enum): - INVALID_DATA = 'INVALID_DATA' - INVALID_MESSAGE = 'INVALID_MESSAGE' - INVALID_CONTENT = 'INVALID_CONTENT' - TEMPORARY_ERROR = 'TEMPORARY_ERROR' - PERMANENT_ERROR = 'PERMANENT_ERROR' - OK = 'OK' - - -class NumberRange(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - start_of_range: float = Field( - ..., description='Number that defines the start of the range' - ) - end_of_range: float = Field( - ..., description='Number that defines the end of the range' - ) - - -class Transition(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - id: ID = Field( - ..., - description='ID of the Transition. Must be unique in the scope of the OMBC.SystemDescription, FRBC.ActuatorDescription or DDBC.ActuatorDescription in which it is used.', - ) - from_: ID = Field( - ..., - alias='from', - description='ID of the OperationMode (exact type differs per ControlType) that should be switched from.', - ) - to: ID = Field( - ..., - description='ID of the OperationMode (exact type differs per ControlType) that will be switched to.', - ) - start_timers: List[ID] = Field( - ..., - description='List of IDs of Timers that will be (re)started when this transition is initiated', - max_length=1000, - min_length=0, - ) - blocking_timers: List[ID] = Field( - ..., - description='List of IDs of Timers that block this Transition from initiating while at least one of these Timers is not yet finished', - max_length=1000, - min_length=0, - ) - transition_costs: Optional[float] = Field( - None, - description='Absolute costs for going through this Transition in the currency as described in the ResourceManagerDetails.', - ) - transition_duration: Optional[Duration] = Field( - None, - description='Indicates the time between the initiation of this Transition, and the time at which the device behaves according to the Operation Mode which is defined in the ‘to’ data element. When no value is provided it is assumed the transition duration is negligible.', - ) - abnormal_condition_only: bool = Field( - ..., - description='Indicates if this Transition may only be used during an abnormal condition (see Clause )', - ) - - -class Timer(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - id: ID = Field( - ..., - description='ID of the Timer. Must be unique in the scope of the OMBC.SystemDescription, FRBC.ActuatorDescription or DDBC.ActuatorDescription in which it is used.', - ) - diagnostic_label: Optional[str] = Field( - None, - description='Human readable name/description of the Timer. This element is only intended for diagnostic purposes and not for HMI applications.', - ) - duration: Duration = Field( - ..., - description='The time it takes for the Timer to finish after it has been started', - ) - - -class PEBCPowerEnvelopeElement(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - duration: Duration = Field(..., description='The duration of the element') - upper_limit: float = Field( - ..., - description='Upper power limit according to the commodity_quantity of the containing PEBC.PowerEnvelope. The lower_limit must be smaller or equal to the upper_limit. The Resource Manager is requested to keep the power values for the given commodity quantity equal to or below the upper_limit. The upper_limit shall be in accordance with the constraints provided by the Resource Manager through any PEBC.AllowedLimitRange with limit_type UPPER_LIMIT.', - ) - lower_limit: float = Field( - ..., - description='Lower power limit according to the commodity_quantity of the containing PEBC.PowerEnvelope. The lower_limit must be smaller or equal to the upper_limit. The Resource Manager is requested to keep the power values for the given commodity quantity equal to or above the lower_limit. The lower_limit shall be in accordance with the constraints provided by the Resource Manager through any PEBC.AllowedLimitRange with limit_type LOWER_LIMIT.', - ) - - -class FRBCStorageDescription(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - diagnostic_label: Optional[str] = Field( - None, - description='Human readable name/description of the storage (e.g. hot water buffer or battery). This element is only intended for diagnostic purposes and not for HMI applications.', - ) - fill_level_label: Optional[str] = Field( - None, - description='Human readable description of the (physical) units associated with the fill_level (e.g. degrees Celsius or percentage state of charge). This element is only intended for diagnostic purposes and not for HMI applications.', - ) - provides_leakage_behaviour: bool = Field( - ..., - description='Indicates whether the Storage could provide details of power leakage behaviour through the FRBC.LeakageBehaviour.', - ) - provides_fill_level_target_profile: bool = Field( - ..., - description='Indicates whether the Storage could provide a target profile for the fill level through the FRBC.FillLevelTargetProfile.', - ) - provides_usage_forecast: bool = Field( - ..., - description='Indicates whether the Storage could provide a UsageForecast through the FRBC.UsageForecast.', - ) - fill_level_range: NumberRange = Field( - ..., - description='The range in which the fill_level should remain. It is expected of the CEM to keep the fill_level within this range. When the fill_level is not within this range, the Resource Manager can ignore instructions from the CEM (except during abnormal conditions). ', - ) - - -class FRBCLeakageBehaviourElement(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - fill_level_range: NumberRange = Field( - ..., - description='The fill level range for which this FRBC.LeakageBehaviourElement applies. The start of the range must be less than the end of the range.', - ) - leakage_rate: float = Field( - ..., - description='Indicates how fast the momentary fill level will decrease per second due to leakage within the given range of the fill level. A positive value indicates that the fill level decreases over time due to leakage.', - ) - - -class FRBCUsageForecastElement(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - duration: Duration = Field( - ..., description='Indicator for how long the given usage_rate is valid.' - ) - usage_rate_upper_limit: Optional[float] = Field( - None, - description='The upper limit of the range with a 100 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', - ) - usage_rate_upper_95PPR: Optional[float] = Field( - None, - description='The upper limit of the range with a 95 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', - ) - usage_rate_upper_68PPR: Optional[float] = Field( - None, - description='The upper limit of the range with a 68 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', - ) - usage_rate_expected: float = Field( - ..., - description='The most likely value for the usage rate; the expected increase or decrease of the fill_level per second. A positive value indicates that the fill level will decrease due to usage.', - ) - usage_rate_lower_68PPR: Optional[float] = Field( - None, - description='The lower limit of the range with a 68 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', - ) - usage_rate_lower_95PPR: Optional[float] = Field( - None, - description='The lower limit of the range with a 95 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', - ) - usage_rate_lower_limit: Optional[float] = Field( - None, - description='The lower limit of the range with a 100 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', - ) - - -class FRBCFillLevelTargetProfileElement(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - duration: Duration = Field(..., description='The duration of the element.') - fill_level_range: NumberRange = Field( - ..., - description='The target range in which the fill_level must be for the time period during which the element is active. The start of the range must be smaller or equal to the end of the range. The CEM must take best-effort actions to proactively achieve this target.', - ) - - -class DDBCAverageDemandRateForecastElement(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - duration: Duration = Field(..., description='Duration of the element') - demand_rate_upper_limit: Optional[float] = Field( - None, - description='The upper limit of the range with a 100 % probability that the demand rate is within that range', - ) - demand_rate_upper_95PPR: Optional[float] = Field( - None, - description='The upper limit of the range with a 95 % probability that the demand rate is within that range', - ) - demand_rate_upper_68PPR: Optional[float] = Field( - None, - description='The upper limit of the range with a 68 % probability that the demand rate is within that range', - ) - demand_rate_expected: float = Field( - ..., - description='The most likely value for the demand rate; the expected increase or decrease of the fill_level per second', - ) - demand_rate_lower_68PPR: Optional[float] = Field( - None, - description='The lower limit of the range with a 68 % probability that the demand rate is within that range', - ) - demand_rate_lower_95PPR: Optional[float] = Field( - None, - description='The lower limit of the range with a 95 % probability that the demand rate is within that range', - ) - demand_rate_lower_limit: Optional[float] = Field( - None, - description='The lower limit of the range with a 100 % probability that the demand rate is within that range', - ) - - -class RoleType(Enum): - ENERGY_PRODUCER = 'ENERGY_PRODUCER' - ENERGY_CONSUMER = 'ENERGY_CONSUMER' - ENERGY_STORAGE = 'ENERGY_STORAGE' - - -class Commodity(Enum): - GAS = 'GAS' - HEAT = 'HEAT' - ELECTRICITY = 'ELECTRICITY' - OIL = 'OIL' - - -class CommodityQuantity(Enum): - ELECTRIC_POWER_L1 = 'ELECTRIC.POWER.L1' - ELECTRIC_POWER_L2 = 'ELECTRIC.POWER.L2' - ELECTRIC_POWER_L3 = 'ELECTRIC.POWER.L3' - ELECTRIC_POWER_3_PHASE_SYMMETRIC = 'ELECTRIC.POWER.3_PHASE_SYMMETRIC' - NATURAL_GAS_FLOW_RATE = 'NATURAL_GAS.FLOW_RATE' - HYDROGEN_FLOW_RATE = 'HYDROGEN.FLOW_RATE' - HEAT_TEMPERATURE = 'HEAT.TEMPERATURE' - HEAT_FLOW_RATE = 'HEAT.FLOW_RATE' - HEAT_THERMAL_POWER = 'HEAT.THERMAL_POWER' - OIL_FLOW_RATE = 'OIL.FLOW_RATE' - - -class InstructionStatus(Enum): - NEW = 'NEW' - ACCEPTED = 'ACCEPTED' - REJECTED = 'REJECTED' - REVOKED = 'REVOKED' - STARTED = 'STARTED' - SUCCEEDED = 'SUCCEEDED' - ABORTED = 'ABORTED' - - -class ControlType(Enum): - POWER_ENVELOPE_BASED_CONTROL = 'POWER_ENVELOPE_BASED_CONTROL' - POWER_PROFILE_BASED_CONTROL = 'POWER_PROFILE_BASED_CONTROL' - OPERATION_MODE_BASED_CONTROL = 'OPERATION_MODE_BASED_CONTROL' - FILL_RATE_BASED_CONTROL = 'FILL_RATE_BASED_CONTROL' - DEMAND_DRIVEN_BASED_CONTROL = 'DEMAND_DRIVEN_BASED_CONTROL' - NOT_CONTROLABLE = 'NOT_CONTROLABLE' - NO_SELECTION = 'NO_SELECTION' - - -class PEBCPowerEnvelopeLimitType(Enum): - UPPER_LIMIT = 'UPPER_LIMIT' - LOWER_LIMIT = 'LOWER_LIMIT' - - -class PEBCPowerEnvelopeConsequenceType(Enum): - VANISH = 'VANISH' - DEFER = 'DEFER' - - -class PPBCPowerSequenceStatus(Enum): - NOT_SCHEDULED = 'NOT_SCHEDULED' - SCHEDULED = 'SCHEDULED' - EXECUTING = 'EXECUTING' - INTERRUPTED = 'INTERRUPTED' - FINISHED = 'FINISHED' - ABORTED = 'ABORTED' - - -class OMBCTimerStatus(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['OMBC.TimerStatus'] = 'OMBC.TimerStatus' - message_id: ID - timer_id: ID = Field(..., description='The ID of the timer this message refers to') - finished_at: AwareDatetime = Field( - ..., - description='Indicates when the Timer will be finished. If the DateTimeStamp is in the future, the timer is not yet finished. If the DateTimeStamp is in the past, the timer is finished. If the timer was never started, the value can be an arbitrary DateTimeStamp in the past.', - ) - - -class FRBCTimerStatus(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['FRBC.TimerStatus'] = 'FRBC.TimerStatus' - message_id: ID - timer_id: ID = Field(..., description='The ID of the timer this message refers to') - actuator_id: ID = Field( - ..., description='The ID of the actuator the timer belongs to' - ) - finished_at: AwareDatetime = Field( - ..., - description='Indicates when the Timer will be finished. If the DateTimeStamp is in the future, the timer is not yet finished. If the DateTimeStamp is in the past, the timer is finished. If the timer was never started, the value can be an arbitrary DateTimeStamp in the past.', - ) - - -class DDBCTimerStatus(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['DDBC.TimerStatus'] = 'DDBC.TimerStatus' - message_id: ID - timer_id: ID = Field(..., description='The ID of the timer this message refers to') - actuator_id: ID = Field( - ..., description='The ID of the actuator the timer belongs to' - ) - finished_at: AwareDatetime = Field( - ..., - description='Indicates when the Timer will be finished. If the DateTimeStamp is in the future, the timer is not yet finished. If the DateTimeStamp is in the past, the timer is finished. If the timer was never started, the value can be an arbitrary DateTimeStamp in the past.', - ) - - -class SelectControlType(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['SelectControlType'] = 'SelectControlType' - message_id: ID - control_type: ControlType = Field( - ..., - description='The ControlType to activate. Must be one of the available ControlTypes as defined in the ResourceManagerDetails', - ) - - -class SessionRequest(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['SessionRequest'] = 'SessionRequest' - message_id: ID - request: SessionRequestType = Field(..., description='The type of request') - diagnostic_label: Optional[str] = Field( - None, - description='Optional field for a human readible descirption for debugging purposes', - ) - - -class RevokeObject(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['RevokeObject'] = 'RevokeObject' - message_id: ID - object_type: RevokableObjects = Field( - ..., description='The type of object that needs to be revoked' - ) - object_id: ID = Field(..., description='The ID of object that needs to be revoked') - - -class Handshake(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['Handshake'] = 'Handshake' - message_id: ID - role: EnergyManagementRole = Field( - ..., description='The role of the sender of this message' - ) - supported_protocol_versions: Optional[List[str]] = Field( - None, - description='Protocol versions supported by the sender of this message. This field is mandatory for the RM, but optional for the CEM.', - min_length=1, - ) - - -class HandshakeResponse(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['HandshakeResponse'] = 'HandshakeResponse' - message_id: ID - selected_protocol_version: str = Field( - ..., description='The protocol version the CEM selected for this session' - ) - - -class ReceptionStatus(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['ReceptionStatus'] = 'ReceptionStatus' - subject_message_id: ID = Field( - ..., description='The message this ReceptionStatus refers to' - ) - status: ReceptionStatusValues = Field( - ..., description='Enumeration of status values' - ) - diagnostic_label: Optional[str] = Field( - None, - description='Diagnostic label that can be used to provide additional information for debugging. However, not for HMI purposes.', - ) - - -class InstructionStatusUpdate(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['InstructionStatusUpdate'] = 'InstructionStatusUpdate' - message_id: ID - instruction_id: ID = Field( - ..., description='ID of this instruction (as provided by the CEM) ' - ) - status_type: InstructionStatus = Field( - ..., description='Present status of this instruction.' - ) - timestamp: AwareDatetime = Field( - ..., description='Timestamp when status_type has changed the last time.' - ) - - -class PEBCEnergyConstraint(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['PEBC.EnergyConstraint'] = 'PEBC.EnergyConstraint' - message_id: ID - id: ID = Field( - ..., - description='Identifier of this PEBC.EnergyConstraints. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', - ) - valid_from: AwareDatetime = Field( - ..., - description='Moment this PEBC.EnergyConstraints information starts to be valid', - ) - valid_until: AwareDatetime = Field( - ..., - description='Moment until this PEBC.EnergyConstraints information is valid.', - ) - upper_average_power: float = Field( - ..., - description='Upper average power within the time period given by valid_from and valid_until. If the duration is multiplied with this power value, then the associated upper energy content can be derived. This is the highest amount of energy the resource will consume during that period of time. The Power Envelope created by the CEM must allow at least this much energy consumption (in case the number is positive). Must be greater than or equal to lower_average_power, and can be negative in case of energy production.', - ) - lower_average_power: float = Field( - ..., - description='Lower average power within the time period given by valid_from and valid_until. If the duration is multiplied with this power value, then the associated lower energy content can be derived. This is the lowest amount of energy the resource will consume during that period of time. The Power Envelope created by the CEM must allow at least this much energy production (in case the number is negative). Must be greater than or equal to lower_average_power, and can be negative in case of energy production.', - ) - commodity_quantity: CommodityQuantity = Field( - ..., - description='Type of power quantity which applies to upper_average_power and lower_average_power', - ) - - -class PPBCScheduleInstruction(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['PPBC.ScheduleInstruction'] = 'PPBC.ScheduleInstruction' - message_id: ID - id: ID = Field( - ..., - description='ID of the Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', - ) - power_profile_id: ID = Field( - ..., - description='ID of the PPBC.PowerProfileDefinition of which the PPBC.PowerSequence is being selected and scheduled by the CEM.', - ) - sequence_container_id: ID = Field( - ..., - description='ID of the PPBC.PowerSequnceContainer of which the PPBC.PowerSequence is being selected and scheduled by the CEM.', - ) - power_sequence_id: ID = Field( - ..., - description='ID of the PPBC.PowerSequence that is being selected and scheduled by the CEM.', - ) - execution_time: AwareDatetime = Field( - ..., - description='Indicates the moment the PPBC.PowerSequence shall start. When the specified execution time is in the past, execution must start as soon as possible.', - ) - abnormal_condition: bool = Field( - ..., - description='Indicates if this is an instruction during an abnormal condition', - ) - - -class PPBCStartInterruptionInstruction(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['PPBC.StartInterruptionInstruction'] = ( - 'PPBC.StartInterruptionInstruction' - ) - message_id: ID - id: ID = Field( - ..., - description='ID of the Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', - ) - power_profile_id: ID = Field( - ..., - description='ID of the PPBC.PowerProfileDefinition of which the PPBC.PowerSequence is being interrupted by the CEM.', - ) - sequence_container_id: ID = Field( - ..., - description='ID of the PPBC.PowerSequnceContainer of which the PPBC.PowerSequence is being interrupted by the CEM.', - ) - power_sequence_id: ID = Field( - ..., description='ID of the PPBC.PowerSequence that the CEM wants to interrupt.' - ) - execution_time: AwareDatetime = Field( - ..., - description='Indicates the moment the PPBC.PowerSequence shall be interrupted. When the specified execution time is in the past, execution must start as soon as possible.', - ) - abnormal_condition: bool = Field( - ..., - description='Indicates if this is an instruction during an abnormal condition', - ) - - -class PPBCEndInterruptionInstruction(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['PPBC.EndInterruptionInstruction'] = ( - 'PPBC.EndInterruptionInstruction' - ) - message_id: ID - id: ID = Field( - ..., - description='ID of the Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', - ) - power_profile_id: ID = Field( - ..., - description='ID of the PPBC.PowerProfileDefinition of which the PPBC.PowerSequence interruption is being ended by the CEM.', - ) - sequence_container_id: ID = Field( - ..., - description='ID of the PPBC.PowerSequnceContainer of which the PPBC.PowerSequence interruption is being ended by the CEM.', - ) - power_sequence_id: ID = Field( - ..., - description='ID of the PPBC.PowerSequence for which the CEM wants to end the interruption.', - ) - execution_time: AwareDatetime = Field( - ..., - description='Indicates the moment PPBC.PowerSequence interruption shall end. When the specified execution time is in the past, execution must start as soon as possible.', - ) - abnormal_condition: bool = Field( - ..., - description='Indicates if this is an instruction during an abnormal condition', - ) - - -class OMBCStatus(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['OMBC.Status'] = 'OMBC.Status' - message_id: ID - active_operation_mode_id: ID = Field( - ..., description='ID of the active OMBC.OperationMode.' - ) - operation_mode_factor: float = Field( - ..., - description='The number indicates the factor with which the OMBC.OperationMode should be configured. The factor should be greater than or equal than 0 and less or equal to 1.', - ) - previous_operation_mode_id: Optional[ID] = Field( - None, - description='ID of the OMBC.OperationMode that was previously active. This value shall always be provided, unless the active OMBC.OperationMode is the first OMBC.OperationMode the Resource Manager is aware of.', - ) - transition_timestamp: Optional[AwareDatetime] = Field( - None, - description='Time at which the transition from the previous OMBC.OperationMode to the active OMBC.OperationMode was initiated. This value shall always be provided, unless the active OMBC.OperationMode is the first OMBC.OperationMode the Resource Manager is aware of.', - ) - - -class OMBCInstruction(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['OMBC.Instruction'] = 'OMBC.Instruction' - message_id: ID - id: ID = Field( - ..., - description='ID of the instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', - ) - execution_time: AwareDatetime = Field( - ..., - description='Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.', - ) - operation_mode_id: ID = Field( - ..., description='ID of the OMBC.OperationMode that should be activated' - ) - operation_mode_factor: float = Field( - ..., - description='The number indicates the factor with which the OMBC.OperationMode should be configured. The factor should be greater than or equal than 0 and less or equal to 1.', - ) - abnormal_condition: bool = Field( - ..., - description='Indicates if this is an instruction during an abnormal condition', - ) - - -class FRBCActuatorStatus(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['FRBC.ActuatorStatus'] = 'FRBC.ActuatorStatus' - message_id: ID - actuator_id: ID = Field( - ..., description='ID of the actuator this messages refers to' - ) - active_operation_mode_id: ID = Field( - ..., description='ID of the FRBC.OperationMode that is presently active.' - ) - operation_mode_factor: float = Field( - ..., - description='The number indicates the factor with which the FRBC.OperationMode is configured. The factor should be greater than or equal than 0 and less or equal to 1.', - ) - previous_operation_mode_id: Optional[ID] = Field( - None, - description='ID of the FRBC.OperationMode that was active before the present one. This value shall always be provided, unless the active FRBC.OperationMode is the first FRBC.OperationMode the Resource Manager is aware of.', - ) - transition_timestamp: Optional[AwareDatetime] = Field( - None, - description='Time at which the transition from the previous FRBC.OperationMode to the active FRBC.OperationMode was initiated. This value shall always be provided, unless the active FRBC.OperationMode is the first FRBC.OperationMode the Resource Manager is aware of.', - ) - - -class FRBCStorageStatus(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['FRBC.StorageStatus'] = 'FRBC.StorageStatus' - message_id: ID - present_fill_level: float = Field( - ..., description='Present fill level of the Storage' - ) - - -class FRBCLeakageBehaviour(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['FRBC.LeakageBehaviour'] = 'FRBC.LeakageBehaviour' - message_id: ID - valid_from: AwareDatetime = Field( - ..., - description='Moment this FRBC.LeakageBehaviour starts to be valid. If the FRBC.LeakageBehaviour is immediately valid, the DateTimeStamp should be now or in the past.', - ) - elements: List[FRBCLeakageBehaviourElement] = Field( - ..., - description='List of elements that model the leakage behaviour of the buffer. The fill_level_ranges of the elements must be contiguous.', - max_length=288, - min_length=1, - ) - - -class FRBCInstruction(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['FRBC.Instruction'] = 'FRBC.Instruction' - message_id: ID - id: ID = Field( - ..., - description='ID of the instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', - ) - actuator_id: ID = Field( - ..., description='ID of the actuator this instruction belongs to.' - ) - operation_mode: ID = Field( - ..., description='ID of the FRBC.OperationMode that should be activated.' - ) - operation_mode_factor: float = Field( - ..., - description='The number indicates the factor with which the FRBC.OperationMode should be configured. The factor should be greater than or equal to 0 and less or equal to 1.', - ) - execution_time: AwareDatetime = Field( - ..., - description='Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.', - ) - abnormal_condition: bool = Field( - ..., - description='Indicates if this is an instruction during an abnormal condition.', - ) - - -class FRBCUsageForecast(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['FRBC.UsageForecast'] = 'FRBC.UsageForecast' - message_id: ID - start_time: AwareDatetime = Field( - ..., description='Time at which the FRBC.UsageForecast starts.' - ) - elements: List[FRBCUsageForecastElement] = Field( - ..., - description='Further elements that model the profile. There shall be at least one element. Elements must be placed in chronological order.', - max_length=288, - min_length=1, - ) - - -class FRBCFillLevelTargetProfile(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['FRBC.FillLevelTargetProfile'] = 'FRBC.FillLevelTargetProfile' - message_id: ID - start_time: AwareDatetime = Field( - ..., description='Time at which the FRBC.FillLevelTargetProfile starts.' - ) - elements: List[FRBCFillLevelTargetProfileElement] = Field( - ..., - description='List of different fill levels that have to be targeted within a given duration. There shall be at least one element. Elements must be placed in chronological order.', - max_length=288, - min_length=1, - ) - - -class DDBCActuatorStatus(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['DDBC.ActuatorStatus'] = 'DDBC.ActuatorStatus' - message_id: ID - actuator_id: ID = Field( - ..., description='ID of the actuator this messages refers to' - ) - active_operation_mode_id: ID = Field( - ..., - description='The operation mode that is presently active for this actuator.', - ) - operation_mode_factor: float = Field( - ..., - description='The number indicates the factor with which the DDBC.OperationMode is configured. The factor should be greater than or equal to 0 and less or equal to 1.', - ) - previous_operation_mode_id: Optional[ID] = Field( - None, - description='ID of the DDBC,OperationMode that was active before the present one. This value shall always be provided, unless the active DDBC.OperationMode is the first DDBC.OperationMode the Resource Manager is aware of.', - ) - transition_timestamp: Optional[AwareDatetime] = Field( - None, - description='Time at which the transition from the previous DDBC.OperationMode to the active DDBC.OperationMode was initiated. This value shall always be provided, unless the active DDBC.OperationMode is the first DDBC.OperationMode the Resource Manager is aware of.', - ) - - -class DDBCInstruction(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['DDBC.Instruction'] = 'DDBC.Instruction' - message_id: ID - id: ID = Field( - ..., - description='Identifier of this DDBC.Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', - ) - execution_time: AwareDatetime = Field( - ..., - description='Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.', - ) - abnormal_condition: bool = Field( - ..., - description='Indicates if this is an instruction during an abnormal condition', - ) - actuator_id: ID = Field( - ..., description='ID of the actuator this Instruction belongs to.' - ) - operation_mode_id: ID = Field(..., description='ID of the DDBC.OperationMode') - operation_mode_factor: float = Field( - ..., - description='The number indicates the factor with which the OMBC.OperationMode should be configured. The factor should be greater than or equal to 0 and less or equal to 1.', - ) - - -class DDBCAverageDemandRateForecast(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['DDBC.AverageDemandRateForecast'] = ( - 'DDBC.AverageDemandRateForecast' - ) - message_id: ID - start_time: AwareDatetime = Field(..., description='Start time of the profile.') - elements: List[DDBCAverageDemandRateForecastElement] = Field( - ..., - description='Elements of the profile. Elements must be placed in chronological order.', - max_length=288, - min_length=1, - ) - - -class PowerValue(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - commodity_quantity: CommodityQuantity = Field( - ..., description='The power quantity the value refers to' - ) - value: float = Field( - ..., - description='Power value expressed in the unit associated with the CommodityQuantity', - ) - - -class PowerForecastValue(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - value_upper_limit: Optional[float] = Field( - None, - description='The upper boundary of the range with 100 % certainty the power value is in it', - ) - value_upper_95PPR: Optional[float] = Field( - None, - description='The upper boundary of the range with 95 % certainty the power value is in it', - ) - value_upper_68PPR: Optional[float] = Field( - None, - description='The upper boundary of the range with 68 % certainty the power value is in it', - ) - value_expected: float = Field(..., description='The expected power value.') - value_lower_68PPR: Optional[float] = Field( - None, - description='The lower boundary of the range with 68 % certainty the power value is in it', - ) - value_lower_95PPR: Optional[float] = Field( - None, - description='The lower boundary of the range with 95 % certainty the power value is in it', - ) - value_lower_limit: Optional[float] = Field( - None, - description='The lower boundary of the range with 100 % certainty the power value is in it', - ) - commodity_quantity: CommodityQuantity = Field( - ..., description='The power quantity the value refers to' - ) - - -class PowerRange(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - start_of_range: float = Field( - ..., description='Power value that defines the start of the range.' - ) - end_of_range: float = Field( - ..., description='Power value that defines the end of the range.' - ) - commodity_quantity: CommodityQuantity = Field( - ..., description='The power quantity the values refer to' - ) - - -class Role(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - role: RoleType = Field( - ..., description='Role type of the Resource Manager for the given commodity' - ) - commodity: Commodity = Field(..., description='Commodity the role refers to.') - - -class PowerForecastElement(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - duration: Duration = Field(..., description='Duration of the PowerForecastElement') - power_values: List[PowerForecastValue] = Field( - ..., - description='The values of power that are expected for the given period of time. There shall be at least one PowerForecastValue, and at most one PowerForecastValue per CommodityQuantity.', - max_length=10, - min_length=1, - ) - - -class PEBCAllowedLimitRange(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - commodity_quantity: CommodityQuantity = Field( - ..., description='Type of power quantity this PEBC.AllowedLimitRange applies to' - ) - limit_type: PEBCPowerEnvelopeLimitType = Field( - ..., - description='Indicates if this ranges applies to the upper limit or the lower limit', - ) - range_boundary: NumberRange = Field( - ..., - description='Boundaries of the power range of this PEBC.AllowedLimitRange. The CEM is allowed to choose values within this range for the power envelope for the limit as described in limit_type. The start of the range shall be smaller or equal than the end of the range. ', - ) - abnormal_condition_only: bool = Field( - ..., - description='Indicates if this PEBC.AllowedLimitRange may only be used during an abnormal condition', - ) - - -class PEBCPowerEnvelope(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - id: ID = Field( - ..., - description='Identifier of this PEBC.PowerEnvelope. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', - ) - commodity_quantity: CommodityQuantity = Field( - ..., description='Type of power quantity this PEBC.PowerEnvelope applies to' - ) - power_envelope_elements: List[PEBCPowerEnvelopeElement] = Field( - ..., - description='The elements of this PEBC.PowerEnvelope. Shall contain at least one element. Elements must be placed in chronological order.', - max_length=288, - min_length=1, - ) - - -class PPBCPowerSequenceElement(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - duration: Duration = Field( - ..., description='Duration of the PPBC.PowerSequenceElement.' - ) - power_values: List[PowerForecastValue] = Field( - ..., - description='The value of power and deviations for the given duration. The array should contain at least one PowerForecastValue and at most one PowerForecastValue per CommodityQuantity.', - max_length=10, - min_length=1, - ) - - -class PPBCPowerSequenceContainerStatus(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - power_profile_id: ID = Field( - ..., - description='ID of the PPBC.PowerProfileDefinition of which the data element ‘sequence_container_id’ refers to. ', - ) - sequence_container_id: ID = Field( - ..., - description='ID of the PPBC.PowerSequenceContainer this PPBC.PowerSequenceContainerStatus provides information about.', - ) - selected_sequence_id: Optional[ID] = Field( - None, - description='ID of selected PPBC.PowerSequence. When no ID is given, no sequence was selected yet.', - ) - progress: Optional[Duration] = Field( - None, - description='Time that has passed since the selected sequence has started. A value must be provided, unless no sequence has been selected or the selected sequence hasn’t started yet.', - ) - status: PPBCPowerSequenceStatus = Field( - ..., description='Status of the selected PPBC.PowerSequence' - ) - - -class OMBCOperationMode(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - id: ID = Field( - ..., - description='ID of the OBMC.OperationMode. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', - ) - diagnostic_label: Optional[str] = Field( - None, - description='Human readable name/description of the OMBC.OperationMode. This element is only intended for diagnostic purposes and not for HMI applications.', - ) - power_ranges: List[PowerRange] = Field( - ..., - description='The power produced or consumed by this operation mode. The start of each PowerRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1. In the array there must be at least one PowerRange, and at most one PowerRange per CommodityQuantity.', - max_length=10, - min_length=1, - ) - running_costs: Optional[NumberRange] = Field( - None, - description='Additional costs per second (e.g. wear, services) associated with this operation mode in the currency defined by the ResourceManagerDetails , excluding the commodity cost. The range is expressing uncertainty and is not linked to the operation_mode_factor.', - ) - abnormal_condition_only: bool = Field( - ..., - description='Indicates if this OMBC.OperationMode may only be used during an abnormal condition.', - ) - - -class FRBCOperationModeElement(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - fill_level_range: NumberRange = Field( - ..., - description='The range of the fill level for which this FRBC.OperationModeElement applies. The start of the NumberRange shall be smaller than the end of the NumberRange.', - ) - fill_rate: NumberRange = Field( - ..., - description='Indicates the change in fill_level per second. The lower_boundary of the NumberRange is associated with an operation_mode_factor of 0, the upper_boundary is associated with an operation_mode_factor of 1. ', - ) - power_ranges: List[PowerRange] = Field( - ..., - description='The power produced or consumed by this operation mode. The start of each PowerRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1. In the array there must be at least one PowerRange, and at most one PowerRange per CommodityQuantity.', - max_length=10, - min_length=1, - ) - running_costs: Optional[NumberRange] = Field( - None, - description='Additional costs per second (e.g. wear, services) associated with this operation mode in the currency defined by the ResourceManagerDetails, excluding the commodity cost. The range is expressing uncertainty and is not linked to the operation_mode_factor.', - ) - - -class DDBCOperationMode(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - Id: ID = Field( - ..., - description='ID of this operation mode. Must be unique in the scope of the DDBC.ActuatorDescription in which it is used.', - ) - diagnostic_label: Optional[str] = Field( - None, - description='Human readable name/description of the DDBC.OperationMode. This element is only intended for diagnostic purposes and not for HMI applications.', - ) - power_ranges: List[PowerRange] = Field( - ..., - description='The power produced or consumed by this operation mode. The start of each PowerRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1. In the array there must be at least one PowerRange, and at most one PowerRange per CommodityQuantity.', - max_length=10, - min_length=1, - ) - supply_range: NumberRange = Field( - ..., - description='The supply rate this DDBC.OperationMode can deliver for the CEM to match the demand rate. The start of the NumberRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1.', - ) - running_costs: Optional[NumberRange] = Field( - None, - description='Additional costs per second (e.g. wear, services) associated with this operation mode in the currency defined by the ResourceManagerDetails, excluding the commodity cost. The range is expressing uncertainty and is not linked to the operation_mode_factor.', - ) - abnormal_condition_only: bool = Field( - ..., - description='Indicates if this DDBC.OperationMode may only be used during an abnormal condition.', - ) - - -class ResourceManagerDetails(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['ResourceManagerDetails'] = 'ResourceManagerDetails' - message_id: ID - resource_id: ID = Field( - ..., - description='Identifier of the Resource Manager. Must be unique within the scope of the CEM.', - ) - name: Optional[str] = Field(None, description='Human readable name given by user') - roles: List[Role] = Field( - ..., - description='Each Resource Manager provides one or more energy Roles', - max_length=3, - min_length=1, - ) - manufacturer: Optional[str] = Field(None, description='Name of Manufacturer') - model: Optional[str] = Field( - None, - description='Name of the model of the device (provided by the manufacturer)', - ) - serial_number: Optional[str] = Field( - None, description='Serial number of the device (provided by the manufacturer)' - ) - firmware_version: Optional[str] = Field( - None, - description='Version identifier of the firmware used in the device (provided by the manufacturer)', - ) - instruction_processing_delay: Duration = Field( - ..., - description='The average time the combination of Resource Manager and HBES/BACS/SASS or (Smart) device needs to process and execute an instruction', - ) - available_control_types: List[ControlType] = Field( - ..., - description='The control types supported by this Resource Manager.', - max_length=5, - min_length=1, - ) - currency: Optional[Currency] = Field( - None, - description='Currency to be used for all information regarding costs. Mandatory if cost information is published.', - ) - provides_forecast: bool = Field( - ..., - description='Indicates whether the ResourceManager is able to provide PowerForecasts', - ) - provides_power_measurement_types: List[CommodityQuantity] = Field( - ..., - description='Array of all CommodityQuantities that this Resource Manager can provide measurements for. ', - max_length=10, - min_length=1, - ) - - -class PowerMeasurement(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['PowerMeasurement'] = 'PowerMeasurement' - message_id: ID - measurement_timestamp: AwareDatetime = Field( - ..., description='Timestamp when PowerValues were measured.' - ) - values: List[PowerValue] = Field( - ..., - description='Array of measured PowerValues. Must contain at least one item and at most one item per ‘commodity_quantity’ (defined inside the PowerValue).', - max_length=10, - min_length=1, - ) - - -class PowerForecast(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['PowerForecast'] = 'PowerForecast' - message_id: ID - start_time: AwareDatetime = Field( - ..., description='Start time of time period that is covered by the profile.' - ) - elements: List[PowerForecastElement] = Field( - ..., - description='Elements of which this forecast consists. Contains at least one element. Elements must be placed in chronological order.', - max_length=288, - min_length=1, - ) - - -class PEBCPowerConstraints(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['PEBC.PowerConstraints'] = 'PEBC.PowerConstraints' - message_id: ID - id: ID = Field( - ..., - description='Identifier of this PEBC.PowerConstraints. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', - ) - valid_from: AwareDatetime = Field( - ..., description='Moment this PEBC.PowerConstraints start to be valid' - ) - valid_until: Optional[AwareDatetime] = Field( - None, - description='Moment until this PEBC.PowerConstraints is valid. If valid_until is not present, there is no determined end time of this PEBC.PowerConstraints.', - ) - consequence_type: PEBCPowerEnvelopeConsequenceType = Field( - ..., description='Type of consequence of limiting power' - ) - allowed_limit_ranges: List[PEBCAllowedLimitRange] = Field( - ..., - description='The actual constraints. There shall be at least one PEBC.AllowedLimitRange for the UPPER_LIMIT and at least one AllowedLimitRange for the LOWER_LIMIT. It is allowed to have multiple PEBC.AllowedLimitRange objects with identical CommodityQuantities and LimitTypes.', - max_length=100, - min_length=2, - ) - - -class PEBCInstruction(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['PEBC.Instruction'] = 'PEBC.Instruction' - message_id: ID - id: ID = Field( - ..., - description='Identifier of this PEBC.Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', - ) - execution_time: AwareDatetime = Field( - ..., - description='Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.', - ) - abnormal_condition: bool = Field( - ..., - description='Indicates if this is an instruction during an abnormal condition.', - ) - power_constraints_id: ID = Field( - ..., - description='Identifier of the PEBC.PowerConstraints this PEBC.Instruction was based on.', - ) - power_envelopes: List[PEBCPowerEnvelope] = Field( - ..., - description='The PEBC.PowerEnvelope(s) that should be followed by the Resource Manager. There shall be at least one PEBC.PowerEnvelope, but at most one PEBC.PowerEnvelope for each CommodityQuantity.', - max_length=10, - min_length=1, - ) - - -class PPBCPowerProfileStatus(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['PPBC.PowerProfileStatus'] = 'PPBC.PowerProfileStatus' - message_id: ID - sequence_container_status: List[PPBCPowerSequenceContainerStatus] = Field( - ..., - description='Array with status information for all PPBC.PowerSequenceContainers in the PPBC.PowerProfileDefinition.', - max_length=1000, - min_length=1, - ) - - -class OMBCSystemDescription(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['OMBC.SystemDescription'] = 'OMBC.SystemDescription' - message_id: ID - valid_from: AwareDatetime = Field( - ..., - description='Moment this OMBC.SystemDescription starts to be valid. If the system description is immediately valid, the DateTimeStamp should be now or in the past.', - ) - operation_modes: List[OMBCOperationMode] = Field( - ..., - description='OMBC.OperationModes available for the CEM in order to coordinate the device behaviour.', - max_length=100, - min_length=1, - ) - transitions: List[Transition] = Field( - ..., - description='Possible transitions to switch from one OMBC.OperationMode to another.', - max_length=1000, - min_length=0, - ) - timers: List[Timer] = Field( - ..., - description='Timers that control when certain transitions can be made.', - max_length=1000, - min_length=0, - ) - - -class PPBCPowerSequence(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - id: ID = Field( - ..., - description='ID of the PPBC.PowerSequence. Must be unique in the scope of the PPBC.PowerSequnceContainer in which it is used.', - ) - elements: List[PPBCPowerSequenceElement] = Field( - ..., - description='List of PPBC.PowerSequenceElements. Shall contain at least one element. Elements must be placed in chronological order.', - max_length=288, - min_length=1, - ) - is_interruptible: bool = Field( - ..., - description='Indicates whether the option of pausing a sequence is available.', - ) - max_pause_before: Optional[Duration] = Field( - None, - description='The maximum duration for which a device can be paused between the end of the previous running sequence and the start of this one', - ) - abnormal_condition_only: bool = Field( - ..., - description='Indicates if this PPBC.PowerSequence may only be used during an abnormal condition', - ) - - -class FRBCOperationMode(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - id: ID = Field( - ..., - description='ID of the FRBC.OperationMode. Must be unique in the scope of the FRBC.ActuatorDescription in which it is used.', - ) - diagnostic_label: Optional[str] = Field( - None, - description='Human readable name/description of the FRBC.OperationMode. This element is only intended for diagnostic purposes and not for HMI applications.', - ) - elements: List[FRBCOperationModeElement] = Field( - ..., - description='List of FRBC.OperationModeElements, which describe the properties of this FRBC.OperationMode depending on the fill_level. The fill_level_ranges of the items in the Array must be contiguous.', - max_length=100, - min_length=1, - ) - abnormal_condition_only: bool = Field( - ..., - description='Indicates if this FRBC.OperationMode may only be used during an abnormal condition', - ) - - -class DDBCActuatorDescription(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - id: ID = Field( - ..., - description='ID of this DDBC.ActuatorDescription. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', - ) - diagnostic_label: Optional[str] = Field( - None, - description='Human readable name/description of the actuator. This element is only intended for diagnostic purposes and not for HMI applications.', - ) - supported_commodites: List[Commodity] = Field( - ..., - description='Commodities supported by the operation modes of this actuator. There shall be at least one commodity', - max_length=4, - min_length=1, - ) - operation_modes: List[DDBCOperationMode] = Field( - ..., - description='List of all Operation Modes that are available for this actuator. There shall be at least one DDBC.OperationMode.', - max_length=100, - min_length=1, - ) - transitions: List[Transition] = Field( - ..., - description='List of Transitions between Operation Modes. Shall contain at least one Transition.', - max_length=1000, - min_length=0, - ) - timers: List[Timer] = Field( - ..., - description='List of Timers associated with Transitions for this Actuator. Can be empty.', - max_length=1000, - min_length=0, - ) - - -class DDBCSystemDescription(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['DDBC.SystemDescription'] = 'DDBC.SystemDescription' - message_id: ID - valid_from: AwareDatetime = Field( - ..., - description='Moment this DDBC.SystemDescription starts to be valid. If the system description is immediately valid, the DateTimeStamp should be now or in the past.', - ) - actuators: List[DDBCActuatorDescription] = Field( - ..., - description='List of all available actuators in the system. Must contain at least one DDBC.ActuatorAggregated.', - max_length=10, - min_length=1, - ) - present_demand_rate: NumberRange = Field( - ..., description='Present demand rate that needs to be satisfied by the system' - ) - provides_average_demand_rate_forecast: bool = Field( - ..., - description='Indicates whether the Resource Manager could provide a demand rate forecast through the DDBC.AverageDemandRateForecast.', - ) - - -class PPBCPowerSequenceContainer(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - id: ID = Field( - ..., - description='ID of the PPBC.PowerSequenceContainer. Must be unique in the scope of the PPBC.PowerProfileDefinition in which it is used.', - ) - power_sequences: List[PPBCPowerSequence] = Field( - ..., - description='List of alternative Sequences where one could be chosen by the CEM', - max_length=288, - min_length=1, - ) - - -class FRBCActuatorDescription(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - id: ID = Field( - ..., - description='ID of the Actuator. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', - ) - diagnostic_label: Optional[str] = Field( - None, - description='Human readable name/description for the actuator. This element is only intended for diagnostic purposes and not for HMI applications.', - ) - supported_commodities: List[Commodity] = Field( - ..., - description='List of all supported Commodities.', - max_length=4, - min_length=1, - ) - operation_modes: List[FRBCOperationMode] = Field( - ..., - description='Provided FRBC.OperationModes associated with this actuator', - max_length=100, - min_length=1, - ) - transitions: List[Transition] = Field( - ..., - description='Possible transitions between FRBC.OperationModes associated with this actuator.', - max_length=1000, - min_length=0, - ) - timers: List[Timer] = Field( - ..., - description='List of Timers associated with this actuator', - max_length=1000, - min_length=0, - ) - - -class PPBCPowerProfileDefinition(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['PPBC.PowerProfileDefinition'] = 'PPBC.PowerProfileDefinition' - message_id: ID - id: ID = Field( - ..., - description='ID of the PPBC.PowerProfileDefinition. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', - ) - start_time: AwareDatetime = Field( - ..., - description='Indicates the first possible time the first PPBC.PowerSequence could start', - ) - end_time: AwareDatetime = Field( - ..., - description='Indicates when the last PPBC.PowerSequence shall be finished at the latest', - ) - power_sequences_containers: List[PPBCPowerSequenceContainer] = Field( - ..., - description='The PPBC.PowerSequenceContainers that make up this PPBC.PowerProfileDefinition. There shall be at least one PPBC.PowerSequenceContainer that includes at least one PPBC.PowerSequence. PPBC.PowerSequenceContainers must be placed in chronological order.', - max_length=1000, - min_length=1, - ) - - -class FRBCSystemDescription(BaseModel): - model_config = ConfigDict( - extra='forbid', - ) - message_type: Literal['FRBC.SystemDescription'] = 'FRBC.SystemDescription' - message_id: ID - valid_from: AwareDatetime = Field( - ..., - description='Moment this FRBC.SystemDescription starts to be valid. If the system description is immediately valid, the DateTimeStamp should be now or in the past.', - ) - actuators: List[FRBCActuatorDescription] = Field( - ..., description='Details of all Actuators.', max_length=10, min_length=1 - ) - storage: FRBCStorageDescription = Field(..., description='Details of the storage.') diff --git a/build/lib/s2python/py.typed b/build/lib/s2python/py.typed deleted file mode 100644 index e69de29..0000000 diff --git a/build/lib/s2python/reception_status_awaiter.py b/build/lib/s2python/reception_status_awaiter.py deleted file mode 100644 index 5c4bd42..0000000 --- a/build/lib/s2python/reception_status_awaiter.py +++ /dev/null @@ -1,60 +0,0 @@ -"""ReceptationStatusAwaiter class which notifies any coroutine waiting for a certain reception status message. - -Copied from -https://github.com/flexiblepower/s2-analyzer/blob/main/backend/s2_analyzer_backend/reception_status_awaiter.py under -Apache2 license on 31-08-2024. -""" - -import asyncio -import uuid -from typing import Dict - -from s2python.common import ReceptionStatus - - -class ReceptionStatusAwaiter: - received: Dict[uuid.UUID, ReceptionStatus] - awaiting: Dict[uuid.UUID, asyncio.Event] - - def __init__(self) -> None: - self.received = {} - self.awaiting = {} - - async def wait_for_reception_status( - self, message_id: uuid.UUID, timeout_reception_status: float - ) -> ReceptionStatus: - if message_id in self.received: - reception_status = self.received[message_id] - else: - if message_id in self.awaiting: - received_event = self.awaiting[message_id] - else: - received_event = asyncio.Event() - self.awaiting[message_id] = received_event - - await asyncio.wait_for(received_event.wait(), timeout_reception_status) - reception_status = self.received[message_id] - - if message_id in self.awaiting: - del self.awaiting[message_id] - - return reception_status - - async def receive_reception_status(self, reception_status: ReceptionStatus) -> None: - if not isinstance(reception_status, ReceptionStatus): - raise RuntimeError( - f"Expected a ReceptionStatus but received message {reception_status}" - ) - - if reception_status.subject_message_id in self.received: - raise RuntimeError( - f"ReceptationStatus for message_subject_id {reception_status.subject_message_id} has already " - f"been received!" - ) - - self.received[reception_status.subject_message_id] = reception_status - awaiting = self.awaiting.get(reception_status.subject_message_id) - - if awaiting: - awaiting.set() - del self.awaiting[reception_status.subject_message_id] diff --git a/build/lib/s2python/s2_connection.py b/build/lib/s2python/s2_connection.py deleted file mode 100644 index 188ecc7..0000000 --- a/build/lib/s2python/s2_connection.py +++ /dev/null @@ -1,526 +0,0 @@ -import asyncio -import json -import logging -import time -import threading -import uuid -from dataclasses import dataclass -from typing import Optional, List, Type, Dict, Callable, Awaitable, Union - -import websockets -from websockets.asyncio.client import ClientConnection as WSConnection, connect as ws_connect - -from s2python.common import ( - ReceptionStatusValues, - ReceptionStatus, - Handshake, - EnergyManagementRole, - Role, - HandshakeResponse, - ResourceManagerDetails, - Duration, - Currency, - SelectControlType, -) -from s2python.generated.gen_s2 import CommodityQuantity -from s2python.reception_status_awaiter import ReceptionStatusAwaiter -from s2python.s2_control_type import S2ControlType -from s2python.s2_parser import S2Parser -from s2python.s2_validation_error import S2ValidationError -from s2python.validate_values_mixin import S2Message -from s2python.version import S2_VERSION - -logger = logging.getLogger("s2python") - - -@dataclass -class AssetDetails: # pylint: disable=too-many-instance-attributes - resource_id: str - - provides_forecast: bool - provides_power_measurements: List[CommodityQuantity] - - instruction_processing_delay: Duration - roles: List[Role] - currency: Optional[Currency] = None - - name: Optional[str] = None - manufacturer: Optional[str] = None - model: Optional[str] = None - firmware_version: Optional[str] = None - serial_number: Optional[str] = None - - def to_resource_manager_details( - self, control_types: List[S2ControlType] - ) -> ResourceManagerDetails: - return ResourceManagerDetails( - available_control_types=[ - control_type.get_protocol_control_type() for control_type in control_types - ], - currency=self.currency, - firmware_version=self.firmware_version, - instruction_processing_delay=self.instruction_processing_delay, - manufacturer=self.manufacturer, - message_id=uuid.uuid4(), - model=self.model, - name=self.name, - provides_forecast=self.provides_forecast, - provides_power_measurement_types=self.provides_power_measurements, - resource_id=self.resource_id, - roles=self.roles, - serial_number=self.serial_number, - ) - - -S2MessageHandler = Union[ - Callable[["S2Connection", S2Message, Callable[[], None]], None], - Callable[["S2Connection", S2Message, Awaitable[None]], Awaitable[None]], -] - - -class SendOkay: - status_is_send: threading.Event - connection: "S2Connection" - subject_message_id: uuid.UUID - - def __init__(self, connection: "S2Connection", subject_message_id: uuid.UUID): - self.status_is_send = threading.Event() - self.connection = connection - self.subject_message_id = subject_message_id - - async def run_async(self) -> None: - self.status_is_send.set() - - await self.connection.respond_with_reception_status( - subject_message_id=str(self.subject_message_id), - status=ReceptionStatusValues.OK, - diagnostic_label="Processed okay.", - ) - - def run_sync(self) -> None: - self.status_is_send.set() - - self.connection.respond_with_reception_status_sync( - subject_message_id=str(self.subject_message_id), - status=ReceptionStatusValues.OK, - diagnostic_label="Processed okay.", - ) - - async def ensure_send_async(self, type_msg: Type[S2Message]) -> None: - if not self.status_is_send.is_set(): - logger.warning( - "Handler for message %s %s did not call send_okay / function to send the ReceptionStatus. " - "Sending it now.", - type_msg, - self.subject_message_id, - ) - await self.run_async() - - def ensure_send_sync(self, type_msg: Type[S2Message]) -> None: - if not self.status_is_send.is_set(): - logger.warning( - "Handler for message %s %s did not call send_okay / function to send the ReceptionStatus. " - "Sending it now.", - type_msg, - self.subject_message_id, - ) - self.run_sync() - - -class MessageHandlers: - handlers: Dict[Type[S2Message], S2MessageHandler] - - def __init__(self) -> None: - self.handlers = {} - - async def handle_message(self, connection: "S2Connection", msg: S2Message) -> None: - """Handle the S2 message using the registered handler. - - :param connection: The S2 conncetion the `msg` is received from. - :param msg: The S2 message - """ - handler = self.handlers.get(type(msg)) - if handler is not None: - send_okay = SendOkay(connection, msg.message_id) # type: ignore[attr-defined] - - try: - if asyncio.iscoroutinefunction(handler): - await handler(connection, msg, send_okay.run_async()) # type: ignore[arg-type] - await send_okay.ensure_send_async(type(msg)) - else: - - def do_message() -> None: - handler(connection, msg, send_okay.run_sync) # type: ignore[arg-type] - send_okay.ensure_send_sync(type(msg)) - - eventloop = asyncio.get_event_loop() - await eventloop.run_in_executor(executor=None, func=do_message) - except Exception: - if not send_okay.status_is_send.is_set(): - await connection.respond_with_reception_status( - subject_message_id=str(msg.message_id), # type: ignore[attr-defined] - status=ReceptionStatusValues.PERMANENT_ERROR, - diagnostic_label=f"While processing message {msg.message_id} " # type: ignore[attr-defined] - f"an unrecoverable error occurred.", - ) - raise - else: - logger.warning( - "Received a message of type %s but no handler is registered. Ignoring the message.", - type(msg), - ) - - def register_handler(self, msg_type: Type[S2Message], handler: S2MessageHandler) -> None: - """Register a coroutine function or a normal function as the handler for a specific S2 message type. - - :param msg_type: The S2 message type to attach the handler to. - :param handler: The function (asynchronuous or normal) which should handle the S2 message. - """ - self.handlers[msg_type] = handler - - -class S2Connection: # pylint: disable=too-many-instance-attributes - url: str - reconnect: bool - reception_status_awaiter: ReceptionStatusAwaiter - ws: Optional[WSConnection] - s2_parser: S2Parser - control_types: List[S2ControlType] - role: EnergyManagementRole - asset_details: AssetDetails - - _thread: threading.Thread - - _handlers: MessageHandlers - _current_control_type: Optional[S2ControlType] - _received_messages: asyncio.Queue - - _eventloop: asyncio.AbstractEventLoop - _stop_event: asyncio.Event - _restart_connection_event: asyncio.Event - - def __init__( # pylint: disable=too-many-arguments - self, - url: str, - role: EnergyManagementRole, - control_types: List[S2ControlType], - asset_details: AssetDetails, - reconnect: bool = False, - ) -> None: - self.url = url - self.reconnect = reconnect - self.reception_status_awaiter = ReceptionStatusAwaiter() - self.ws = None - self.s2_parser = S2Parser() - - self._handlers = MessageHandlers() - self._current_control_type = None - - self._eventloop = asyncio.new_event_loop() - - self.control_types = control_types - self.role = role - self.asset_details = asset_details - - self._handlers.register_handler(SelectControlType, self.handle_select_control_type_as_rm) - self._handlers.register_handler(Handshake, self.handle_handshake) - self._handlers.register_handler(HandshakeResponse, self.handle_handshake_response_as_rm) - - def start_as_rm(self) -> None: - self._run_eventloop(self._run_as_rm()) - - def _run_eventloop(self, main_task: Awaitable[None]) -> None: - self._thread = threading.current_thread() - logger.debug("Starting eventloop") - try: - self._eventloop.run_until_complete(main_task) - except asyncio.CancelledError: - pass - logger.debug("S2 connection thread has stopped.") - - def stop(self) -> None: - """Stops the S2 connection. - - Note: Ensure this method is called from a different thread than the thread running the S2 connection. - Otherwise it will block waiting on the coroutine _do_stop to terminate successfully but it can't run - the coroutine. A `RuntimeError` will be raised to prevent the indefinite block. - """ - if threading.current_thread() == self._thread: - raise RuntimeError( - "Do not call stop from the thread running the S2 connection. This results in an " - "infinite block!" - ) - if self._eventloop.is_running(): - asyncio.run_coroutine_threadsafe(self._do_stop(), self._eventloop).result() - self._thread.join() - logger.info("Stopped the S2 connection.") - - async def _do_stop(self) -> None: - logger.info("Will stop the S2 connection.") - self._stop_event.set() - - async def _run_as_rm(self) -> None: - logger.debug("Connecting as S2 resource manager.") - - self._stop_event = asyncio.Event() - - first_run = True - - while (first_run or self.reconnect) and not self._stop_event.is_set(): - first_run = False - self._restart_connection_event = asyncio.Event() - await self._connect_and_run() - time.sleep(1) - - logger.debug("Finished S2 connection eventloop.") - - async def _connect_and_run(self) -> None: - self._received_messages = asyncio.Queue() - await self._connect_ws() - if self.ws: - - async def wait_till_stop() -> None: - await self._stop_event.wait() - - async def wait_till_connection_restart() -> None: - await self._restart_connection_event.wait() - - background_tasks = [ - self._eventloop.create_task(self._receive_messages()), - self._eventloop.create_task(wait_till_stop()), - self._eventloop.create_task(self._connect_as_rm()), - self._eventloop.create_task(wait_till_connection_restart()), - ] - - (done, pending) = await asyncio.wait( - background_tasks, return_when=asyncio.FIRST_COMPLETED - ) - if self._current_control_type: - self._current_control_type.deactivate(self) - self._current_control_type = None - - for task in done: - try: - await task - except asyncio.CancelledError: - pass - except (websockets.ConnectionClosedError, websockets.ConnectionClosedOK): - logger.info("The other party closed the websocket connection.") - - for task in pending: - try: - task.cancel() - await task - except asyncio.CancelledError: - pass - - await self.ws.close() - await self.ws.wait_closed() - - async def _connect_ws(self) -> None: - try: - self.ws = await ws_connect(uri=self.url) - except (EOFError, OSError) as e: - logger.info("Could not connect due to: %s", str(e)) - - async def _connect_as_rm(self) -> None: - await self.send_msg_and_await_reception_status_async( - Handshake( - message_id=uuid.uuid4(), role=self.role, supported_protocol_versions=[S2_VERSION] - ) - ) - logger.debug("Send handshake to CEM. Expecting Handshake and HandshakeResponse from CEM.") - - await self._handle_received_messages() - - async def handle_handshake( - self, _: "S2Connection", message: S2Message, send_okay: Awaitable[None] - ) -> None: - if not isinstance(message, Handshake): - logger.error( - "Handler for Handshake received a message of the wrong type: %s", type(message) - ) - return - - logger.debug( - "%s supports S2 protocol versions: %s", - message.role, - message.supported_protocol_versions, - ) - await send_okay - - async def handle_handshake_response_as_rm( - self, _: "S2Connection", message: S2Message, send_okay: Awaitable[None] - ) -> None: - if not isinstance(message, HandshakeResponse): - logger.error( - "Handler for HandshakeResponse received a message of the wrong type: %s", - type(message), - ) - return - - logger.debug("Received HandshakeResponse %s", message.to_json()) - - logger.debug("CEM selected to use version %s", message.selected_protocol_version) - await send_okay - logger.debug("Handshake complete. Sending first ResourceManagerDetails.") - - await self.send_msg_and_await_reception_status_async( - self.asset_details.to_resource_manager_details(self.control_types) - ) - - async def handle_select_control_type_as_rm( - self, _: "S2Connection", message: S2Message, send_okay: Awaitable[None] - ) -> None: - if not isinstance(message, SelectControlType): - logger.error( - "Handler for SelectControlType received a message of the wrong type: %s", - type(message), - ) - return - - await send_okay - - logger.debug("CEM selected control type %s. Activating control type.", message.control_type) - - control_types_by_protocol_name = { - c.get_protocol_control_type(): c for c in self.control_types - } - selected_control_type: Optional[S2ControlType] = control_types_by_protocol_name.get( - message.control_type - ) - - if self._current_control_type is not None: - await self._eventloop.run_in_executor(None, self._current_control_type.deactivate, self) - - self._current_control_type = selected_control_type - - if self._current_control_type is not None: - await self._eventloop.run_in_executor(None, self._current_control_type.activate, self) - self._current_control_type.register_handlers(self._handlers) - - async def _receive_messages(self) -> None: - """Receives all incoming messages in the form of a generator. - - Will also receive the ReceptionStatus messages but instead of yielding these messages, they are routed - to any calls of `send_msg_and_await_reception_status`. - """ - if self.ws is None: - raise RuntimeError( - "Cannot receive messages if websocket connection is not yet established." - ) - - logger.info("S2 connection has started to receive messages.") - - async for message in self.ws: - try: - s2_msg: S2Message = self.s2_parser.parse_as_any_message(message) - except json.JSONDecodeError: - await self._send_and_forget( - ReceptionStatus( - subject_message_id="00000000-0000-0000-0000-000000000000", - status=ReceptionStatusValues.INVALID_DATA, - diagnostic_label="Not valid json.", - ) - ) - except S2ValidationError as e: - json_msg = json.loads(message) - message_id = json_msg.get("message_id") - if message_id: - await self.respond_with_reception_status( - subject_message_id=message_id, - status=ReceptionStatusValues.INVALID_MESSAGE, - diagnostic_label=str(e), - ) - else: - await self.respond_with_reception_status( - subject_message_id="00000000-0000-0000-0000-000000000000", - status=ReceptionStatusValues.INVALID_DATA, - diagnostic_label="Message appears valid json but could not find a message_id field.", - ) - else: - logger.debug("Received message %s", s2_msg.to_json()) - - if isinstance(s2_msg, ReceptionStatus): - logger.debug( - "Message is a reception status for %s so registering in cache.", - s2_msg.subject_message_id, - ) - await self.reception_status_awaiter.receive_reception_status(s2_msg) - else: - await self._received_messages.put(s2_msg) - - async def _send_and_forget(self, s2_msg: S2Message) -> None: - if self.ws is None: - raise RuntimeError( - "Cannot send messages if websocket connection is not yet established." - ) - - json_msg = s2_msg.to_json() - logger.debug("Sending message %s", json_msg) - try: - await self.ws.send(json_msg) - except websockets.ConnectionClosedError as e: - logger.error("Unable to send message %s due to %s", s2_msg, str(e)) - self._restart_connection_event.set() - - async def respond_with_reception_status( - self, subject_message_id: str, status: ReceptionStatusValues, diagnostic_label: str - ) -> None: - logger.debug("Responding to message %s with status %s", subject_message_id, status) - await self._send_and_forget( - ReceptionStatus( - subject_message_id=subject_message_id, - status=status, - diagnostic_label=diagnostic_label, - ) - ) - - def respond_with_reception_status_sync( - self, subject_message_id: str, status: ReceptionStatusValues, diagnostic_label: str - ) -> None: - asyncio.run_coroutine_threadsafe( - self.respond_with_reception_status(subject_message_id, status, diagnostic_label), - self._eventloop, - ).result() - - async def send_msg_and_await_reception_status_async( - self, s2_msg: S2Message, timeout_reception_status: float = 5.0, raise_on_error: bool = True - ) -> ReceptionStatus: - await self._send_and_forget(s2_msg) - logger.debug( - "Waiting for ReceptionStatus for %s %s seconds", - s2_msg.message_id, # type: ignore[attr-defined] - timeout_reception_status, - ) - try: - reception_status = await self.reception_status_awaiter.wait_for_reception_status( - s2_msg.message_id, timeout_reception_status # type: ignore[attr-defined] - ) - except TimeoutError: - logger.error( - "Did not receive a reception status on time for %s", - s2_msg.message_id, # type: ignore[attr-defined] - ) - self._stop_event.set() - raise - - if reception_status.status != ReceptionStatusValues.OK and raise_on_error: - raise RuntimeError(f"ReceptionStatus was not OK but rather {reception_status.status}") - - return reception_status - - def send_msg_and_await_reception_status_sync( - self, s2_msg: S2Message, timeout_reception_status: float = 5.0, raise_on_error: bool = True - ) -> ReceptionStatus: - return asyncio.run_coroutine_threadsafe( - self.send_msg_and_await_reception_status_async( - s2_msg, timeout_reception_status, raise_on_error - ), - self._eventloop, - ).result() - - async def _handle_received_messages(self) -> None: - while True: - msg = await self._received_messages.get() - await self._handlers.handle_message(self, msg) diff --git a/build/lib/s2python/s2_control_type.py b/build/lib/s2python/s2_control_type.py deleted file mode 100644 index f9a4545..0000000 --- a/build/lib/s2python/s2_control_type.py +++ /dev/null @@ -1,56 +0,0 @@ -import abc -import typing - -from s2python.common import ControlType as ProtocolControlType -from s2python.frbc import FRBCInstruction -from s2python.validate_values_mixin import S2Message - -if typing.TYPE_CHECKING: - from s2python.s2_connection import S2Connection, MessageHandlers - - -class S2ControlType(abc.ABC): - @abc.abstractmethod - def get_protocol_control_type(self) -> ProtocolControlType: ... - - @abc.abstractmethod - def register_handlers(self, handlers: "MessageHandlers") -> None: ... - - @abc.abstractmethod - def activate(self, conn: "S2Connection") -> None: ... - - @abc.abstractmethod - def deactivate(self, conn: "S2Connection") -> None: ... - - -class FRBCControlType(S2ControlType): - def get_protocol_control_type(self) -> ProtocolControlType: - return ProtocolControlType.FILL_RATE_BASED_CONTROL - - def register_handlers(self, handlers: "MessageHandlers") -> None: - handlers.register_handler(FRBCInstruction, self.handle_instruction) - - @abc.abstractmethod - def handle_instruction( - self, conn: "S2Connection", msg: S2Message, send_okay: typing.Callable[[], None] - ) -> None: ... - - @abc.abstractmethod - def activate(self, conn: "S2Connection") -> None: ... - - @abc.abstractmethod - def deactivate(self, conn: "S2Connection") -> None: ... - - -class NoControlControlType(S2ControlType): - def get_protocol_control_type(self) -> ProtocolControlType: - return ProtocolControlType.NOT_CONTROLABLE - - def register_handlers(self, handlers: "MessageHandlers") -> None: - pass - - @abc.abstractmethod - def activate(self, conn: "S2Connection") -> None: ... - - @abc.abstractmethod - def deactivate(self, conn: "S2Connection") -> None: ... diff --git a/build/lib/s2python/s2_parser.py b/build/lib/s2python/s2_parser.py deleted file mode 100644 index 906a286..0000000 --- a/build/lib/s2python/s2_parser.py +++ /dev/null @@ -1,113 +0,0 @@ -import json -import logging -from typing import Optional, TypeVar, Union, Type, Dict - -from s2python.common import ( - Handshake, - HandshakeResponse, - InstructionStatusUpdate, - PowerForecast, - PowerMeasurement, - ReceptionStatus, - ResourceManagerDetails, - RevokeObject, - SelectControlType, - SessionRequest, -) -from s2python.frbc import ( - FRBCActuatorStatus, - FRBCFillLevelTargetProfile, - FRBCInstruction, - FRBCLeakageBehaviour, - FRBCStorageStatus, - FRBCSystemDescription, - FRBCTimerStatus, - FRBCUsageForecast, -) -from s2python.validate_values_mixin import S2Message -from s2python.s2_validation_error import S2ValidationError - - -LOGGER = logging.getLogger(__name__) -S2MessageType = str - -M = TypeVar("M", bound=S2Message) - - -# May be generated with development_utilities/generate_s2_message_type_to_class.py -TYPE_TO_MESSAGE_CLASS: Dict[str, Type[S2Message]] = { - "FRBC.ActuatorStatus": FRBCActuatorStatus, - "FRBC.FillLevelTargetProfile": FRBCFillLevelTargetProfile, - "FRBC.Instruction": FRBCInstruction, - "FRBC.LeakageBehaviour": FRBCLeakageBehaviour, - "FRBC.StorageStatus": FRBCStorageStatus, - "FRBC.SystemDescription": FRBCSystemDescription, - "FRBC.TimerStatus": FRBCTimerStatus, - "FRBC.UsageForecast": FRBCUsageForecast, - "Handshake": Handshake, - "HandshakeResponse": HandshakeResponse, - "InstructionStatusUpdate": InstructionStatusUpdate, - "PowerForecast": PowerForecast, - "PowerMeasurement": PowerMeasurement, - "ReceptionStatus": ReceptionStatus, - "ResourceManagerDetails": ResourceManagerDetails, - "RevokeObject": RevokeObject, - "SelectControlType": SelectControlType, - "SessionRequest": SessionRequest, -} - - -class S2Parser: - @staticmethod - def _parse_json_if_required(unparsed_message: Union[dict, str, bytes]) -> dict: - if isinstance(unparsed_message, (str, bytes)): - return json.loads(unparsed_message) - return unparsed_message - - @staticmethod - def parse_as_any_message(unparsed_message: Union[dict, str, bytes]) -> S2Message: - """Parse the message as any S2 python message regardless of message type. - - :param unparsed_message: The message as a JSON-formatted string or as a json-parsed dictionary. - :raises: S2ValidationError, json.JSONDecodeError - :return: The parsed S2 message if no errors were found. - """ - message_json = S2Parser._parse_json_if_required(unparsed_message) - message_type = S2Parser.parse_message_type(message_json) - - if message_type not in TYPE_TO_MESSAGE_CLASS: - raise S2ValidationError( - None, - message_json, - f"Unable to parse {message_type} as an S2 message. Type unknown.", - None, - ) - - return TYPE_TO_MESSAGE_CLASS[message_type].model_validate(message_json) - - @staticmethod - def parse_as_message(unparsed_message: Union[dict, str, bytes], as_message: Type[M]) -> M: - """Parse the message to a specific S2 python message. - - :param unparsed_message: The message as a JSON-formatted string or as a JSON-parsed dictionary. - :param as_message: The type of message that is expected within the `message` - :raises: S2ValidationError, json.JSONDecodeError - :return: The parsed S2 message if no errors were found. - """ - message_json = S2Parser._parse_json_if_required(unparsed_message) - return as_message.from_dict(message_json) - - @staticmethod - def parse_message_type(unparsed_message: Union[dict, str, bytes]) -> Optional[S2MessageType]: - """Parse only the message type from the unparsed message. - - This is useful to call before `parse_as_message` to retrieve the message type and allows for strictly-typed - parsing. - - :param unparsed_message: The message as a JSON-formatted string or as a JSON-parsed dictionary. - :raises: json.JSONDecodeError - :return: The parsed S2 message type if no errors were found. - """ - message_json = S2Parser._parse_json_if_required(unparsed_message) - - return message_json.get("message_type") diff --git a/build/lib/s2python/s2_validation_error.py b/build/lib/s2python/s2_validation_error.py deleted file mode 100644 index 8ab7664..0000000 --- a/build/lib/s2python/s2_validation_error.py +++ /dev/null @@ -1,13 +0,0 @@ -from dataclasses import dataclass -from typing import Union, Type, Optional - -from pydantic import ValidationError -from pydantic.v1.error_wrappers import ValidationError as ValidationErrorV1 - - -@dataclass -class S2ValidationError(Exception): - class_: Optional[Type] - obj: object - msg: str - pydantic_validation_error: Union[ValidationErrorV1, ValidationError, TypeError, None] diff --git a/build/lib/s2python/utils.py b/build/lib/s2python/utils.py deleted file mode 100644 index b4f78ed..0000000 --- a/build/lib/s2python/utils.py +++ /dev/null @@ -1,8 +0,0 @@ -from typing import Generator, Tuple, List, TypeVar - -P = TypeVar("P") - - -def pairwise(arr: List[P]) -> Generator[Tuple[P, P], None, None]: - for i in range(max(len(arr) - 1, 0)): - yield arr[i], arr[i + 1] diff --git a/build/lib/s2python/validate_values_mixin.py b/build/lib/s2python/validate_values_mixin.py deleted file mode 100644 index 7d0d9d6..0000000 --- a/build/lib/s2python/validate_values_mixin.py +++ /dev/null @@ -1,70 +0,0 @@ -from typing import TypeVar, Generic, Type, Callable, Any, Union, AbstractSet, Mapping, List, Dict - -from pydantic import BaseModel, ValidationError # pylint: disable=no-name-in-module -from pydantic.v1.error_wrappers import display_errors # pylint: disable=no-name-in-module - -from s2python.s2_validation_error import S2ValidationError - -B_co = TypeVar("B_co", bound=BaseModel, covariant=True) - -IntStr = Union[int, str] -AbstractSetIntStr = AbstractSet[IntStr] -MappingIntStrAny = Mapping[IntStr, Any] - - -C = TypeVar("C", bound="BaseModel") - - -class S2Message(BaseModel, Generic[C]): - def to_json(self: C) -> str: - try: - return self.model_dump_json(by_alias=True, exclude_none=True) - except (ValidationError, TypeError) as e: - raise S2ValidationError( - type(self), self, "Pydantic raised a format validation error.", e - ) from e - - def to_dict(self: C) -> Dict: - return self.model_dump() - - @classmethod - def from_json(cls: Type[C], json_str: str) -> C: - gen_model: C = cls.model_validate_json(json_str) - return gen_model - - @classmethod - def from_dict(cls: Type[C], json_dict: dict) -> C: - gen_model: C = cls.model_validate(json_dict) - return gen_model - - -def convert_to_s2exception(f: Callable) -> Callable: - def inner(*args: List[Any], **kwargs: Dict[str, Any]) -> Any: - try: - return f(*args, **kwargs) - except ValidationError as e: - if isinstance(args[0], BaseModel): - class_type = type(args[0]) - args = args[1:] - else: - class_type = None - - raise S2ValidationError(class_type, args, display_errors(e.errors()), e) from e # type: ignore[arg-type] - except TypeError as e: - raise S2ValidationError(None, args, str(e), e) from e - - inner.__doc__ = f.__doc__ - inner.__annotations__ = f.__annotations__ - - return inner - - -def catch_and_convert_exceptions(input_class: Type[S2Message[B_co]]) -> Type[S2Message[B_co]]: - input_class.__init__ = convert_to_s2exception(input_class.__init__) # type: ignore[method-assign] - input_class.__setattr__ = convert_to_s2exception(input_class.__setattr__) # type: ignore[method-assign] - input_class.model_validate_json = convert_to_s2exception( # type: ignore[method-assign] - input_class.model_validate_json - ) - input_class.model_validate = convert_to_s2exception(input_class.model_validate) # type: ignore[method-assign] - - return input_class diff --git a/build/lib/s2python/version.py b/build/lib/s2python/version.py deleted file mode 100644 index 3789fe8..0000000 --- a/build/lib/s2python/version.py +++ /dev/null @@ -1,3 +0,0 @@ -VERSION = "0.2.0" - -S2_VERSION = "0.0.2-beta" From fe50c0ee069a4aced3dffaa734262d487d810dfc Mon Sep 17 00:00:00 2001 From: Vlad Iftime Date: Thu, 9 Jan 2025 15:13:33 +0100 Subject: [PATCH 05/14] Add dynamic unit test generation for frbc and ombc classes --- .../gen_unit_test_template.py | 131 ++++++++++-------- src/s2python/__init__.py | 1 + src/s2python/ombc/__init__.py | 3 + 3 files changed, 78 insertions(+), 57 deletions(-) diff --git a/development_utilities/gen_unit_test_template.py b/development_utilities/gen_unit_test_template.py index 93e2b03..fa67b45 100644 --- a/development_utilities/gen_unit_test_template.py +++ b/development_utilities/gen_unit_test_template.py @@ -1,5 +1,6 @@ import datetime import json +import os from enum import Enum import inspect import pprint @@ -18,7 +19,8 @@ import pydantic -from s2python import frbc +import s2python +from s2python import frbc, ombc from s2python.common import Duration, PowerRange, NumberRange from s2python.generated.gen_s2 import CommodityQuantity @@ -79,6 +81,7 @@ def message_type_from_class_name(class_name: str) -> str: def generate_json_test_data_for_field(field_type: Type): + if field_type is Duration: value = random.randint(0, 39999) elif field_type is NumberRange: @@ -125,6 +128,8 @@ def generate_json_test_data_for_field(field_type: Type): ) elif field_type is uuid.UUID: value = uuid.uuid4() + elif field_type is Duration: + value = random.randint(0, 39999) else: raise RuntimeError(f"Please implement test data for field type {field_type}") return value @@ -241,60 +246,72 @@ def dump_test_data_as_json_for(test_data: dict, class_: Type) -> dict: return result -for class_name, class_ in inspect.getmembers(frbc): - if inspect.isclass(class_) and issubclass(class_, pydantic.BaseModel): - test_data = generate_json_test_data_for_class(class_) - - assert_lines = [] - for field_name, field_type in get_type_hints(class_).items(): - assert_test_data = dump_test_data_as_constructor_field_for( - test_data[field_name], field_type - ) - - assert_lines.append( - f"self.assertEqual({snake_case(class_name)}.{field_name}, {assert_test_data})" +for class_name_bc, class_bc in [("frbc", frbc), ("ombc", ombc)]: + # Dynamically get the module object + for class_name, class_ in inspect.getmembers(class_bc): + # print(f"{class_name}: {class_}") + # Print the folder thats being inspected + print(f"Checking :tests/unit/{class_name_bc}/{snake_case(class_name)}_test.py") + if ( + inspect.isclass(class_) + and issubclass(class_, pydantic.BaseModel) + and not os.path.exists( + f"tests/unit/{class_name_bc}/{snake_case(class_name)}_test.py" ) - - asserts = "\n ".join(assert_lines) - template = f""" -from datetime import timedelta, datetime, timezone as offset -import json -from unittest import TestCase -import uuid - -from s2python.common import * -from s2python.frbc import * - - -class {class_name}Test(TestCase): - def test__from_json__happy_path_full(self): - # Arrange - json_str = \"\"\" -{json.dumps(dump_test_data_as_json_for(test_data, class_), indent=4)} - \"\"\" - - # Act - {snake_case(class_name)} = {class_name}.from_json(json_str) - - # Assert - {asserts} - - def test__to_json__happy_path_full(self): - # Arrange - {snake_case(class_name)} = {dump_test_data_as_constructor_for(test_data, class_)} - - # Act - json_str = {snake_case(class_name)}.to_json() - - # Assert - expected_json = {pprint.pformat(dump_test_data_as_json_for(test_data, class_), indent=4)} - self.assertEqual(json.loads(json_str), expected_json) -""" - print(template) - print() - print() - - with open( - f"tests/unit/frbc/{snake_case(class_name)}_test.py", "w+" - ) as unit_test_file: - unit_test_file.write(template) + ): + print(f"Generating test for {class_name}") + test_data = generate_json_test_data_for_class(class_) + + assert_lines = [] + for field_name, field_type in get_type_hints(class_).items(): + assert_test_data = dump_test_data_as_constructor_field_for( + test_data[field_name], field_type + ) + + assert_lines.append( + f"self.assertEqual({snake_case(class_name)}.{field_name}, {assert_test_data})" + ) + + asserts = "\n ".join(assert_lines) + template = f""" + from datetime import timedelta, datetime, timezone as offset + import json + from unittest import TestCase + import uuid + + from s2python.common import * + from s2python.frbc import * + + + class {class_name}Test(TestCase): + def test__from_json__happy_path_full(self): + # Arrange + json_str = \"\"\" + {json.dumps(dump_test_data_as_json_for(test_data, class_), indent=4)} + \"\"\" + + # Act + {snake_case(class_name)} = {class_name}.from_json(json_str) + + # Assert + {asserts} + + def test__to_json__happy_path_full(self): + # Arrange + {snake_case(class_name)} = {dump_test_data_as_constructor_for(test_data, class_)} + + # Act + json_str = {snake_case(class_name)}.to_json() + + # Assert + expected_json = {pprint.pformat(dump_test_data_as_json_for(test_data, class_), indent=4)} + self.assertEqual(json.loads(json_str), expected_json) + """ + print(template) + print() + print() + + with open( + f"tests/unit/frbc/{snake_case(class_name)}_test.py", "w+" + ) as unit_test_file: + unit_test_file.write(template) diff --git a/src/s2python/__init__.py b/src/s2python/__init__.py index 0ab0a42..6e520e1 100644 --- a/src/s2python/__init__.py +++ b/src/s2python/__init__.py @@ -8,3 +8,4 @@ __version__ = "unknown" finally: del version, PackageNotFoundError + \ No newline at end of file diff --git a/src/s2python/ombc/__init__.py b/src/s2python/ombc/__init__.py index 32aa3c1..6da257e 100644 --- a/src/s2python/ombc/__init__.py +++ b/src/s2python/ombc/__init__.py @@ -1,3 +1,6 @@ from s2python.ombc.ombc_instruction import OMBCInstruction +from s2python.ombc.ombc_operation_mode import OMBCOperationMode from s2python.ombc.ombc_status import OMBCStatus from s2python.ombc.ombc_system_description import OMBCSystemDescription +from s2python.ombc.ombc_timer_status import OMBCTimerStatus + From 98772fb4507c18e4ee5695005fdc3074cb3936b5 Mon Sep 17 00:00:00 2001 From: Vlad Iftime Date: Thu, 9 Jan 2025 15:17:17 +0100 Subject: [PATCH 06/14] Trailing line --- src/s2python/ombc/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/s2python/ombc/__init__.py b/src/s2python/ombc/__init__.py index 6da257e..623f04d 100644 --- a/src/s2python/ombc/__init__.py +++ b/src/s2python/ombc/__init__.py @@ -3,4 +3,3 @@ from s2python.ombc.ombc_status import OMBCStatus from s2python.ombc.ombc_system_description import OMBCSystemDescription from s2python.ombc.ombc_timer_status import OMBCTimerStatus - From cf5e84a779b78d536a43cb9e9441fe781fd1e313 Mon Sep 17 00:00:00 2001 From: Vlad Iftime Date: Mon, 13 Jan 2025 10:51:27 +0100 Subject: [PATCH 07/14] Fixed trailing line --- .github/workflows/ci.yml | 396 +++++++++++++++++++-------------------- src/s2python/__init__.py | 1 - 2 files changed, 198 insertions(+), 199 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bf4e441..7322b36 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,198 +1,198 @@ -name: tests-and-publish -# this pipeline started as an adaptation of the pipeline of the -# FlexMeasures client (https://github.com/FlexMeasures/flexmeasures-client/) - -on: - push: - # Avoid using all the resources/limits available by checking only - # relevant branches and tags. Other branches can be checked via PRs. - branches: [main] - tags: - - 'v[0-9]+\.[0-9]+\.[0-9]+\.dev[0-9]+' # Match tags that resemble a version - - 'v[0-9]+\.[0-9]+\.[0-9]+' # Match tags that resemble a version - pull_request: # Run in every PR - workflow_dispatch: # Allow manually triggering the workflow - schedule: - # Run roughly every 15 days at 00:00 UTC - # (useful to check if updates on dependencies break the package) - - cron: '0 0 1,16 * *' - -concurrency: - group: >- - ${{ github.workflow }}-${{ github.ref_type }}- - ${{ github.event.pull_request.number || github.sha }} - cancel-in-progress: true - -jobs: - prepare: - runs-on: ubuntu-latest - outputs: - wheel-distribution: ${{ steps.wheel-distribution.outputs.path }} - steps: - - uses: actions/checkout@v3 - with: {fetch-depth: 0} # deep clone for setuptools-scm - - uses: actions/setup-python@v4 - id: setup-python - with: {python-version: "3.11"} - # - name: Run static analysis and format checkers - # run: pipx run pre-commit run --all-files --show-diff-on-failure - - name: Build package distribution files - run: >- - pipx run --python '${{ steps.setup-python.outputs.python-path }}' - tox -e clean,build - - name: Record the path of wheel distribution - id: wheel-distribution - run: echo "path=$(ls dist/*.whl)" >> $GITHUB_OUTPUT - - name: Store the distribution files for use in other stages - # `tests` and `publish` will use the same pre-built distributions, - # so we make sure to release the exact same package that was tested - uses: actions/upload-artifact@v3 - with: - name: python-distribution-files - path: dist/ - retention-days: 1 - - test: - needs: prepare - strategy: - matrix: - python: - - "3.8" - - "3.9" - - "3.10" - - "3.11" - - "3.12" # newest Python that is stable - platform: - - ubuntu-latest - # - macos-latest - # - windows-latest - runs-on: ${{ matrix.platform }} - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-python@v4 - id: setup-python - with: - python-version: ${{ matrix.python }} - - name: Retrieve pre-built distribution files - uses: actions/download-artifact@v3 - with: {name: python-distribution-files, path: dist/} - - name: Run tests - run: >- - pipx run --python '${{ steps.setup-python.outputs.python-path }}' - tox --installpkg '${{ needs.prepare.outputs.wheel-distribution }}' - -- -rFEx --durations 10 --color yes # pytest args - # - name: Generate coverage report - # run: pipx run coverage lcov -o coverage.lcov - # - name: Upload partial coverage report - # uses: coverallsapp/github-action@master - # with: - # path-to-lcov: coverage.lcov - # github-token: ${{ secrets.GITHUB_TOKEN }} - # flag-name: ${{ matrix.platform }} - py${{ matrix.python }} - # parallel: true - - lint: - needs: prepare - strategy: - matrix: - python: - - "3.8" - - "3.9" - - "3.10" - - "3.11" - - "3.12" # newest Python that is stable - platform: - - ubuntu-latest - # - macos-latest - # - windows-latest - runs-on: ${{ matrix.platform }} - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-python@v4 - id: setup-python - with: - python-version: ${{ matrix.python }} - - name: Retrieve pre-built distribution files - uses: actions/download-artifact@v3 - with: {name: python-distribution-files, path: dist/} - - name: Run tests - run: >- - pipx run --python '${{ steps.setup-python.outputs.python-path }}' - tox -e lint --installpkg '${{ needs.prepare.outputs.wheel-distribution }}' - - typecheck: - needs: prepare - strategy: - matrix: - python: - - "3.8" - - "3.9" - - "3.10" - - "3.11" - - "3.12" # newest Python that is stable - platform: - - ubuntu-latest - # - macos-latest - # - windows-latest - runs-on: ${{ matrix.platform }} - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-python@v4 - id: setup-python - with: - python-version: ${{ matrix.python }} - - name: Retrieve pre-built distribution files - uses: actions/download-artifact@v3 - with: {name: python-distribution-files, path: dist/} - - name: Run tests - run: >- - pipx run --python '${{ steps.setup-python.outputs.python-path }}' - tox -e typecheck --installpkg '${{ needs.prepare.outputs.wheel-distribution }}' - - finalize: - needs: [test, lint, typecheck] - runs-on: ubuntu-latest - steps: - - run: echo "Finished checks" - - publish: - needs: finalize - if: ${{ github.event_name == 'push' && contains(github.ref, 'refs/tags/v') }} - runs-on: ubuntu-latest - environment: - name: release - url: https://pypi.org/project/s2-python/ - permissions: - id-token: write - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-python@v4 - with: {python-version: "3.11"} - - name: Retrieve pre-built distribution files - uses: actions/download-artifact@v3 - with: {name: python-distribution-files, path: dist/} - - name: Publish Package - uses: pypa/gh-action-pypi-publish@release/v1 - # run: pipx run tox -e publish - - test-publish: - needs: finalize - if: ${{ github.event_name == 'push' && contains(github.ref, 'refs/tags/test') }} - runs-on: ubuntu-latest - environment: - name: testpypi - url: https://test.pypi.org/project/s2-python/ - permissions: - id-token: write - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-python@v4 - with: {python-version: "3.11"} - - name: Retrieve pre-built distribution files - uses: actions/download-artifact@v3 - with: {name: python-distribution-files, path: dist/} - - name: Publish Package - uses: pypa/gh-action-pypi-publish@release/v1 - with: - repository-url: https://test.pypi.org/legacy/ - # run: pipx run tox -e publish +name: tests-and-publish +# this pipeline started as an adaptation of the pipeline of the +# FlexMeasures client (https://github.com/FlexMeasures/flexmeasures-client/) + +on: + push: + # Avoid using all the resources/limits available by checking only + # relevant branches and tags. Other branches can be checked via PRs. + branches: [main] + tags: + - 'v[0-9]+\.[0-9]+\.[0-9]+\.dev[0-9]+' # Match tags that resemble a version + - 'v[0-9]+\.[0-9]+\.[0-9]+' # Match tags that resemble a version + pull_request: # Run in every PR + workflow_dispatch: # Allow manually triggering the workflow + schedule: + # Run roughly every 15 days at 00:00 UTC + # (useful to check if updates on dependencies break the package) + - cron: '0 0 1,16 * *' + +concurrency: + group: >- + ${{ github.workflow }}-${{ github.ref_type }}- + ${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: true + +jobs: + prepare: + runs-on: ubuntu-latest + outputs: + wheel-distribution: ${{ steps.wheel-distribution.outputs.path }} + steps: + - uses: actions/checkout@v3 + with: {fetch-depth: 0} # deep clone for setuptools-scm + - uses: actions/setup-python@v4 + id: setup-python + with: {python-version: "3.11"} + # - name: Run static analysis and format checkers + # run: pipx run pre-commit run --all-files --show-diff-on-failure + - name: Build package distribution files + run: >- + pipx run --python '${{ steps.setup-python.outputs.python-path }}' + tox -e clean,build + - name: Record the path of wheel distribution + id: wheel-distribution + run: echo "path=$(ls dist/*.whl)" >> $GITHUB_OUTPUT + - name: Store the distribution files for use in other stages + # `tests` and `publish` will use the same pre-built distributions, + # so we make sure to release the exact same package that was tested + uses: actions/upload-artifact@v3 + with: + name: python-distribution-files + path: dist/ + retention-days: 1 + + test: + needs: prepare + strategy: + matrix: + python: + - "3.8" + - "3.9" + - "3.10" + - "3.11" + - "3.12" # newest Python that is stable + platform: + - ubuntu-latest + # - macos-latest + # - windows-latest + runs-on: ${{ matrix.platform }} + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + id: setup-python + with: + python-version: ${{ matrix.python }} + - name: Retrieve pre-built distribution files + uses: actions/download-artifact@v3 + with: {name: python-distribution-files, path: dist/} + - name: Run tests + run: >- + pipx run --python '${{ steps.setup-python.outputs.python-path }}' + tox --installpkg '${{ needs.prepare.outputs.wheel-distribution }}' + -- -rFEx --durations 10 --color yes # pytest args + # - name: Generate coverage report + # run: pipx run coverage lcov -o coverage.lcov + # - name: Upload partial coverage report + # uses: coverallsapp/github-action@master + # with: + # path-to-lcov: coverage.lcov + # github-token: ${{ secrets.GITHUB_TOKEN }} + # flag-name: ${{ matrix.platform }} - py${{ matrix.python }} + # parallel: true + + lint: + needs: prepare + strategy: + matrix: + python: + - "3.8" + - "3.9" + - "3.10" + - "3.11" + - "3.12" # newest Python that is stable + platform: + - ubuntu-latest + # - macos-latest + # - windows-latest + runs-on: ${{ matrix.platform }} + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + id: setup-python + with: + python-version: ${{ matrix.python }} + - name: Retrieve pre-built distribution files + uses: actions/download-artifact@v3 + with: {name: python-distribution-files, path: dist/} + - name: Run tests + run: >- + pipx run --python '${{ steps.setup-python.outputs.python-path }}' + tox -e lint --installpkg '${{ needs.prepare.outputs.wheel-distribution }}' + + typecheck: + needs: prepare + strategy: + matrix: + python: + - "3.8" + - "3.9" + - "3.10" + - "3.11" + - "3.12" # newest Python that is stable + platform: + - ubuntu-latest + # - macos-latest + # - windows-latest + runs-on: ${{ matrix.platform }} + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + id: setup-python + with: + python-version: ${{ matrix.python }} + - name: Retrieve pre-built distribution files + uses: actions/download-artifact@v3 + with: {name: python-distribution-files, path: dist/} + - name: Run tests + run: >- + pipx run --python '${{ steps.setup-python.outputs.python-path }}' + tox -e typecheck --installpkg '${{ needs.prepare.outputs.wheel-distribution }}' + + finalize: + needs: [test, lint, typecheck] + runs-on: ubuntu-latest + steps: + - run: echo "Finished checks" + + publish: + needs: finalize + if: ${{ github.event_name == 'push' && contains(github.ref, 'refs/tags/v') }} + runs-on: ubuntu-latest + environment: + name: release + url: https://pypi.org/project/s2-python/ + permissions: + id-token: write + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: {python-version: "3.11"} + - name: Retrieve pre-built distribution files + uses: actions/download-artifact@v3 + with: {name: python-distribution-files, path: dist/} + - name: Publish Package + uses: pypa/gh-action-pypi-publish@release/v1 + # run: pipx run tox -e publish + + test-publish: + needs: finalize + if: ${{ github.event_name == 'push' && contains(github.ref, 'refs/tags/test') }} + runs-on: ubuntu-latest + environment: + name: testpypi + url: https://test.pypi.org/project/s2-python/ + permissions: + id-token: write + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: {python-version: "3.11"} + - name: Retrieve pre-built distribution files + uses: actions/download-artifact@v3 + with: {name: python-distribution-files, path: dist/} + - name: Publish Package + uses: pypa/gh-action-pypi-publish@release/v1 + with: + repository-url: https://test.pypi.org/legacy/ + # run: pipx run tox -e publish diff --git a/src/s2python/__init__.py b/src/s2python/__init__.py index 6e520e1..0ab0a42 100644 --- a/src/s2python/__init__.py +++ b/src/s2python/__init__.py @@ -8,4 +8,3 @@ __version__ = "unknown" finally: del version, PackageNotFoundError - \ No newline at end of file From 08f0d5728a1bb134a70c276e68053e680f4c06cf Mon Sep 17 00:00:00 2001 From: Vlad Iftime Date: Fri, 24 Jan 2025 12:43:41 +0100 Subject: [PATCH 08/14] Fixed the new type of S2Message as union Signed-off-by: Vlad Iftime --- src/s2python/ombc/ombc_instruction.py | 4 ++-- src/s2python/ombc/ombc_operation_mode.py | 4 ++-- src/s2python/ombc/ombc_status.py | 4 ++-- src/s2python/ombc/ombc_system_description.py | 4 ++-- src/s2python/ombc/ombc_timer_status.py | 4 ++-- 5 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/s2python/ombc/ombc_instruction.py b/src/s2python/ombc/ombc_instruction.py index 8dd76b2..18800e2 100644 --- a/src/s2python/ombc/ombc_instruction.py +++ b/src/s2python/ombc/ombc_instruction.py @@ -3,12 +3,12 @@ from s2python.generated.gen_s2 import OMBCInstruction as GenOMBCInstruction from s2python.validate_values_mixin import ( catch_and_convert_exceptions, - S2Message, + S2MessageComponent, ) @catch_and_convert_exceptions -class OMBCInstruction(GenOMBCInstruction, S2Message["OMBCInstruction"]): +class OMBCInstruction(GenOMBCInstruction, S2MessageComponent["OMBCInstruction"]): model_config = GenOMBCInstruction.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/ombc/ombc_operation_mode.py b/src/s2python/ombc/ombc_operation_mode.py index 9f11438..1a9586f 100644 --- a/src/s2python/ombc/ombc_operation_mode.py +++ b/src/s2python/ombc/ombc_operation_mode.py @@ -7,12 +7,12 @@ from s2python.validate_values_mixin import ( catch_and_convert_exceptions, - S2Message, + S2MessageComponent, ) @catch_and_convert_exceptions -class OMBCOperationMode(GenOMBCOperationMode, S2Message["OMBCOperationMode"]): +class OMBCOperationMode(GenOMBCOperationMode, S2MessageComponent["OMBCOperationMode"]): model_config = GenOMBCOperationMode.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/ombc/ombc_status.py b/src/s2python/ombc/ombc_status.py index 89b282a..3c0f6ec 100644 --- a/src/s2python/ombc/ombc_status.py +++ b/src/s2python/ombc/ombc_status.py @@ -4,12 +4,12 @@ from s2python.validate_values_mixin import ( catch_and_convert_exceptions, - S2Message, + S2MessageComponent, ) @catch_and_convert_exceptions -class OMBCStatus(GenOMBCStatus, S2Message["OMBCStatus"]): +class OMBCStatus(GenOMBCStatus, S2MessageComponent["OMBCStatus"]): model_config = GenOMBCStatus.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/ombc/ombc_system_description.py b/src/s2python/ombc/ombc_system_description.py index f2d31bd..694cf4b 100644 --- a/src/s2python/ombc/ombc_system_description.py +++ b/src/s2python/ombc/ombc_system_description.py @@ -8,13 +8,13 @@ from s2python.validate_values_mixin import ( catch_and_convert_exceptions, - S2Message, + S2MessageComponent, ) @catch_and_convert_exceptions class OMBCSystemDescription( - GenOMBCSystemDescription, S2Message["OMBCSystemDescription"] + GenOMBCSystemDescription, S2MessageComponent["OMBCSystemDescription"] ): model_config = GenOMBCSystemDescription.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/ombc/ombc_timer_status.py b/src/s2python/ombc/ombc_timer_status.py index 3fa35ed..2c530e7 100644 --- a/src/s2python/ombc/ombc_timer_status.py +++ b/src/s2python/ombc/ombc_timer_status.py @@ -4,12 +4,12 @@ from s2python.validate_values_mixin import ( catch_and_convert_exceptions, - S2Message, + S2MessageComponent, ) @catch_and_convert_exceptions -class OMBCTimerStatus(GenOMBCTimerStatus, S2Message["OMBCTimerStatus"]): +class OMBCTimerStatus(GenOMBCTimerStatus, S2MessageComponent["OMBCTimerStatus"]): model_config = GenOMBCTimerStatus.model_config model_config["validate_assignment"] = True From 72978481b57598067f446643dc0968a2058e4d85 Mon Sep 17 00:00:00 2001 From: Vlad Iftime Date: Fri, 24 Jan 2025 12:47:09 +0100 Subject: [PATCH 09/14] Fixed extra file changes Signed-off-by: Vlad Iftime --- .github/workflows/ci.yml | 396 +++++++++--------- .../gen_unit_test_template.py | 29 +- 2 files changed, 211 insertions(+), 214 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7322b36..bf4e441 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,198 +1,198 @@ -name: tests-and-publish -# this pipeline started as an adaptation of the pipeline of the -# FlexMeasures client (https://github.com/FlexMeasures/flexmeasures-client/) - -on: - push: - # Avoid using all the resources/limits available by checking only - # relevant branches and tags. Other branches can be checked via PRs. - branches: [main] - tags: - - 'v[0-9]+\.[0-9]+\.[0-9]+\.dev[0-9]+' # Match tags that resemble a version - - 'v[0-9]+\.[0-9]+\.[0-9]+' # Match tags that resemble a version - pull_request: # Run in every PR - workflow_dispatch: # Allow manually triggering the workflow - schedule: - # Run roughly every 15 days at 00:00 UTC - # (useful to check if updates on dependencies break the package) - - cron: '0 0 1,16 * *' - -concurrency: - group: >- - ${{ github.workflow }}-${{ github.ref_type }}- - ${{ github.event.pull_request.number || github.sha }} - cancel-in-progress: true - -jobs: - prepare: - runs-on: ubuntu-latest - outputs: - wheel-distribution: ${{ steps.wheel-distribution.outputs.path }} - steps: - - uses: actions/checkout@v3 - with: {fetch-depth: 0} # deep clone for setuptools-scm - - uses: actions/setup-python@v4 - id: setup-python - with: {python-version: "3.11"} - # - name: Run static analysis and format checkers - # run: pipx run pre-commit run --all-files --show-diff-on-failure - - name: Build package distribution files - run: >- - pipx run --python '${{ steps.setup-python.outputs.python-path }}' - tox -e clean,build - - name: Record the path of wheel distribution - id: wheel-distribution - run: echo "path=$(ls dist/*.whl)" >> $GITHUB_OUTPUT - - name: Store the distribution files for use in other stages - # `tests` and `publish` will use the same pre-built distributions, - # so we make sure to release the exact same package that was tested - uses: actions/upload-artifact@v3 - with: - name: python-distribution-files - path: dist/ - retention-days: 1 - - test: - needs: prepare - strategy: - matrix: - python: - - "3.8" - - "3.9" - - "3.10" - - "3.11" - - "3.12" # newest Python that is stable - platform: - - ubuntu-latest - # - macos-latest - # - windows-latest - runs-on: ${{ matrix.platform }} - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-python@v4 - id: setup-python - with: - python-version: ${{ matrix.python }} - - name: Retrieve pre-built distribution files - uses: actions/download-artifact@v3 - with: {name: python-distribution-files, path: dist/} - - name: Run tests - run: >- - pipx run --python '${{ steps.setup-python.outputs.python-path }}' - tox --installpkg '${{ needs.prepare.outputs.wheel-distribution }}' - -- -rFEx --durations 10 --color yes # pytest args - # - name: Generate coverage report - # run: pipx run coverage lcov -o coverage.lcov - # - name: Upload partial coverage report - # uses: coverallsapp/github-action@master - # with: - # path-to-lcov: coverage.lcov - # github-token: ${{ secrets.GITHUB_TOKEN }} - # flag-name: ${{ matrix.platform }} - py${{ matrix.python }} - # parallel: true - - lint: - needs: prepare - strategy: - matrix: - python: - - "3.8" - - "3.9" - - "3.10" - - "3.11" - - "3.12" # newest Python that is stable - platform: - - ubuntu-latest - # - macos-latest - # - windows-latest - runs-on: ${{ matrix.platform }} - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-python@v4 - id: setup-python - with: - python-version: ${{ matrix.python }} - - name: Retrieve pre-built distribution files - uses: actions/download-artifact@v3 - with: {name: python-distribution-files, path: dist/} - - name: Run tests - run: >- - pipx run --python '${{ steps.setup-python.outputs.python-path }}' - tox -e lint --installpkg '${{ needs.prepare.outputs.wheel-distribution }}' - - typecheck: - needs: prepare - strategy: - matrix: - python: - - "3.8" - - "3.9" - - "3.10" - - "3.11" - - "3.12" # newest Python that is stable - platform: - - ubuntu-latest - # - macos-latest - # - windows-latest - runs-on: ${{ matrix.platform }} - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-python@v4 - id: setup-python - with: - python-version: ${{ matrix.python }} - - name: Retrieve pre-built distribution files - uses: actions/download-artifact@v3 - with: {name: python-distribution-files, path: dist/} - - name: Run tests - run: >- - pipx run --python '${{ steps.setup-python.outputs.python-path }}' - tox -e typecheck --installpkg '${{ needs.prepare.outputs.wheel-distribution }}' - - finalize: - needs: [test, lint, typecheck] - runs-on: ubuntu-latest - steps: - - run: echo "Finished checks" - - publish: - needs: finalize - if: ${{ github.event_name == 'push' && contains(github.ref, 'refs/tags/v') }} - runs-on: ubuntu-latest - environment: - name: release - url: https://pypi.org/project/s2-python/ - permissions: - id-token: write - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-python@v4 - with: {python-version: "3.11"} - - name: Retrieve pre-built distribution files - uses: actions/download-artifact@v3 - with: {name: python-distribution-files, path: dist/} - - name: Publish Package - uses: pypa/gh-action-pypi-publish@release/v1 - # run: pipx run tox -e publish - - test-publish: - needs: finalize - if: ${{ github.event_name == 'push' && contains(github.ref, 'refs/tags/test') }} - runs-on: ubuntu-latest - environment: - name: testpypi - url: https://test.pypi.org/project/s2-python/ - permissions: - id-token: write - steps: - - uses: actions/checkout@v3 - - uses: actions/setup-python@v4 - with: {python-version: "3.11"} - - name: Retrieve pre-built distribution files - uses: actions/download-artifact@v3 - with: {name: python-distribution-files, path: dist/} - - name: Publish Package - uses: pypa/gh-action-pypi-publish@release/v1 - with: - repository-url: https://test.pypi.org/legacy/ - # run: pipx run tox -e publish +name: tests-and-publish +# this pipeline started as an adaptation of the pipeline of the +# FlexMeasures client (https://github.com/FlexMeasures/flexmeasures-client/) + +on: + push: + # Avoid using all the resources/limits available by checking only + # relevant branches and tags. Other branches can be checked via PRs. + branches: [main] + tags: + - 'v[0-9]+\.[0-9]+\.[0-9]+\.dev[0-9]+' # Match tags that resemble a version + - 'v[0-9]+\.[0-9]+\.[0-9]+' # Match tags that resemble a version + pull_request: # Run in every PR + workflow_dispatch: # Allow manually triggering the workflow + schedule: + # Run roughly every 15 days at 00:00 UTC + # (useful to check if updates on dependencies break the package) + - cron: '0 0 1,16 * *' + +concurrency: + group: >- + ${{ github.workflow }}-${{ github.ref_type }}- + ${{ github.event.pull_request.number || github.sha }} + cancel-in-progress: true + +jobs: + prepare: + runs-on: ubuntu-latest + outputs: + wheel-distribution: ${{ steps.wheel-distribution.outputs.path }} + steps: + - uses: actions/checkout@v3 + with: {fetch-depth: 0} # deep clone for setuptools-scm + - uses: actions/setup-python@v4 + id: setup-python + with: {python-version: "3.11"} + # - name: Run static analysis and format checkers + # run: pipx run pre-commit run --all-files --show-diff-on-failure + - name: Build package distribution files + run: >- + pipx run --python '${{ steps.setup-python.outputs.python-path }}' + tox -e clean,build + - name: Record the path of wheel distribution + id: wheel-distribution + run: echo "path=$(ls dist/*.whl)" >> $GITHUB_OUTPUT + - name: Store the distribution files for use in other stages + # `tests` and `publish` will use the same pre-built distributions, + # so we make sure to release the exact same package that was tested + uses: actions/upload-artifact@v3 + with: + name: python-distribution-files + path: dist/ + retention-days: 1 + + test: + needs: prepare + strategy: + matrix: + python: + - "3.8" + - "3.9" + - "3.10" + - "3.11" + - "3.12" # newest Python that is stable + platform: + - ubuntu-latest + # - macos-latest + # - windows-latest + runs-on: ${{ matrix.platform }} + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + id: setup-python + with: + python-version: ${{ matrix.python }} + - name: Retrieve pre-built distribution files + uses: actions/download-artifact@v3 + with: {name: python-distribution-files, path: dist/} + - name: Run tests + run: >- + pipx run --python '${{ steps.setup-python.outputs.python-path }}' + tox --installpkg '${{ needs.prepare.outputs.wheel-distribution }}' + -- -rFEx --durations 10 --color yes # pytest args + # - name: Generate coverage report + # run: pipx run coverage lcov -o coverage.lcov + # - name: Upload partial coverage report + # uses: coverallsapp/github-action@master + # with: + # path-to-lcov: coverage.lcov + # github-token: ${{ secrets.GITHUB_TOKEN }} + # flag-name: ${{ matrix.platform }} - py${{ matrix.python }} + # parallel: true + + lint: + needs: prepare + strategy: + matrix: + python: + - "3.8" + - "3.9" + - "3.10" + - "3.11" + - "3.12" # newest Python that is stable + platform: + - ubuntu-latest + # - macos-latest + # - windows-latest + runs-on: ${{ matrix.platform }} + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + id: setup-python + with: + python-version: ${{ matrix.python }} + - name: Retrieve pre-built distribution files + uses: actions/download-artifact@v3 + with: {name: python-distribution-files, path: dist/} + - name: Run tests + run: >- + pipx run --python '${{ steps.setup-python.outputs.python-path }}' + tox -e lint --installpkg '${{ needs.prepare.outputs.wheel-distribution }}' + + typecheck: + needs: prepare + strategy: + matrix: + python: + - "3.8" + - "3.9" + - "3.10" + - "3.11" + - "3.12" # newest Python that is stable + platform: + - ubuntu-latest + # - macos-latest + # - windows-latest + runs-on: ${{ matrix.platform }} + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + id: setup-python + with: + python-version: ${{ matrix.python }} + - name: Retrieve pre-built distribution files + uses: actions/download-artifact@v3 + with: {name: python-distribution-files, path: dist/} + - name: Run tests + run: >- + pipx run --python '${{ steps.setup-python.outputs.python-path }}' + tox -e typecheck --installpkg '${{ needs.prepare.outputs.wheel-distribution }}' + + finalize: + needs: [test, lint, typecheck] + runs-on: ubuntu-latest + steps: + - run: echo "Finished checks" + + publish: + needs: finalize + if: ${{ github.event_name == 'push' && contains(github.ref, 'refs/tags/v') }} + runs-on: ubuntu-latest + environment: + name: release + url: https://pypi.org/project/s2-python/ + permissions: + id-token: write + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: {python-version: "3.11"} + - name: Retrieve pre-built distribution files + uses: actions/download-artifact@v3 + with: {name: python-distribution-files, path: dist/} + - name: Publish Package + uses: pypa/gh-action-pypi-publish@release/v1 + # run: pipx run tox -e publish + + test-publish: + needs: finalize + if: ${{ github.event_name == 'push' && contains(github.ref, 'refs/tags/test') }} + runs-on: ubuntu-latest + environment: + name: testpypi + url: https://test.pypi.org/project/s2-python/ + permissions: + id-token: write + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: {python-version: "3.11"} + - name: Retrieve pre-built distribution files + uses: actions/download-artifact@v3 + with: {name: python-distribution-files, path: dist/} + - name: Publish Package + uses: pypa/gh-action-pypi-publish@release/v1 + with: + repository-url: https://test.pypi.org/legacy/ + # run: pipx run tox -e publish diff --git a/development_utilities/gen_unit_test_template.py b/development_utilities/gen_unit_test_template.py index ad19f6e..87bddc9 100644 --- a/development_utilities/gen_unit_test_template.py +++ b/development_utilities/gen_unit_test_template.py @@ -20,8 +20,7 @@ import pydantic from pydantic.types import AwareDatetime -import s2python -from s2python import frbc, ombc +from s2python import frbc from s2python.common import Duration, PowerRange, NumberRange from s2python.generated.gen_s2 import CommodityQuantity @@ -82,7 +81,6 @@ def message_type_from_class_name(class_name: str) -> str: def generate_json_test_data_for_field(field_type: Type): - if field_type is Duration: value = random.randint(0, 39999) elif field_type is NumberRange: @@ -128,8 +126,6 @@ def generate_json_test_data_for_field(field_type: Type): ) elif field_type is uuid.UUID: value = uuid.uuid4() - elif field_type is Duration: - value = random.randint(0, 39999) else: raise RuntimeError(f"Please implement test data for field type {field_type}") return value @@ -255,17 +251,18 @@ def dump_test_data_as_json_for(test_data: dict, class_: Type) -> dict: return result -for class_name_bc, class_bc in [("frbc", frbc), ("ombc", ombc)]: - # Dynamically get the module object - for class_name, class_ in inspect.getmembers(class_bc): - # print(f"{class_name}: {class_}") - # Print the folder thats being inspected - print(f"Checking :tests/unit/{class_name_bc}/{snake_case(class_name)}_test.py") - if ( - inspect.isclass(class_) - and issubclass(class_, pydantic.BaseModel) - and not os.path.exists( - f"tests/unit/{class_name_bc}/{snake_case(class_name)}_test.py" +for class_name, class_ in inspect.getmembers(frbc): + if inspect.isclass(class_) and issubclass(class_, pydantic.BaseModel): + test_data = generate_json_test_data_for_class(class_) + + assert_lines = [] + for field_name, field_type in get_type_hints(class_).items(): + assert_test_data = dump_test_data_as_constructor_field_for( + test_data[field_name], field_type + ) + + assert_lines.append( + f"self.assertEqual({snake_case(class_name)}.{field_name}, {assert_test_data})" ) asserts = "\n ".join(assert_lines) From fb4a9211168c865e2ad844ce261353cd45070241 Mon Sep 17 00:00:00 2001 From: Vlad Iftime Date: Mon, 3 Mar 2025 10:21:30 +0100 Subject: [PATCH 10/14] Added the OMBC to s2_controll_types Signed-off-by: Vlad Iftime --- .github/workflows/ci.yml | 24 ++++++++++++------------ examples/example_frbc_rm.py | 2 +- src/s2python/s2_control_type.py | 20 ++++++++++++++++++++ 3 files changed, 33 insertions(+), 13 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bf4e441..7ca3906 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,7 +29,7 @@ jobs: outputs: wheel-distribution: ${{ steps.wheel-distribution.outputs.path }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 with: {fetch-depth: 0} # deep clone for setuptools-scm - uses: actions/setup-python@v4 id: setup-python @@ -46,7 +46,7 @@ jobs: - name: Store the distribution files for use in other stages # `tests` and `publish` will use the same pre-built distributions, # so we make sure to release the exact same package that was tested - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: python-distribution-files path: dist/ @@ -68,13 +68,13 @@ jobs: # - windows-latest runs-on: ${{ matrix.platform }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-python@v4 id: setup-python with: python-version: ${{ matrix.python }} - name: Retrieve pre-built distribution files - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: {name: python-distribution-files, path: dist/} - name: Run tests run: >- @@ -107,13 +107,13 @@ jobs: # - windows-latest runs-on: ${{ matrix.platform }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-python@v4 id: setup-python with: python-version: ${{ matrix.python }} - name: Retrieve pre-built distribution files - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: {name: python-distribution-files, path: dist/} - name: Run tests run: >- @@ -136,13 +136,13 @@ jobs: # - windows-latest runs-on: ${{ matrix.platform }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-python@v4 id: setup-python with: python-version: ${{ matrix.python }} - name: Retrieve pre-built distribution files - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: {name: python-distribution-files, path: dist/} - name: Run tests run: >- @@ -165,11 +165,11 @@ jobs: permissions: id-token: write steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-python@v4 with: {python-version: "3.11"} - name: Retrieve pre-built distribution files - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: {name: python-distribution-files, path: dist/} - name: Publish Package uses: pypa/gh-action-pypi-publish@release/v1 @@ -185,11 +185,11 @@ jobs: permissions: id-token: write steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - uses: actions/setup-python@v4 with: {python-version: "3.11"} - name: Retrieve pre-built distribution files - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: {name: python-distribution-files, path: dist/} - name: Publish Package uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/examples/example_frbc_rm.py b/examples/example_frbc_rm.py index 53b80df..774d936 100644 --- a/examples/example_frbc_rm.py +++ b/examples/example_frbc_rm.py @@ -30,7 +30,7 @@ ) from s2python.s2_connection import S2Connection, AssetDetails from s2python.s2_control_type import FRBCControlType, NoControlControlType -from s2python.validate_values_mixin import S2Message +from s2python.message import S2Message logger = logging.getLogger("s2python") logger.addHandler(logging.StreamHandler(sys.stdout)) diff --git a/src/s2python/s2_control_type.py b/src/s2python/s2_control_type.py index 982c9be..d503a69 100644 --- a/src/s2python/s2_control_type.py +++ b/src/s2python/s2_control_type.py @@ -4,6 +4,7 @@ from s2python.common import ControlType as ProtocolControlType from s2python.frbc import FRBCInstruction from s2python.ppbc import PPBCScheduleInstruction +from s2python.ombc import OMBCInstruction from s2python.message import S2Message if typing.TYPE_CHECKING: @@ -65,6 +66,25 @@ def activate(self, conn: "S2Connection") -> None: def deactivate(self, conn: "S2Connection") -> None: """Overwrite with the actual deactivation logic of your Resource Manager for this particular control type.""" +class OMBCControlType(S2ControlType): + def get_protocol_control_type(self) -> ProtocolControlType: + return ProtocolControlType.OPERATION_MODE_BASED_CONTROL + + def register_handlers(self, handlers: "MessageHandlers") -> None: + handlers.register_handler(OMBCInstruction, self.handle_instruction) + + @abc.abstractmethod + def handle_instruction( + self, conn: "S2Connection", msg: S2Message, send_okay: typing.Callable[[], None] + ) -> None: ... + + @abc.abstractmethod + def activate(self, conn: "S2Connection") -> None: + """Overwrite with the actual dctivation logic of your Resource Manager for this particular control type.""" + + @abc.abstractmethod + def deactivate(self, conn: "S2Connection") -> None: + """Overwrite with the actual deactivation logic of your Resource Manager for this particular control type.""" class NoControlControlType(S2ControlType): def get_protocol_control_type(self) -> ProtocolControlType: From 410fde3e42da717178e727a83ccf75c84fad7aa5 Mon Sep 17 00:00:00 2001 From: Vlad Iftime Date: Mon, 3 Mar 2025 10:33:03 +0100 Subject: [PATCH 11/14] Failed test fix Signed-off-by: Vlad Iftime --- .../generate_s2_message_type_to_class.py | 12 +- development_utilities/get_all_messages.py | 8 +- .../common/instruction_status_update.py | 4 +- src/s2python/common/number_range.py | 5 +- src/s2python/common/power_forecast_element.py | 4 +- src/s2python/common/power_forecast_value.py | 4 +- src/s2python/common/power_range.py | 4 +- .../common/resource_manager_details.py | 4 +- .../frbc/frbc_actuator_description.py | 16 +- src/s2python/frbc/frbc_actuator_status.py | 8 +- .../frbc/frbc_fill_level_target_profile.py | 8 +- .../frbc_fill_level_target_profile_element.py | 8 +- src/s2python/frbc/frbc_leakage_behaviour.py | 4 +- .../frbc/frbc_leakage_behaviour_element.py | 9 +- src/s2python/frbc/frbc_operation_mode.py | 13 +- .../frbc/frbc_operation_mode_element.py | 4 +- src/s2python/frbc/frbc_storage_description.py | 4 +- src/s2python/frbc/frbc_system_description.py | 4 +- .../frbc/frbc_usage_forecast_element.py | 4 +- src/s2python/generated/gen_s2.py | 1012 ++++++++--------- src/s2python/message.py | 16 +- .../ppbc/ppbc_end_interruption_instruction.py | 3 +- .../ppbc_power_sequence_container_status.py | 3 +- .../ppbc_start_interruption_instruction.py | 3 +- src/s2python/s2_connection.py | 89 +- src/s2python/s2_control_type.py | 2 + src/s2python/s2_validation_error.py | 4 +- src/s2python/validate_values_mixin.py | 21 +- tests/unit/common/handshake_test.py | 4 +- .../common/instruction_status_update_test.py | 8 +- tests/unit/common/number_range_test.py | 8 +- .../common/power_forecast_element_test.py | 4 +- .../unit/common/power_forecast_value_test.py | 13 +- tests/unit/common/power_measurement_test.py | 16 +- tests/unit/common/transition_test.py | 32 +- tests/unit/frbc/frbc_actuator_status_test.py | 4 +- ..._fill_level_target_profile_element_test.py | 4 +- .../frbc_fill_level_target_profile_test.py | 4 +- .../frbc_leakage_behaviour_element_test.py | 8 +- .../unit/frbc/frbc_system_description_test.py | 16 +- tests/unit/reception_status_awaiter_test.py | 16 +- 41 files changed, 815 insertions(+), 602 deletions(-) diff --git a/development_utilities/generate_s2_message_type_to_class.py b/development_utilities/generate_s2_message_type_to_class.py index 2d15c59..9ddceaa 100644 --- a/development_utilities/generate_s2_message_type_to_class.py +++ b/development_utilities/generate_s2_message_type_to_class.py @@ -5,14 +5,20 @@ all_members.sort(key=lambda t: t[0]) -print(""" +print( + """ from s2python.common import * from s2python.frbc import * -TYPE_TO_MESSAGE_CLASS = {""") +TYPE_TO_MESSAGE_CLASS = {""" +) for name, member in all_members: - if inspect.isclass(member) and hasattr(member, '__fields__') and ('message_type' in member.__fields__): + if ( + inspect.isclass(member) + and hasattr(member, "__fields__") + and ("message_type" in member.__fields__) + ): print(f" '{member.__fields__['message_type'].default}': {name},") print("}") diff --git a/development_utilities/get_all_messages.py b/development_utilities/get_all_messages.py index 4135eaa..5b70631 100644 --- a/development_utilities/get_all_messages.py +++ b/development_utilities/get_all_messages.py @@ -8,5 +8,9 @@ all_members.sort(key=lambda t: t[0]) for name, member in all_members: - if inspect.isclass(member) and issubclass(member, BaseModel) and "message_type" in member.__fields__: - print(f"{name},") \ No newline at end of file + if ( + inspect.isclass(member) + and issubclass(member, BaseModel) + and "message_type" in member.__fields__ + ): + print(f"{name},") diff --git a/src/s2python/common/instruction_status_update.py b/src/s2python/common/instruction_status_update.py index 6420058..916eadf 100644 --- a/src/s2python/common/instruction_status_update.py +++ b/src/s2python/common/instruction_status_update.py @@ -10,7 +10,9 @@ @catch_and_convert_exceptions -class InstructionStatusUpdate(GenInstructionStatusUpdate, S2MessageComponent["InstructionStatusUpdate"]): +class InstructionStatusUpdate( + GenInstructionStatusUpdate, S2MessageComponent["InstructionStatusUpdate"] +): model_config = GenInstructionStatusUpdate.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/common/number_range.py b/src/s2python/common/number_range.py index 40525a2..8d30f7b 100644 --- a/src/s2python/common/number_range.py +++ b/src/s2python/common/number_range.py @@ -1,6 +1,9 @@ from typing import Any -from s2python.validate_values_mixin import S2MessageComponent, catch_and_convert_exceptions +from s2python.validate_values_mixin import ( + S2MessageComponent, + catch_and_convert_exceptions, +) from s2python.generated.gen_s2 import NumberRange as GenNumberRange diff --git a/src/s2python/common/power_forecast_element.py b/src/s2python/common/power_forecast_element.py index 5f1626d..fff52aa 100644 --- a/src/s2python/common/power_forecast_element.py +++ b/src/s2python/common/power_forecast_element.py @@ -10,7 +10,9 @@ @catch_and_convert_exceptions -class PowerForecastElement(GenPowerForecastElement, S2MessageComponent["PowerForecastElement"]): +class PowerForecastElement( + GenPowerForecastElement, S2MessageComponent["PowerForecastElement"] +): model_config = GenPowerForecastElement.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/common/power_forecast_value.py b/src/s2python/common/power_forecast_value.py index 296b35e..ce3e6fe 100644 --- a/src/s2python/common/power_forecast_value.py +++ b/src/s2python/common/power_forecast_value.py @@ -6,6 +6,8 @@ @catch_and_convert_exceptions -class PowerForecastValue(GenPowerForecastValue, S2MessageComponent["PowerForecastValue"]): +class PowerForecastValue( + GenPowerForecastValue, S2MessageComponent["PowerForecastValue"] +): model_config = GenPowerForecastValue.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/common/power_range.py b/src/s2python/common/power_range.py index dc0e0bf..51c4fa6 100644 --- a/src/s2python/common/power_range.py +++ b/src/s2python/common/power_range.py @@ -17,6 +17,8 @@ class PowerRange(GenPowerRange, S2MessageComponent["PowerRange"]): @model_validator(mode="after") def validate_start_end_order(self) -> Self: if self.start_of_range > self.end_of_range: - raise ValueError(self, "start_of_range should not be higher than end_of_range") + raise ValueError( + self, "start_of_range should not be higher than end_of_range" + ) return self diff --git a/src/s2python/common/resource_manager_details.py b/src/s2python/common/resource_manager_details.py index 35b00b6..1ccc731 100644 --- a/src/s2python/common/resource_manager_details.py +++ b/src/s2python/common/resource_manager_details.py @@ -13,7 +13,9 @@ @catch_and_convert_exceptions -class ResourceManagerDetails(GenResourceManagerDetails, S2MessageComponent["ResourceManagerDetails"]): +class ResourceManagerDetails( + GenResourceManagerDetails, S2MessageComponent["ResourceManagerDetails"] +): model_config = GenResourceManagerDetails.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/frbc/frbc_actuator_description.py b/src/s2python/frbc/frbc_actuator_description.py index eee1132..f1865dd 100644 --- a/src/s2python/frbc/frbc_actuator_description.py +++ b/src/s2python/frbc/frbc_actuator_description.py @@ -18,7 +18,9 @@ @catch_and_convert_exceptions -class FRBCActuatorDescription(GenFRBCActuatorDescription, S2MessageComponent["FRBCActuatorDescription"]): +class FRBCActuatorDescription( + GenFRBCActuatorDescription, S2MessageComponent["FRBCActuatorDescription"] +): model_config = GenFRBCActuatorDescription.model_config model_config["validate_assignment"] = True @@ -61,14 +63,18 @@ def validate_timers_unique_ids(self) -> Self: timer: Timer for timer in self.timers: if timer.id in ids: - raise ValueError(self, f"Id {timer.id} was found multiple times in 'timers'.") + raise ValueError( + self, f"Id {timer.id} was found multiple times in 'timers'." + ) ids.append(timer.id) return self @model_validator(mode="after") def validate_operation_modes_in_transitions(self) -> Self: - operation_mode_by_id = {operation_mode.id: operation_mode for operation_mode in self.operation_modes} + operation_mode_by_id = { + operation_mode.id: operation_mode for operation_mode in self.operation_modes + } transition: Transition for transition in self.transitions: if transition.from_ not in operation_mode_by_id: @@ -111,7 +117,9 @@ def validate_operation_mode_elements_have_all_supported_commodities(self) -> Sel power_ranges_for_commodity = [ power_range for power_range in operation_mode_element.power_ranges - if commodity_has_quantity(commodity, power_range.commodity_quantity) + if commodity_has_quantity( + commodity, power_range.commodity_quantity + ) ] if len(power_ranges_for_commodity) > 1: diff --git a/src/s2python/frbc/frbc_actuator_status.py b/src/s2python/frbc/frbc_actuator_status.py index a9d6072..0e1eb26 100644 --- a/src/s2python/frbc/frbc_actuator_status.py +++ b/src/s2python/frbc/frbc_actuator_status.py @@ -9,7 +9,9 @@ @catch_and_convert_exceptions -class FRBCActuatorStatus(GenFRBCActuatorStatus, S2MessageComponent["FRBCActuatorStatus"]): +class FRBCActuatorStatus( + GenFRBCActuatorStatus, S2MessageComponent["FRBCActuatorStatus"] +): model_config = GenFRBCActuatorStatus.model_config model_config["validate_assignment"] = True @@ -18,6 +20,8 @@ class FRBCActuatorStatus(GenFRBCActuatorStatus, S2MessageComponent["FRBCActuator ] # type: ignore[assignment] actuator_id: uuid.UUID = GenFRBCActuatorStatus.model_fields["actuator_id"] # type: ignore[assignment] message_id: uuid.UUID = GenFRBCActuatorStatus.model_fields["message_id"] # type: ignore[assignment] - previous_operation_mode_id: Optional[uuid.UUID] = GenFRBCActuatorStatus.model_fields[ + previous_operation_mode_id: Optional[ + uuid.UUID + ] = GenFRBCActuatorStatus.model_fields[ "previous_operation_mode_id" ] # type: ignore[assignment] diff --git a/src/s2python/frbc/frbc_fill_level_target_profile.py b/src/s2python/frbc/frbc_fill_level_target_profile.py index 5232172..398ac54 100644 --- a/src/s2python/frbc/frbc_fill_level_target_profile.py +++ b/src/s2python/frbc/frbc_fill_level_target_profile.py @@ -14,11 +14,15 @@ @catch_and_convert_exceptions -class FRBCFillLevelTargetProfile(GenFRBCFillLevelTargetProfile, S2MessageComponent["FRBCFillLevelTargetProfile"]): +class FRBCFillLevelTargetProfile( + GenFRBCFillLevelTargetProfile, S2MessageComponent["FRBCFillLevelTargetProfile"] +): model_config = GenFRBCFillLevelTargetProfile.model_config model_config["validate_assignment"] = True - elements: List[FRBCFillLevelTargetProfileElement] = GenFRBCFillLevelTargetProfile.model_fields[ + elements: List[ + FRBCFillLevelTargetProfileElement + ] = GenFRBCFillLevelTargetProfile.model_fields[ "elements" ] # type: ignore[assignment] message_id: uuid.UUID = GenFRBCFillLevelTargetProfile.model_fields["message_id"] # type: ignore[assignment] diff --git a/src/s2python/frbc/frbc_fill_level_target_profile_element.py b/src/s2python/frbc/frbc_fill_level_target_profile_element.py index ab32ef5..2fe27be 100644 --- a/src/s2python/frbc/frbc_fill_level_target_profile_element.py +++ b/src/s2python/frbc/frbc_fill_level_target_profile_element.py @@ -8,12 +8,16 @@ from s2python.generated.gen_s2 import ( FRBCFillLevelTargetProfileElement as GenFRBCFillLevelTargetProfileElement, ) -from s2python.validate_values_mixin import catch_and_convert_exceptions, S2MessageComponent +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2MessageComponent, +) @catch_and_convert_exceptions class FRBCFillLevelTargetProfileElement( - GenFRBCFillLevelTargetProfileElement, S2MessageComponent["FRBCFillLevelTargetProfileElement"] + GenFRBCFillLevelTargetProfileElement, + S2MessageComponent["FRBCFillLevelTargetProfileElement"], ): model_config = GenFRBCFillLevelTargetProfileElement.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/frbc/frbc_leakage_behaviour.py b/src/s2python/frbc/frbc_leakage_behaviour.py index 29ca901..eca6497 100644 --- a/src/s2python/frbc/frbc_leakage_behaviour.py +++ b/src/s2python/frbc/frbc_leakage_behaviour.py @@ -10,7 +10,9 @@ @catch_and_convert_exceptions -class FRBCLeakageBehaviour(GenFRBCLeakageBehaviour, S2MessageComponent["FRBCLeakageBehaviour"]): +class FRBCLeakageBehaviour( + GenFRBCLeakageBehaviour, S2MessageComponent["FRBCLeakageBehaviour"] +): model_config = GenFRBCLeakageBehaviour.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/frbc/frbc_leakage_behaviour_element.py b/src/s2python/frbc/frbc_leakage_behaviour_element.py index 103abe9..6eb9f53 100644 --- a/src/s2python/frbc/frbc_leakage_behaviour_element.py +++ b/src/s2python/frbc/frbc_leakage_behaviour_element.py @@ -4,8 +4,13 @@ from typing_extensions import Self from s2python.common import NumberRange -from s2python.generated.gen_s2 import FRBCLeakageBehaviourElement as GenFRBCLeakageBehaviourElement -from s2python.validate_values_mixin import catch_and_convert_exceptions, S2MessageComponent +from s2python.generated.gen_s2 import ( + FRBCLeakageBehaviourElement as GenFRBCLeakageBehaviourElement, +) +from s2python.validate_values_mixin import ( + catch_and_convert_exceptions, + S2MessageComponent, +) @catch_and_convert_exceptions diff --git a/src/s2python/frbc/frbc_operation_mode.py b/src/s2python/frbc/frbc_operation_mode.py index a37d0d9..0ec3221 100644 --- a/src/s2python/frbc/frbc_operation_mode.py +++ b/src/s2python/frbc/frbc_operation_mode.py @@ -26,14 +26,21 @@ class FRBCOperationMode(GenFRBCOperationMode, S2MessageComponent["FRBCOperationM @model_validator(mode="after") def validate_contiguous_fill_levels_operation_mode_elements(self) -> Self: elements_by_fill_level_range: Dict[NumberRange, FRBCOperationModeElement] - elements_by_fill_level_range = {element.fill_level_range: element for element in self.elements} + elements_by_fill_level_range = { + element.fill_level_range: element for element in self.elements + } sorted_fill_level_ranges: List[NumberRange] sorted_fill_level_ranges = list(elements_by_fill_level_range.keys()) sorted_fill_level_ranges.sort(key=lambda r: r.start_of_range) - for current_fill_level_range, next_fill_level_range in pairwise(sorted_fill_level_ranges): - if current_fill_level_range.end_of_range != next_fill_level_range.start_of_range: + for current_fill_level_range, next_fill_level_range in pairwise( + sorted_fill_level_ranges + ): + if ( + current_fill_level_range.end_of_range + != next_fill_level_range.start_of_range + ): raise ValueError( self, f"Elements with fill level ranges {current_fill_level_range} and " diff --git a/src/s2python/frbc/frbc_operation_mode_element.py b/src/s2python/frbc/frbc_operation_mode_element.py index 55f18b3..4f58f45 100644 --- a/src/s2python/frbc/frbc_operation_mode_element.py +++ b/src/s2python/frbc/frbc_operation_mode_element.py @@ -11,7 +11,9 @@ @catch_and_convert_exceptions -class FRBCOperationModeElement(GenFRBCOperationModeElement, S2MessageComponent["FRBCOperationModeElement"]): +class FRBCOperationModeElement( + GenFRBCOperationModeElement, S2MessageComponent["FRBCOperationModeElement"] +): model_config = GenFRBCOperationModeElement.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/frbc/frbc_storage_description.py b/src/s2python/frbc/frbc_storage_description.py index 3b2c985..4c48245 100644 --- a/src/s2python/frbc/frbc_storage_description.py +++ b/src/s2python/frbc/frbc_storage_description.py @@ -9,7 +9,9 @@ @catch_and_convert_exceptions -class FRBCStorageDescription(GenFRBCStorageDescription, S2MessageComponent["FRBCStorageDescription"]): +class FRBCStorageDescription( + GenFRBCStorageDescription, S2MessageComponent["FRBCStorageDescription"] +): model_config = GenFRBCStorageDescription.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/frbc/frbc_system_description.py b/src/s2python/frbc/frbc_system_description.py index 4497d44..36f731c 100644 --- a/src/s2python/frbc/frbc_system_description.py +++ b/src/s2python/frbc/frbc_system_description.py @@ -11,7 +11,9 @@ @catch_and_convert_exceptions -class FRBCSystemDescription(GenFRBCSystemDescription, S2MessageComponent["FRBCSystemDescription"]): +class FRBCSystemDescription( + GenFRBCSystemDescription, S2MessageComponent["FRBCSystemDescription"] +): model_config = GenFRBCSystemDescription.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/frbc/frbc_usage_forecast_element.py b/src/s2python/frbc/frbc_usage_forecast_element.py index 97e9524..58cb80c 100644 --- a/src/s2python/frbc/frbc_usage_forecast_element.py +++ b/src/s2python/frbc/frbc_usage_forecast_element.py @@ -10,7 +10,9 @@ @catch_and_convert_exceptions -class FRBCUsageForecastElement(GenFRBCUsageForecastElement, S2MessageComponent["FRBCUsageForecastElement"]): +class FRBCUsageForecastElement( + GenFRBCUsageForecastElement, S2MessageComponent["FRBCUsageForecastElement"] +): model_config = GenFRBCUsageForecastElement.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/generated/gen_s2.py b/src/s2python/generated/gen_s2.py index c7febd6..f665886 100644 --- a/src/s2python/generated/gen_s2.py +++ b/src/s2python/generated/gen_s2.py @@ -20,805 +20,805 @@ class Duration(RootModel[conint(ge=0)]): - root: conint(ge=0) = Field(..., description='Duration in milliseconds') + root: conint(ge=0) = Field(..., description="Duration in milliseconds") -class ID(RootModel[constr(pattern=r'[a-zA-Z0-9\-_:]{2,64}')]): - root: constr(pattern=r'[a-zA-Z0-9\-_:]{2,64}') = Field(..., description='UUID') +class ID(RootModel[constr(pattern=r"[a-zA-Z0-9\-_:]{2,64}")]): + root: constr(pattern=r"[a-zA-Z0-9\-_:]{2,64}") = Field(..., description="UUID") class Currency(Enum): - AED = 'AED' - ANG = 'ANG' - AUD = 'AUD' - CHE = 'CHE' - CHF = 'CHF' - CHW = 'CHW' - EUR = 'EUR' - GBP = 'GBP' - LBP = 'LBP' - LKR = 'LKR' - LRD = 'LRD' - LSL = 'LSL' - LYD = 'LYD' - MAD = 'MAD' - MDL = 'MDL' - MGA = 'MGA' - MKD = 'MKD' - MMK = 'MMK' - MNT = 'MNT' - MOP = 'MOP' - MRO = 'MRO' - MUR = 'MUR' - MVR = 'MVR' - MWK = 'MWK' - MXN = 'MXN' - MXV = 'MXV' - MYR = 'MYR' - MZN = 'MZN' - NAD = 'NAD' - NGN = 'NGN' - NIO = 'NIO' - NOK = 'NOK' - NPR = 'NPR' - NZD = 'NZD' - OMR = 'OMR' - PAB = 'PAB' - PEN = 'PEN' - PGK = 'PGK' - PHP = 'PHP' - PKR = 'PKR' - PLN = 'PLN' - PYG = 'PYG' - QAR = 'QAR' - RON = 'RON' - RSD = 'RSD' - RUB = 'RUB' - RWF = 'RWF' - SAR = 'SAR' - SBD = 'SBD' - SCR = 'SCR' - SDG = 'SDG' - SEK = 'SEK' - SGD = 'SGD' - SHP = 'SHP' - SLL = 'SLL' - SOS = 'SOS' - SRD = 'SRD' - SSP = 'SSP' - STD = 'STD' - SYP = 'SYP' - SZL = 'SZL' - THB = 'THB' - TJS = 'TJS' - TMT = 'TMT' - TND = 'TND' - TOP = 'TOP' - TRY = 'TRY' - TTD = 'TTD' - TWD = 'TWD' - TZS = 'TZS' - UAH = 'UAH' - UGX = 'UGX' - USD = 'USD' - USN = 'USN' - UYI = 'UYI' - UYU = 'UYU' - UZS = 'UZS' - VEF = 'VEF' - VND = 'VND' - VUV = 'VUV' - WST = 'WST' - XAG = 'XAG' - XAU = 'XAU' - XBA = 'XBA' - XBB = 'XBB' - XBC = 'XBC' - XBD = 'XBD' - XCD = 'XCD' - XOF = 'XOF' - XPD = 'XPD' - XPF = 'XPF' - XPT = 'XPT' - XSU = 'XSU' - XTS = 'XTS' - XUA = 'XUA' - XXX = 'XXX' - YER = 'YER' - ZAR = 'ZAR' - ZMW = 'ZMW' - ZWL = 'ZWL' + AED = "AED" + ANG = "ANG" + AUD = "AUD" + CHE = "CHE" + CHF = "CHF" + CHW = "CHW" + EUR = "EUR" + GBP = "GBP" + LBP = "LBP" + LKR = "LKR" + LRD = "LRD" + LSL = "LSL" + LYD = "LYD" + MAD = "MAD" + MDL = "MDL" + MGA = "MGA" + MKD = "MKD" + MMK = "MMK" + MNT = "MNT" + MOP = "MOP" + MRO = "MRO" + MUR = "MUR" + MVR = "MVR" + MWK = "MWK" + MXN = "MXN" + MXV = "MXV" + MYR = "MYR" + MZN = "MZN" + NAD = "NAD" + NGN = "NGN" + NIO = "NIO" + NOK = "NOK" + NPR = "NPR" + NZD = "NZD" + OMR = "OMR" + PAB = "PAB" + PEN = "PEN" + PGK = "PGK" + PHP = "PHP" + PKR = "PKR" + PLN = "PLN" + PYG = "PYG" + QAR = "QAR" + RON = "RON" + RSD = "RSD" + RUB = "RUB" + RWF = "RWF" + SAR = "SAR" + SBD = "SBD" + SCR = "SCR" + SDG = "SDG" + SEK = "SEK" + SGD = "SGD" + SHP = "SHP" + SLL = "SLL" + SOS = "SOS" + SRD = "SRD" + SSP = "SSP" + STD = "STD" + SYP = "SYP" + SZL = "SZL" + THB = "THB" + TJS = "TJS" + TMT = "TMT" + TND = "TND" + TOP = "TOP" + TRY = "TRY" + TTD = "TTD" + TWD = "TWD" + TZS = "TZS" + UAH = "UAH" + UGX = "UGX" + USD = "USD" + USN = "USN" + UYI = "UYI" + UYU = "UYU" + UZS = "UZS" + VEF = "VEF" + VND = "VND" + VUV = "VUV" + WST = "WST" + XAG = "XAG" + XAU = "XAU" + XBA = "XBA" + XBB = "XBB" + XBC = "XBC" + XBD = "XBD" + XCD = "XCD" + XOF = "XOF" + XPD = "XPD" + XPF = "XPF" + XPT = "XPT" + XSU = "XSU" + XTS = "XTS" + XUA = "XUA" + XXX = "XXX" + YER = "YER" + ZAR = "ZAR" + ZMW = "ZMW" + ZWL = "ZWL" class SessionRequestType(Enum): - RECONNECT = 'RECONNECT' - TERMINATE = 'TERMINATE' + RECONNECT = "RECONNECT" + TERMINATE = "TERMINATE" class RevokableObjects(Enum): - PEBC_PowerConstraints = 'PEBC.PowerConstraints' - PEBC_EnergyConstraint = 'PEBC.EnergyConstraint' - PEBC_Instruction = 'PEBC.Instruction' - PPBC_PowerProfileDefinition = 'PPBC.PowerProfileDefinition' - PPBC_ScheduleInstruction = 'PPBC.ScheduleInstruction' - PPBC_StartInterruptionInstruction = 'PPBC.StartInterruptionInstruction' - PPBC_EndInterruptionInstruction = 'PPBC.EndInterruptionInstruction' - OMBC_SystemDescription = 'OMBC.SystemDescription' - OMBC_Instruction = 'OMBC.Instruction' - FRBC_SystemDescription = 'FRBC.SystemDescription' - FRBC_Instruction = 'FRBC.Instruction' - DDBC_SystemDescription = 'DDBC.SystemDescription' - DDBC_Instruction = 'DDBC.Instruction' + PEBC_PowerConstraints = "PEBC.PowerConstraints" + PEBC_EnergyConstraint = "PEBC.EnergyConstraint" + PEBC_Instruction = "PEBC.Instruction" + PPBC_PowerProfileDefinition = "PPBC.PowerProfileDefinition" + PPBC_ScheduleInstruction = "PPBC.ScheduleInstruction" + PPBC_StartInterruptionInstruction = "PPBC.StartInterruptionInstruction" + PPBC_EndInterruptionInstruction = "PPBC.EndInterruptionInstruction" + OMBC_SystemDescription = "OMBC.SystemDescription" + OMBC_Instruction = "OMBC.Instruction" + FRBC_SystemDescription = "FRBC.SystemDescription" + FRBC_Instruction = "FRBC.Instruction" + DDBC_SystemDescription = "DDBC.SystemDescription" + DDBC_Instruction = "DDBC.Instruction" class EnergyManagementRole(Enum): - CEM = 'CEM' - RM = 'RM' + CEM = "CEM" + RM = "RM" class ReceptionStatusValues(Enum): - INVALID_DATA = 'INVALID_DATA' - INVALID_MESSAGE = 'INVALID_MESSAGE' - INVALID_CONTENT = 'INVALID_CONTENT' - TEMPORARY_ERROR = 'TEMPORARY_ERROR' - PERMANENT_ERROR = 'PERMANENT_ERROR' - OK = 'OK' + INVALID_DATA = "INVALID_DATA" + INVALID_MESSAGE = "INVALID_MESSAGE" + INVALID_CONTENT = "INVALID_CONTENT" + TEMPORARY_ERROR = "TEMPORARY_ERROR" + PERMANENT_ERROR = "PERMANENT_ERROR" + OK = "OK" class NumberRange(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) start_of_range: float = Field( - ..., description='Number that defines the start of the range' + ..., description="Number that defines the start of the range" ) end_of_range: float = Field( - ..., description='Number that defines the end of the range' + ..., description="Number that defines the end of the range" ) class Transition(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) id: ID = Field( ..., - description='ID of the Transition. Must be unique in the scope of the OMBC.SystemDescription, FRBC.ActuatorDescription or DDBC.ActuatorDescription in which it is used.', + description="ID of the Transition. Must be unique in the scope of the OMBC.SystemDescription, FRBC.ActuatorDescription or DDBC.ActuatorDescription in which it is used.", ) from_: ID = Field( ..., - alias='from', - description='ID of the OperationMode (exact type differs per ControlType) that should be switched from.', + alias="from", + description="ID of the OperationMode (exact type differs per ControlType) that should be switched from.", ) to: ID = Field( ..., - description='ID of the OperationMode (exact type differs per ControlType) that will be switched to.', + description="ID of the OperationMode (exact type differs per ControlType) that will be switched to.", ) start_timers: List[ID] = Field( ..., - description='List of IDs of Timers that will be (re)started when this transition is initiated', + description="List of IDs of Timers that will be (re)started when this transition is initiated", max_length=1000, min_length=0, ) blocking_timers: List[ID] = Field( ..., - description='List of IDs of Timers that block this Transition from initiating while at least one of these Timers is not yet finished', + description="List of IDs of Timers that block this Transition from initiating while at least one of these Timers is not yet finished", max_length=1000, min_length=0, ) transition_costs: Optional[float] = Field( None, - description='Absolute costs for going through this Transition in the currency as described in the ResourceManagerDetails.', + description="Absolute costs for going through this Transition in the currency as described in the ResourceManagerDetails.", ) transition_duration: Optional[Duration] = Field( None, - description='Indicates the time between the initiation of this Transition, and the time at which the device behaves according to the Operation Mode which is defined in the ‘to’ data element. When no value is provided it is assumed the transition duration is negligible.', + description="Indicates the time between the initiation of this Transition, and the time at which the device behaves according to the Operation Mode which is defined in the ‘to’ data element. When no value is provided it is assumed the transition duration is negligible.", ) abnormal_condition_only: bool = Field( ..., - description='Indicates if this Transition may only be used during an abnormal condition (see Clause )', + description="Indicates if this Transition may only be used during an abnormal condition (see Clause )", ) class Timer(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) id: ID = Field( ..., - description='ID of the Timer. Must be unique in the scope of the OMBC.SystemDescription, FRBC.ActuatorDescription or DDBC.ActuatorDescription in which it is used.', + description="ID of the Timer. Must be unique in the scope of the OMBC.SystemDescription, FRBC.ActuatorDescription or DDBC.ActuatorDescription in which it is used.", ) diagnostic_label: Optional[str] = Field( None, - description='Human readable name/description of the Timer. This element is only intended for diagnostic purposes and not for HMI applications.', + description="Human readable name/description of the Timer. This element is only intended for diagnostic purposes and not for HMI applications.", ) duration: Duration = Field( ..., - description='The time it takes for the Timer to finish after it has been started', + description="The time it takes for the Timer to finish after it has been started", ) class PEBCPowerEnvelopeElement(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - duration: Duration = Field(..., description='The duration of the element') + duration: Duration = Field(..., description="The duration of the element") upper_limit: float = Field( ..., - description='Upper power limit according to the commodity_quantity of the containing PEBC.PowerEnvelope. The lower_limit must be smaller or equal to the upper_limit. The Resource Manager is requested to keep the power values for the given commodity quantity equal to or below the upper_limit. The upper_limit shall be in accordance with the constraints provided by the Resource Manager through any PEBC.AllowedLimitRange with limit_type UPPER_LIMIT.', + description="Upper power limit according to the commodity_quantity of the containing PEBC.PowerEnvelope. The lower_limit must be smaller or equal to the upper_limit. The Resource Manager is requested to keep the power values for the given commodity quantity equal to or below the upper_limit. The upper_limit shall be in accordance with the constraints provided by the Resource Manager through any PEBC.AllowedLimitRange with limit_type UPPER_LIMIT.", ) lower_limit: float = Field( ..., - description='Lower power limit according to the commodity_quantity of the containing PEBC.PowerEnvelope. The lower_limit must be smaller or equal to the upper_limit. The Resource Manager is requested to keep the power values for the given commodity quantity equal to or above the lower_limit. The lower_limit shall be in accordance with the constraints provided by the Resource Manager through any PEBC.AllowedLimitRange with limit_type LOWER_LIMIT.', + description="Lower power limit according to the commodity_quantity of the containing PEBC.PowerEnvelope. The lower_limit must be smaller or equal to the upper_limit. The Resource Manager is requested to keep the power values for the given commodity quantity equal to or above the lower_limit. The lower_limit shall be in accordance with the constraints provided by the Resource Manager through any PEBC.AllowedLimitRange with limit_type LOWER_LIMIT.", ) class FRBCStorageDescription(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) diagnostic_label: Optional[str] = Field( None, - description='Human readable name/description of the storage (e.g. hot water buffer or battery). This element is only intended for diagnostic purposes and not for HMI applications.', + description="Human readable name/description of the storage (e.g. hot water buffer or battery). This element is only intended for diagnostic purposes and not for HMI applications.", ) fill_level_label: Optional[str] = Field( None, - description='Human readable description of the (physical) units associated with the fill_level (e.g. degrees Celsius or percentage state of charge). This element is only intended for diagnostic purposes and not for HMI applications.', + description="Human readable description of the (physical) units associated with the fill_level (e.g. degrees Celsius or percentage state of charge). This element is only intended for diagnostic purposes and not for HMI applications.", ) provides_leakage_behaviour: bool = Field( ..., - description='Indicates whether the Storage could provide details of power leakage behaviour through the FRBC.LeakageBehaviour.', + description="Indicates whether the Storage could provide details of power leakage behaviour through the FRBC.LeakageBehaviour.", ) provides_fill_level_target_profile: bool = Field( ..., - description='Indicates whether the Storage could provide a target profile for the fill level through the FRBC.FillLevelTargetProfile.', + description="Indicates whether the Storage could provide a target profile for the fill level through the FRBC.FillLevelTargetProfile.", ) provides_usage_forecast: bool = Field( ..., - description='Indicates whether the Storage could provide a UsageForecast through the FRBC.UsageForecast.', + description="Indicates whether the Storage could provide a UsageForecast through the FRBC.UsageForecast.", ) fill_level_range: NumberRange = Field( ..., - description='The range in which the fill_level should remain. It is expected of the CEM to keep the fill_level within this range. When the fill_level is not within this range, the Resource Manager can ignore instructions from the CEM (except during abnormal conditions). ', + description="The range in which the fill_level should remain. It is expected of the CEM to keep the fill_level within this range. When the fill_level is not within this range, the Resource Manager can ignore instructions from the CEM (except during abnormal conditions). ", ) class FRBCLeakageBehaviourElement(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) fill_level_range: NumberRange = Field( ..., - description='The fill level range for which this FRBC.LeakageBehaviourElement applies. The start of the range must be less than the end of the range.', + description="The fill level range for which this FRBC.LeakageBehaviourElement applies. The start of the range must be less than the end of the range.", ) leakage_rate: float = Field( ..., - description='Indicates how fast the momentary fill level will decrease per second due to leakage within the given range of the fill level. A positive value indicates that the fill level decreases over time due to leakage.', + description="Indicates how fast the momentary fill level will decrease per second due to leakage within the given range of the fill level. A positive value indicates that the fill level decreases over time due to leakage.", ) class FRBCUsageForecastElement(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) duration: Duration = Field( - ..., description='Indicator for how long the given usage_rate is valid.' + ..., description="Indicator for how long the given usage_rate is valid." ) usage_rate_upper_limit: Optional[float] = Field( None, - description='The upper limit of the range with a 100 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', + description="The upper limit of the range with a 100 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.", ) usage_rate_upper_95PPR: Optional[float] = Field( None, - description='The upper limit of the range with a 95 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', + description="The upper limit of the range with a 95 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.", ) usage_rate_upper_68PPR: Optional[float] = Field( None, - description='The upper limit of the range with a 68 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', + description="The upper limit of the range with a 68 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.", ) usage_rate_expected: float = Field( ..., - description='The most likely value for the usage rate; the expected increase or decrease of the fill_level per second. A positive value indicates that the fill level will decrease due to usage.', + description="The most likely value for the usage rate; the expected increase or decrease of the fill_level per second. A positive value indicates that the fill level will decrease due to usage.", ) usage_rate_lower_68PPR: Optional[float] = Field( None, - description='The lower limit of the range with a 68 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', + description="The lower limit of the range with a 68 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.", ) usage_rate_lower_95PPR: Optional[float] = Field( None, - description='The lower limit of the range with a 95 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', + description="The lower limit of the range with a 95 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.", ) usage_rate_lower_limit: Optional[float] = Field( None, - description='The lower limit of the range with a 100 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.', + description="The lower limit of the range with a 100 % probability that the usage rate is within that range. A positive value indicates that the fill level will decrease due to usage.", ) class FRBCFillLevelTargetProfileElement(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - duration: Duration = Field(..., description='The duration of the element.') + duration: Duration = Field(..., description="The duration of the element.") fill_level_range: NumberRange = Field( ..., - description='The target range in which the fill_level must be for the time period during which the element is active. The start of the range must be smaller or equal to the end of the range. The CEM must take best-effort actions to proactively achieve this target.', + description="The target range in which the fill_level must be for the time period during which the element is active. The start of the range must be smaller or equal to the end of the range. The CEM must take best-effort actions to proactively achieve this target.", ) class DDBCAverageDemandRateForecastElement(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - duration: Duration = Field(..., description='Duration of the element') + duration: Duration = Field(..., description="Duration of the element") demand_rate_upper_limit: Optional[float] = Field( None, - description='The upper limit of the range with a 100 % probability that the demand rate is within that range', + description="The upper limit of the range with a 100 % probability that the demand rate is within that range", ) demand_rate_upper_95PPR: Optional[float] = Field( None, - description='The upper limit of the range with a 95 % probability that the demand rate is within that range', + description="The upper limit of the range with a 95 % probability that the demand rate is within that range", ) demand_rate_upper_68PPR: Optional[float] = Field( None, - description='The upper limit of the range with a 68 % probability that the demand rate is within that range', + description="The upper limit of the range with a 68 % probability that the demand rate is within that range", ) demand_rate_expected: float = Field( ..., - description='The most likely value for the demand rate; the expected increase or decrease of the fill_level per second', + description="The most likely value for the demand rate; the expected increase or decrease of the fill_level per second", ) demand_rate_lower_68PPR: Optional[float] = Field( None, - description='The lower limit of the range with a 68 % probability that the demand rate is within that range', + description="The lower limit of the range with a 68 % probability that the demand rate is within that range", ) demand_rate_lower_95PPR: Optional[float] = Field( None, - description='The lower limit of the range with a 95 % probability that the demand rate is within that range', + description="The lower limit of the range with a 95 % probability that the demand rate is within that range", ) demand_rate_lower_limit: Optional[float] = Field( None, - description='The lower limit of the range with a 100 % probability that the demand rate is within that range', + description="The lower limit of the range with a 100 % probability that the demand rate is within that range", ) class RoleType(Enum): - ENERGY_PRODUCER = 'ENERGY_PRODUCER' - ENERGY_CONSUMER = 'ENERGY_CONSUMER' - ENERGY_STORAGE = 'ENERGY_STORAGE' + ENERGY_PRODUCER = "ENERGY_PRODUCER" + ENERGY_CONSUMER = "ENERGY_CONSUMER" + ENERGY_STORAGE = "ENERGY_STORAGE" class Commodity(Enum): - GAS = 'GAS' - HEAT = 'HEAT' - ELECTRICITY = 'ELECTRICITY' - OIL = 'OIL' + GAS = "GAS" + HEAT = "HEAT" + ELECTRICITY = "ELECTRICITY" + OIL = "OIL" class CommodityQuantity(Enum): - ELECTRIC_POWER_L1 = 'ELECTRIC.POWER.L1' - ELECTRIC_POWER_L2 = 'ELECTRIC.POWER.L2' - ELECTRIC_POWER_L3 = 'ELECTRIC.POWER.L3' - ELECTRIC_POWER_3_PHASE_SYMMETRIC = 'ELECTRIC.POWER.3_PHASE_SYMMETRIC' - NATURAL_GAS_FLOW_RATE = 'NATURAL_GAS.FLOW_RATE' - HYDROGEN_FLOW_RATE = 'HYDROGEN.FLOW_RATE' - HEAT_TEMPERATURE = 'HEAT.TEMPERATURE' - HEAT_FLOW_RATE = 'HEAT.FLOW_RATE' - HEAT_THERMAL_POWER = 'HEAT.THERMAL_POWER' - OIL_FLOW_RATE = 'OIL.FLOW_RATE' + ELECTRIC_POWER_L1 = "ELECTRIC.POWER.L1" + ELECTRIC_POWER_L2 = "ELECTRIC.POWER.L2" + ELECTRIC_POWER_L3 = "ELECTRIC.POWER.L3" + ELECTRIC_POWER_3_PHASE_SYMMETRIC = "ELECTRIC.POWER.3_PHASE_SYMMETRIC" + NATURAL_GAS_FLOW_RATE = "NATURAL_GAS.FLOW_RATE" + HYDROGEN_FLOW_RATE = "HYDROGEN.FLOW_RATE" + HEAT_TEMPERATURE = "HEAT.TEMPERATURE" + HEAT_FLOW_RATE = "HEAT.FLOW_RATE" + HEAT_THERMAL_POWER = "HEAT.THERMAL_POWER" + OIL_FLOW_RATE = "OIL.FLOW_RATE" class InstructionStatus(Enum): - NEW = 'NEW' - ACCEPTED = 'ACCEPTED' - REJECTED = 'REJECTED' - REVOKED = 'REVOKED' - STARTED = 'STARTED' - SUCCEEDED = 'SUCCEEDED' - ABORTED = 'ABORTED' + NEW = "NEW" + ACCEPTED = "ACCEPTED" + REJECTED = "REJECTED" + REVOKED = "REVOKED" + STARTED = "STARTED" + SUCCEEDED = "SUCCEEDED" + ABORTED = "ABORTED" class ControlType(Enum): - POWER_ENVELOPE_BASED_CONTROL = 'POWER_ENVELOPE_BASED_CONTROL' - POWER_PROFILE_BASED_CONTROL = 'POWER_PROFILE_BASED_CONTROL' - OPERATION_MODE_BASED_CONTROL = 'OPERATION_MODE_BASED_CONTROL' - FILL_RATE_BASED_CONTROL = 'FILL_RATE_BASED_CONTROL' - DEMAND_DRIVEN_BASED_CONTROL = 'DEMAND_DRIVEN_BASED_CONTROL' - NOT_CONTROLABLE = 'NOT_CONTROLABLE' - NO_SELECTION = 'NO_SELECTION' + POWER_ENVELOPE_BASED_CONTROL = "POWER_ENVELOPE_BASED_CONTROL" + POWER_PROFILE_BASED_CONTROL = "POWER_PROFILE_BASED_CONTROL" + OPERATION_MODE_BASED_CONTROL = "OPERATION_MODE_BASED_CONTROL" + FILL_RATE_BASED_CONTROL = "FILL_RATE_BASED_CONTROL" + DEMAND_DRIVEN_BASED_CONTROL = "DEMAND_DRIVEN_BASED_CONTROL" + NOT_CONTROLABLE = "NOT_CONTROLABLE" + NO_SELECTION = "NO_SELECTION" class PEBCPowerEnvelopeLimitType(Enum): - UPPER_LIMIT = 'UPPER_LIMIT' - LOWER_LIMIT = 'LOWER_LIMIT' + UPPER_LIMIT = "UPPER_LIMIT" + LOWER_LIMIT = "LOWER_LIMIT" class PEBCPowerEnvelopeConsequenceType(Enum): - VANISH = 'VANISH' - DEFER = 'DEFER' + VANISH = "VANISH" + DEFER = "DEFER" class PPBCPowerSequenceStatus(Enum): - NOT_SCHEDULED = 'NOT_SCHEDULED' - SCHEDULED = 'SCHEDULED' - EXECUTING = 'EXECUTING' - INTERRUPTED = 'INTERRUPTED' - FINISHED = 'FINISHED' - ABORTED = 'ABORTED' + NOT_SCHEDULED = "NOT_SCHEDULED" + SCHEDULED = "SCHEDULED" + EXECUTING = "EXECUTING" + INTERRUPTED = "INTERRUPTED" + FINISHED = "FINISHED" + ABORTED = "ABORTED" class OMBCTimerStatus(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['OMBC.TimerStatus'] = 'OMBC.TimerStatus' + message_type: Literal["OMBC.TimerStatus"] = "OMBC.TimerStatus" message_id: ID - timer_id: ID = Field(..., description='The ID of the timer this message refers to') + timer_id: ID = Field(..., description="The ID of the timer this message refers to") finished_at: AwareDatetime = Field( ..., - description='Indicates when the Timer will be finished. If the DateTimeStamp is in the future, the timer is not yet finished. If the DateTimeStamp is in the past, the timer is finished. If the timer was never started, the value can be an arbitrary DateTimeStamp in the past.', + description="Indicates when the Timer will be finished. If the DateTimeStamp is in the future, the timer is not yet finished. If the DateTimeStamp is in the past, the timer is finished. If the timer was never started, the value can be an arbitrary DateTimeStamp in the past.", ) class FRBCTimerStatus(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['FRBC.TimerStatus'] = 'FRBC.TimerStatus' + message_type: Literal["FRBC.TimerStatus"] = "FRBC.TimerStatus" message_id: ID - timer_id: ID = Field(..., description='The ID of the timer this message refers to') + timer_id: ID = Field(..., description="The ID of the timer this message refers to") actuator_id: ID = Field( - ..., description='The ID of the actuator the timer belongs to' + ..., description="The ID of the actuator the timer belongs to" ) finished_at: AwareDatetime = Field( ..., - description='Indicates when the Timer will be finished. If the DateTimeStamp is in the future, the timer is not yet finished. If the DateTimeStamp is in the past, the timer is finished. If the timer was never started, the value can be an arbitrary DateTimeStamp in the past.', + description="Indicates when the Timer will be finished. If the DateTimeStamp is in the future, the timer is not yet finished. If the DateTimeStamp is in the past, the timer is finished. If the timer was never started, the value can be an arbitrary DateTimeStamp in the past.", ) class DDBCTimerStatus(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['DDBC.TimerStatus'] = 'DDBC.TimerStatus' + message_type: Literal["DDBC.TimerStatus"] = "DDBC.TimerStatus" message_id: ID - timer_id: ID = Field(..., description='The ID of the timer this message refers to') + timer_id: ID = Field(..., description="The ID of the timer this message refers to") actuator_id: ID = Field( - ..., description='The ID of the actuator the timer belongs to' + ..., description="The ID of the actuator the timer belongs to" ) finished_at: AwareDatetime = Field( ..., - description='Indicates when the Timer will be finished. If the DateTimeStamp is in the future, the timer is not yet finished. If the DateTimeStamp is in the past, the timer is finished. If the timer was never started, the value can be an arbitrary DateTimeStamp in the past.', + description="Indicates when the Timer will be finished. If the DateTimeStamp is in the future, the timer is not yet finished. If the DateTimeStamp is in the past, the timer is finished. If the timer was never started, the value can be an arbitrary DateTimeStamp in the past.", ) class SelectControlType(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['SelectControlType'] = 'SelectControlType' + message_type: Literal["SelectControlType"] = "SelectControlType" message_id: ID control_type: ControlType = Field( ..., - description='The ControlType to activate. Must be one of the available ControlTypes as defined in the ResourceManagerDetails', + description="The ControlType to activate. Must be one of the available ControlTypes as defined in the ResourceManagerDetails", ) class SessionRequest(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['SessionRequest'] = 'SessionRequest' + message_type: Literal["SessionRequest"] = "SessionRequest" message_id: ID - request: SessionRequestType = Field(..., description='The type of request') + request: SessionRequestType = Field(..., description="The type of request") diagnostic_label: Optional[str] = Field( None, - description='Optional field for a human readible descirption for debugging purposes', + description="Optional field for a human readible descirption for debugging purposes", ) class RevokeObject(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['RevokeObject'] = 'RevokeObject' + message_type: Literal["RevokeObject"] = "RevokeObject" message_id: ID object_type: RevokableObjects = Field( - ..., description='The type of object that needs to be revoked' + ..., description="The type of object that needs to be revoked" ) - object_id: ID = Field(..., description='The ID of object that needs to be revoked') + object_id: ID = Field(..., description="The ID of object that needs to be revoked") class Handshake(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['Handshake'] = 'Handshake' + message_type: Literal["Handshake"] = "Handshake" message_id: ID role: EnergyManagementRole = Field( - ..., description='The role of the sender of this message' + ..., description="The role of the sender of this message" ) supported_protocol_versions: Optional[List[str]] = Field( None, - description='Protocol versions supported by the sender of this message. This field is mandatory for the RM, but optional for the CEM.', + description="Protocol versions supported by the sender of this message. This field is mandatory for the RM, but optional for the CEM.", min_length=1, ) class HandshakeResponse(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['HandshakeResponse'] = 'HandshakeResponse' + message_type: Literal["HandshakeResponse"] = "HandshakeResponse" message_id: ID selected_protocol_version: str = Field( - ..., description='The protocol version the CEM selected for this session' + ..., description="The protocol version the CEM selected for this session" ) class ReceptionStatus(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['ReceptionStatus'] = 'ReceptionStatus' + message_type: Literal["ReceptionStatus"] = "ReceptionStatus" subject_message_id: ID = Field( - ..., description='The message this ReceptionStatus refers to' + ..., description="The message this ReceptionStatus refers to" ) status: ReceptionStatusValues = Field( - ..., description='Enumeration of status values' + ..., description="Enumeration of status values" ) diagnostic_label: Optional[str] = Field( None, - description='Diagnostic label that can be used to provide additional information for debugging. However, not for HMI purposes.', + description="Diagnostic label that can be used to provide additional information for debugging. However, not for HMI purposes.", ) class InstructionStatusUpdate(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['InstructionStatusUpdate'] = 'InstructionStatusUpdate' + message_type: Literal["InstructionStatusUpdate"] = "InstructionStatusUpdate" message_id: ID instruction_id: ID = Field( - ..., description='ID of this instruction (as provided by the CEM) ' + ..., description="ID of this instruction (as provided by the CEM) " ) status_type: InstructionStatus = Field( - ..., description='Present status of this instruction.' + ..., description="Present status of this instruction." ) timestamp: AwareDatetime = Field( - ..., description='Timestamp when status_type has changed the last time.' + ..., description="Timestamp when status_type has changed the last time." ) class PEBCEnergyConstraint(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['PEBC.EnergyConstraint'] = 'PEBC.EnergyConstraint' + message_type: Literal["PEBC.EnergyConstraint"] = "PEBC.EnergyConstraint" message_id: ID id: ID = Field( ..., - description='Identifier of this PEBC.EnergyConstraints. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + description="Identifier of this PEBC.EnergyConstraints. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.", ) valid_from: AwareDatetime = Field( ..., - description='Moment this PEBC.EnergyConstraints information starts to be valid', + description="Moment this PEBC.EnergyConstraints information starts to be valid", ) valid_until: AwareDatetime = Field( ..., - description='Moment until this PEBC.EnergyConstraints information is valid.', + description="Moment until this PEBC.EnergyConstraints information is valid.", ) upper_average_power: float = Field( ..., - description='Upper average power within the time period given by valid_from and valid_until. If the duration is multiplied with this power value, then the associated upper energy content can be derived. This is the highest amount of energy the resource will consume during that period of time. The Power Envelope created by the CEM must allow at least this much energy consumption (in case the number is positive). Must be greater than or equal to lower_average_power, and can be negative in case of energy production.', + description="Upper average power within the time period given by valid_from and valid_until. If the duration is multiplied with this power value, then the associated upper energy content can be derived. This is the highest amount of energy the resource will consume during that period of time. The Power Envelope created by the CEM must allow at least this much energy consumption (in case the number is positive). Must be greater than or equal to lower_average_power, and can be negative in case of energy production.", ) lower_average_power: float = Field( ..., - description='Lower average power within the time period given by valid_from and valid_until. If the duration is multiplied with this power value, then the associated lower energy content can be derived. This is the lowest amount of energy the resource will consume during that period of time. The Power Envelope created by the CEM must allow at least this much energy production (in case the number is negative). Must be greater than or equal to lower_average_power, and can be negative in case of energy production.', + description="Lower average power within the time period given by valid_from and valid_until. If the duration is multiplied with this power value, then the associated lower energy content can be derived. This is the lowest amount of energy the resource will consume during that period of time. The Power Envelope created by the CEM must allow at least this much energy production (in case the number is negative). Must be greater than or equal to lower_average_power, and can be negative in case of energy production.", ) commodity_quantity: CommodityQuantity = Field( ..., - description='Type of power quantity which applies to upper_average_power and lower_average_power', + description="Type of power quantity which applies to upper_average_power and lower_average_power", ) class PPBCScheduleInstruction(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['PPBC.ScheduleInstruction'] = 'PPBC.ScheduleInstruction' + message_type: Literal["PPBC.ScheduleInstruction"] = "PPBC.ScheduleInstruction" message_id: ID id: ID = Field( ..., - description='ID of the Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + description="ID of the Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.", ) power_profile_id: ID = Field( ..., - description='ID of the PPBC.PowerProfileDefinition of which the PPBC.PowerSequence is being selected and scheduled by the CEM.', + description="ID of the PPBC.PowerProfileDefinition of which the PPBC.PowerSequence is being selected and scheduled by the CEM.", ) sequence_container_id: ID = Field( ..., - description='ID of the PPBC.PowerSequnceContainer of which the PPBC.PowerSequence is being selected and scheduled by the CEM.', + description="ID of the PPBC.PowerSequnceContainer of which the PPBC.PowerSequence is being selected and scheduled by the CEM.", ) power_sequence_id: ID = Field( ..., - description='ID of the PPBC.PowerSequence that is being selected and scheduled by the CEM.', + description="ID of the PPBC.PowerSequence that is being selected and scheduled by the CEM.", ) execution_time: AwareDatetime = Field( ..., - description='Indicates the moment the PPBC.PowerSequence shall start. When the specified execution time is in the past, execution must start as soon as possible.', + description="Indicates the moment the PPBC.PowerSequence shall start. When the specified execution time is in the past, execution must start as soon as possible.", ) abnormal_condition: bool = Field( ..., - description='Indicates if this is an instruction during an abnormal condition', + description="Indicates if this is an instruction during an abnormal condition", ) class PPBCStartInterruptionInstruction(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['PPBC.StartInterruptionInstruction'] = ( - 'PPBC.StartInterruptionInstruction' + message_type: Literal["PPBC.StartInterruptionInstruction"] = ( + "PPBC.StartInterruptionInstruction" ) message_id: ID id: ID = Field( ..., - description='ID of the Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + description="ID of the Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.", ) power_profile_id: ID = Field( ..., - description='ID of the PPBC.PowerProfileDefinition of which the PPBC.PowerSequence is being interrupted by the CEM.', + description="ID of the PPBC.PowerProfileDefinition of which the PPBC.PowerSequence is being interrupted by the CEM.", ) sequence_container_id: ID = Field( ..., - description='ID of the PPBC.PowerSequnceContainer of which the PPBC.PowerSequence is being interrupted by the CEM.', + description="ID of the PPBC.PowerSequnceContainer of which the PPBC.PowerSequence is being interrupted by the CEM.", ) power_sequence_id: ID = Field( - ..., description='ID of the PPBC.PowerSequence that the CEM wants to interrupt.' + ..., description="ID of the PPBC.PowerSequence that the CEM wants to interrupt." ) execution_time: AwareDatetime = Field( ..., - description='Indicates the moment the PPBC.PowerSequence shall be interrupted. When the specified execution time is in the past, execution must start as soon as possible.', + description="Indicates the moment the PPBC.PowerSequence shall be interrupted. When the specified execution time is in the past, execution must start as soon as possible.", ) abnormal_condition: bool = Field( ..., - description='Indicates if this is an instruction during an abnormal condition', + description="Indicates if this is an instruction during an abnormal condition", ) class PPBCEndInterruptionInstruction(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['PPBC.EndInterruptionInstruction'] = ( - 'PPBC.EndInterruptionInstruction' + message_type: Literal["PPBC.EndInterruptionInstruction"] = ( + "PPBC.EndInterruptionInstruction" ) message_id: ID id: ID = Field( ..., - description='ID of the Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + description="ID of the Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.", ) power_profile_id: ID = Field( ..., - description='ID of the PPBC.PowerProfileDefinition of which the PPBC.PowerSequence interruption is being ended by the CEM.', + description="ID of the PPBC.PowerProfileDefinition of which the PPBC.PowerSequence interruption is being ended by the CEM.", ) sequence_container_id: ID = Field( ..., - description='ID of the PPBC.PowerSequnceContainer of which the PPBC.PowerSequence interruption is being ended by the CEM.', + description="ID of the PPBC.PowerSequnceContainer of which the PPBC.PowerSequence interruption is being ended by the CEM.", ) power_sequence_id: ID = Field( ..., - description='ID of the PPBC.PowerSequence for which the CEM wants to end the interruption.', + description="ID of the PPBC.PowerSequence for which the CEM wants to end the interruption.", ) execution_time: AwareDatetime = Field( ..., - description='Indicates the moment PPBC.PowerSequence interruption shall end. When the specified execution time is in the past, execution must start as soon as possible.', + description="Indicates the moment PPBC.PowerSequence interruption shall end. When the specified execution time is in the past, execution must start as soon as possible.", ) abnormal_condition: bool = Field( ..., - description='Indicates if this is an instruction during an abnormal condition', + description="Indicates if this is an instruction during an abnormal condition", ) class OMBCStatus(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['OMBC.Status'] = 'OMBC.Status' + message_type: Literal["OMBC.Status"] = "OMBC.Status" message_id: ID active_operation_mode_id: ID = Field( - ..., description='ID of the active OMBC.OperationMode.' + ..., description="ID of the active OMBC.OperationMode." ) operation_mode_factor: float = Field( ..., - description='The number indicates the factor with which the OMBC.OperationMode should be configured. The factor should be greater than or equal than 0 and less or equal to 1.', + description="The number indicates the factor with which the OMBC.OperationMode should be configured. The factor should be greater than or equal than 0 and less or equal to 1.", ) previous_operation_mode_id: Optional[ID] = Field( None, - description='ID of the OMBC.OperationMode that was previously active. This value shall always be provided, unless the active OMBC.OperationMode is the first OMBC.OperationMode the Resource Manager is aware of.', + description="ID of the OMBC.OperationMode that was previously active. This value shall always be provided, unless the active OMBC.OperationMode is the first OMBC.OperationMode the Resource Manager is aware of.", ) transition_timestamp: Optional[AwareDatetime] = Field( None, - description='Time at which the transition from the previous OMBC.OperationMode to the active OMBC.OperationMode was initiated. This value shall always be provided, unless the active OMBC.OperationMode is the first OMBC.OperationMode the Resource Manager is aware of.', + description="Time at which the transition from the previous OMBC.OperationMode to the active OMBC.OperationMode was initiated. This value shall always be provided, unless the active OMBC.OperationMode is the first OMBC.OperationMode the Resource Manager is aware of.", ) class OMBCInstruction(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['OMBC.Instruction'] = 'OMBC.Instruction' + message_type: Literal["OMBC.Instruction"] = "OMBC.Instruction" message_id: ID id: ID = Field( ..., - description='ID of the instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + description="ID of the instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.", ) execution_time: AwareDatetime = Field( ..., - description='Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.', + description="Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.", ) operation_mode_id: ID = Field( - ..., description='ID of the OMBC.OperationMode that should be activated' + ..., description="ID of the OMBC.OperationMode that should be activated" ) operation_mode_factor: float = Field( ..., - description='The number indicates the factor with which the OMBC.OperationMode should be configured. The factor should be greater than or equal than 0 and less or equal to 1.', + description="The number indicates the factor with which the OMBC.OperationMode should be configured. The factor should be greater than or equal than 0 and less or equal to 1.", ) abnormal_condition: bool = Field( ..., - description='Indicates if this is an instruction during an abnormal condition', + description="Indicates if this is an instruction during an abnormal condition", ) class FRBCActuatorStatus(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['FRBC.ActuatorStatus'] = 'FRBC.ActuatorStatus' + message_type: Literal["FRBC.ActuatorStatus"] = "FRBC.ActuatorStatus" message_id: ID actuator_id: ID = Field( - ..., description='ID of the actuator this messages refers to' + ..., description="ID of the actuator this messages refers to" ) active_operation_mode_id: ID = Field( - ..., description='ID of the FRBC.OperationMode that is presently active.' + ..., description="ID of the FRBC.OperationMode that is presently active." ) operation_mode_factor: float = Field( ..., - description='The number indicates the factor with which the FRBC.OperationMode is configured. The factor should be greater than or equal than 0 and less or equal to 1.', + description="The number indicates the factor with which the FRBC.OperationMode is configured. The factor should be greater than or equal than 0 and less or equal to 1.", ) previous_operation_mode_id: Optional[ID] = Field( None, - description='ID of the FRBC.OperationMode that was active before the present one. This value shall always be provided, unless the active FRBC.OperationMode is the first FRBC.OperationMode the Resource Manager is aware of.', + description="ID of the FRBC.OperationMode that was active before the present one. This value shall always be provided, unless the active FRBC.OperationMode is the first FRBC.OperationMode the Resource Manager is aware of.", ) transition_timestamp: Optional[AwareDatetime] = Field( None, - description='Time at which the transition from the previous FRBC.OperationMode to the active FRBC.OperationMode was initiated. This value shall always be provided, unless the active FRBC.OperationMode is the first FRBC.OperationMode the Resource Manager is aware of.', + description="Time at which the transition from the previous FRBC.OperationMode to the active FRBC.OperationMode was initiated. This value shall always be provided, unless the active FRBC.OperationMode is the first FRBC.OperationMode the Resource Manager is aware of.", ) class FRBCStorageStatus(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['FRBC.StorageStatus'] = 'FRBC.StorageStatus' + message_type: Literal["FRBC.StorageStatus"] = "FRBC.StorageStatus" message_id: ID present_fill_level: float = Field( - ..., description='Present fill level of the Storage' + ..., description="Present fill level of the Storage" ) class FRBCLeakageBehaviour(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['FRBC.LeakageBehaviour'] = 'FRBC.LeakageBehaviour' + message_type: Literal["FRBC.LeakageBehaviour"] = "FRBC.LeakageBehaviour" message_id: ID valid_from: AwareDatetime = Field( ..., - description='Moment this FRBC.LeakageBehaviour starts to be valid. If the FRBC.LeakageBehaviour is immediately valid, the DateTimeStamp should be now or in the past.', + description="Moment this FRBC.LeakageBehaviour starts to be valid. If the FRBC.LeakageBehaviour is immediately valid, the DateTimeStamp should be now or in the past.", ) elements: List[FRBCLeakageBehaviourElement] = Field( ..., - description='List of elements that model the leakage behaviour of the buffer. The fill_level_ranges of the elements must be contiguous.', + description="List of elements that model the leakage behaviour of the buffer. The fill_level_ranges of the elements must be contiguous.", max_length=288, min_length=1, ) @@ -826,46 +826,46 @@ class FRBCLeakageBehaviour(BaseModel): class FRBCInstruction(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['FRBC.Instruction'] = 'FRBC.Instruction' + message_type: Literal["FRBC.Instruction"] = "FRBC.Instruction" message_id: ID id: ID = Field( ..., - description='ID of the instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + description="ID of the instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.", ) actuator_id: ID = Field( - ..., description='ID of the actuator this instruction belongs to.' + ..., description="ID of the actuator this instruction belongs to." ) operation_mode: ID = Field( - ..., description='ID of the FRBC.OperationMode that should be activated.' + ..., description="ID of the FRBC.OperationMode that should be activated." ) operation_mode_factor: float = Field( ..., - description='The number indicates the factor with which the FRBC.OperationMode should be configured. The factor should be greater than or equal to 0 and less or equal to 1.', + description="The number indicates the factor with which the FRBC.OperationMode should be configured. The factor should be greater than or equal to 0 and less or equal to 1.", ) execution_time: AwareDatetime = Field( ..., - description='Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.', + description="Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.", ) abnormal_condition: bool = Field( ..., - description='Indicates if this is an instruction during an abnormal condition.', + description="Indicates if this is an instruction during an abnormal condition.", ) class FRBCUsageForecast(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['FRBC.UsageForecast'] = 'FRBC.UsageForecast' + message_type: Literal["FRBC.UsageForecast"] = "FRBC.UsageForecast" message_id: ID start_time: AwareDatetime = Field( - ..., description='Time at which the FRBC.UsageForecast starts.' + ..., description="Time at which the FRBC.UsageForecast starts." ) elements: List[FRBCUsageForecastElement] = Field( ..., - description='Further elements that model the profile. There shall be at least one element. Elements must be placed in chronological order.', + description="Further elements that model the profile. There shall be at least one element. Elements must be placed in chronological order.", max_length=288, min_length=1, ) @@ -873,16 +873,16 @@ class FRBCUsageForecast(BaseModel): class FRBCFillLevelTargetProfile(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['FRBC.FillLevelTargetProfile'] = 'FRBC.FillLevelTargetProfile' + message_type: Literal["FRBC.FillLevelTargetProfile"] = "FRBC.FillLevelTargetProfile" message_id: ID start_time: AwareDatetime = Field( - ..., description='Time at which the FRBC.FillLevelTargetProfile starts.' + ..., description="Time at which the FRBC.FillLevelTargetProfile starts." ) elements: List[FRBCFillLevelTargetProfileElement] = Field( ..., - description='List of different fill levels that have to be targeted within a given duration. There shall be at least one element. Elements must be placed in chronological order.', + description="List of different fill levels that have to be targeted within a given duration. There shall be at least one element. Elements must be placed in chronological order.", max_length=288, min_length=1, ) @@ -890,71 +890,71 @@ class FRBCFillLevelTargetProfile(BaseModel): class DDBCActuatorStatus(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['DDBC.ActuatorStatus'] = 'DDBC.ActuatorStatus' + message_type: Literal["DDBC.ActuatorStatus"] = "DDBC.ActuatorStatus" message_id: ID actuator_id: ID = Field( - ..., description='ID of the actuator this messages refers to' + ..., description="ID of the actuator this messages refers to" ) active_operation_mode_id: ID = Field( ..., - description='The operation mode that is presently active for this actuator.', + description="The operation mode that is presently active for this actuator.", ) operation_mode_factor: float = Field( ..., - description='The number indicates the factor with which the DDBC.OperationMode is configured. The factor should be greater than or equal to 0 and less or equal to 1.', + description="The number indicates the factor with which the DDBC.OperationMode is configured. The factor should be greater than or equal to 0 and less or equal to 1.", ) previous_operation_mode_id: Optional[ID] = Field( None, - description='ID of the DDBC,OperationMode that was active before the present one. This value shall always be provided, unless the active DDBC.OperationMode is the first DDBC.OperationMode the Resource Manager is aware of.', + description="ID of the DDBC,OperationMode that was active before the present one. This value shall always be provided, unless the active DDBC.OperationMode is the first DDBC.OperationMode the Resource Manager is aware of.", ) transition_timestamp: Optional[AwareDatetime] = Field( None, - description='Time at which the transition from the previous DDBC.OperationMode to the active DDBC.OperationMode was initiated. This value shall always be provided, unless the active DDBC.OperationMode is the first DDBC.OperationMode the Resource Manager is aware of.', + description="Time at which the transition from the previous DDBC.OperationMode to the active DDBC.OperationMode was initiated. This value shall always be provided, unless the active DDBC.OperationMode is the first DDBC.OperationMode the Resource Manager is aware of.", ) class DDBCInstruction(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['DDBC.Instruction'] = 'DDBC.Instruction' + message_type: Literal["DDBC.Instruction"] = "DDBC.Instruction" message_id: ID id: ID = Field( ..., - description='Identifier of this DDBC.Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + description="Identifier of this DDBC.Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.", ) execution_time: AwareDatetime = Field( ..., - description='Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.', + description="Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.", ) abnormal_condition: bool = Field( ..., - description='Indicates if this is an instruction during an abnormal condition', + description="Indicates if this is an instruction during an abnormal condition", ) actuator_id: ID = Field( - ..., description='ID of the actuator this Instruction belongs to.' + ..., description="ID of the actuator this Instruction belongs to." ) - operation_mode_id: ID = Field(..., description='ID of the DDBC.OperationMode') + operation_mode_id: ID = Field(..., description="ID of the DDBC.OperationMode") operation_mode_factor: float = Field( ..., - description='The number indicates the factor with which the OMBC.OperationMode should be configured. The factor should be greater than or equal to 0 and less or equal to 1.', + description="The number indicates the factor with which the OMBC.OperationMode should be configured. The factor should be greater than or equal to 0 and less or equal to 1.", ) class DDBCAverageDemandRateForecast(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['DDBC.AverageDemandRateForecast'] = ( - 'DDBC.AverageDemandRateForecast' + message_type: Literal["DDBC.AverageDemandRateForecast"] = ( + "DDBC.AverageDemandRateForecast" ) message_id: ID - start_time: AwareDatetime = Field(..., description='Start time of the profile.') + start_time: AwareDatetime = Field(..., description="Start time of the profile.") elements: List[DDBCAverageDemandRateForecastElement] = Field( ..., - description='Elements of the profile. Elements must be placed in chronological order.', + description="Elements of the profile. Elements must be placed in chronological order.", max_length=288, min_length=1, ) @@ -962,84 +962,84 @@ class DDBCAverageDemandRateForecast(BaseModel): class PowerValue(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) commodity_quantity: CommodityQuantity = Field( - ..., description='The power quantity the value refers to' + ..., description="The power quantity the value refers to" ) value: float = Field( ..., - description='Power value expressed in the unit associated with the CommodityQuantity', + description="Power value expressed in the unit associated with the CommodityQuantity", ) class PowerForecastValue(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) value_upper_limit: Optional[float] = Field( None, - description='The upper boundary of the range with 100 % certainty the power value is in it', + description="The upper boundary of the range with 100 % certainty the power value is in it", ) value_upper_95PPR: Optional[float] = Field( None, - description='The upper boundary of the range with 95 % certainty the power value is in it', + description="The upper boundary of the range with 95 % certainty the power value is in it", ) value_upper_68PPR: Optional[float] = Field( None, - description='The upper boundary of the range with 68 % certainty the power value is in it', + description="The upper boundary of the range with 68 % certainty the power value is in it", ) - value_expected: float = Field(..., description='The expected power value.') + value_expected: float = Field(..., description="The expected power value.") value_lower_68PPR: Optional[float] = Field( None, - description='The lower boundary of the range with 68 % certainty the power value is in it', + description="The lower boundary of the range with 68 % certainty the power value is in it", ) value_lower_95PPR: Optional[float] = Field( None, - description='The lower boundary of the range with 95 % certainty the power value is in it', + description="The lower boundary of the range with 95 % certainty the power value is in it", ) value_lower_limit: Optional[float] = Field( None, - description='The lower boundary of the range with 100 % certainty the power value is in it', + description="The lower boundary of the range with 100 % certainty the power value is in it", ) commodity_quantity: CommodityQuantity = Field( - ..., description='The power quantity the value refers to' + ..., description="The power quantity the value refers to" ) class PowerRange(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) start_of_range: float = Field( - ..., description='Power value that defines the start of the range.' + ..., description="Power value that defines the start of the range." ) end_of_range: float = Field( - ..., description='Power value that defines the end of the range.' + ..., description="Power value that defines the end of the range." ) commodity_quantity: CommodityQuantity = Field( - ..., description='The power quantity the values refer to' + ..., description="The power quantity the values refer to" ) class Role(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) role: RoleType = Field( - ..., description='Role type of the Resource Manager for the given commodity' + ..., description="Role type of the Resource Manager for the given commodity" ) - commodity: Commodity = Field(..., description='Commodity the role refers to.') + commodity: Commodity = Field(..., description="Commodity the role refers to.") class PowerForecastElement(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - duration: Duration = Field(..., description='Duration of the PowerForecastElement') + duration: Duration = Field(..., description="Duration of the PowerForecastElement") power_values: List[PowerForecastValue] = Field( ..., - description='The values of power that are expected for the given period of time. There shall be at least one PowerForecastValue, and at most one PowerForecastValue per CommodityQuantity.', + description="The values of power that are expected for the given period of time. There shall be at least one PowerForecastValue, and at most one PowerForecastValue per CommodityQuantity.", max_length=10, min_length=1, ) @@ -1047,39 +1047,39 @@ class PowerForecastElement(BaseModel): class PEBCAllowedLimitRange(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) commodity_quantity: CommodityQuantity = Field( - ..., description='Type of power quantity this PEBC.AllowedLimitRange applies to' + ..., description="Type of power quantity this PEBC.AllowedLimitRange applies to" ) limit_type: PEBCPowerEnvelopeLimitType = Field( ..., - description='Indicates if this ranges applies to the upper limit or the lower limit', + description="Indicates if this ranges applies to the upper limit or the lower limit", ) range_boundary: NumberRange = Field( ..., - description='Boundaries of the power range of this PEBC.AllowedLimitRange. The CEM is allowed to choose values within this range for the power envelope for the limit as described in limit_type. The start of the range shall be smaller or equal than the end of the range. ', + description="Boundaries of the power range of this PEBC.AllowedLimitRange. The CEM is allowed to choose values within this range for the power envelope for the limit as described in limit_type. The start of the range shall be smaller or equal than the end of the range. ", ) abnormal_condition_only: bool = Field( ..., - description='Indicates if this PEBC.AllowedLimitRange may only be used during an abnormal condition', + description="Indicates if this PEBC.AllowedLimitRange may only be used during an abnormal condition", ) class PEBCPowerEnvelope(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) id: ID = Field( ..., - description='Identifier of this PEBC.PowerEnvelope. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + description="Identifier of this PEBC.PowerEnvelope. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.", ) commodity_quantity: CommodityQuantity = Field( - ..., description='Type of power quantity this PEBC.PowerEnvelope applies to' + ..., description="Type of power quantity this PEBC.PowerEnvelope applies to" ) power_envelope_elements: List[PEBCPowerEnvelopeElement] = Field( ..., - description='The elements of this PEBC.PowerEnvelope. Shall contain at least one element. Elements must be placed in chronological order.', + description="The elements of this PEBC.PowerEnvelope. Shall contain at least one element. Elements must be placed in chronological order.", max_length=288, min_length=1, ) @@ -1087,14 +1087,14 @@ class PEBCPowerEnvelope(BaseModel): class PPBCPowerSequenceElement(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) duration: Duration = Field( - ..., description='Duration of the PPBC.PowerSequenceElement.' + ..., description="Duration of the PPBC.PowerSequenceElement." ) power_values: List[PowerForecastValue] = Field( ..., - description='The value of power and deviations for the given duration. The array should contain at least one PowerForecastValue and at most one PowerForecastValue per CommodityQuantity.', + description="The value of power and deviations for the given duration. The array should contain at least one PowerForecastValue and at most one PowerForecastValue per CommodityQuantity.", max_length=10, min_length=1, ) @@ -1102,163 +1102,163 @@ class PPBCPowerSequenceElement(BaseModel): class PPBCPowerSequenceContainerStatus(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) power_profile_id: ID = Field( ..., - description='ID of the PPBC.PowerProfileDefinition of which the data element ‘sequence_container_id’ refers to. ', + description="ID of the PPBC.PowerProfileDefinition of which the data element ‘sequence_container_id’ refers to. ", ) sequence_container_id: ID = Field( ..., - description='ID of the PPBC.PowerSequenceContainer this PPBC.PowerSequenceContainerStatus provides information about.', + description="ID of the PPBC.PowerSequenceContainer this PPBC.PowerSequenceContainerStatus provides information about.", ) selected_sequence_id: Optional[ID] = Field( None, - description='ID of selected PPBC.PowerSequence. When no ID is given, no sequence was selected yet.', + description="ID of selected PPBC.PowerSequence. When no ID is given, no sequence was selected yet.", ) progress: Optional[Duration] = Field( None, - description='Time that has passed since the selected sequence has started. A value must be provided, unless no sequence has been selected or the selected sequence hasn’t started yet.', + description="Time that has passed since the selected sequence has started. A value must be provided, unless no sequence has been selected or the selected sequence hasn’t started yet.", ) status: PPBCPowerSequenceStatus = Field( - ..., description='Status of the selected PPBC.PowerSequence' + ..., description="Status of the selected PPBC.PowerSequence" ) class OMBCOperationMode(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) id: ID = Field( ..., - description='ID of the OBMC.OperationMode. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + description="ID of the OBMC.OperationMode. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.", ) diagnostic_label: Optional[str] = Field( None, - description='Human readable name/description of the OMBC.OperationMode. This element is only intended for diagnostic purposes and not for HMI applications.', + description="Human readable name/description of the OMBC.OperationMode. This element is only intended for diagnostic purposes and not for HMI applications.", ) power_ranges: List[PowerRange] = Field( ..., - description='The power produced or consumed by this operation mode. The start of each PowerRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1. In the array there must be at least one PowerRange, and at most one PowerRange per CommodityQuantity.', + description="The power produced or consumed by this operation mode. The start of each PowerRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1. In the array there must be at least one PowerRange, and at most one PowerRange per CommodityQuantity.", max_length=10, min_length=1, ) running_costs: Optional[NumberRange] = Field( None, - description='Additional costs per second (e.g. wear, services) associated with this operation mode in the currency defined by the ResourceManagerDetails , excluding the commodity cost. The range is expressing uncertainty and is not linked to the operation_mode_factor.', + description="Additional costs per second (e.g. wear, services) associated with this operation mode in the currency defined by the ResourceManagerDetails , excluding the commodity cost. The range is expressing uncertainty and is not linked to the operation_mode_factor.", ) abnormal_condition_only: bool = Field( ..., - description='Indicates if this OMBC.OperationMode may only be used during an abnormal condition.', + description="Indicates if this OMBC.OperationMode may only be used during an abnormal condition.", ) class FRBCOperationModeElement(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) fill_level_range: NumberRange = Field( ..., - description='The range of the fill level for which this FRBC.OperationModeElement applies. The start of the NumberRange shall be smaller than the end of the NumberRange.', + description="The range of the fill level for which this FRBC.OperationModeElement applies. The start of the NumberRange shall be smaller than the end of the NumberRange.", ) fill_rate: NumberRange = Field( ..., - description='Indicates the change in fill_level per second. The lower_boundary of the NumberRange is associated with an operation_mode_factor of 0, the upper_boundary is associated with an operation_mode_factor of 1. ', + description="Indicates the change in fill_level per second. The lower_boundary of the NumberRange is associated with an operation_mode_factor of 0, the upper_boundary is associated with an operation_mode_factor of 1. ", ) power_ranges: List[PowerRange] = Field( ..., - description='The power produced or consumed by this operation mode. The start of each PowerRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1. In the array there must be at least one PowerRange, and at most one PowerRange per CommodityQuantity.', + description="The power produced or consumed by this operation mode. The start of each PowerRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1. In the array there must be at least one PowerRange, and at most one PowerRange per CommodityQuantity.", max_length=10, min_length=1, ) running_costs: Optional[NumberRange] = Field( None, - description='Additional costs per second (e.g. wear, services) associated with this operation mode in the currency defined by the ResourceManagerDetails, excluding the commodity cost. The range is expressing uncertainty and is not linked to the operation_mode_factor.', + description="Additional costs per second (e.g. wear, services) associated with this operation mode in the currency defined by the ResourceManagerDetails, excluding the commodity cost. The range is expressing uncertainty and is not linked to the operation_mode_factor.", ) class DDBCOperationMode(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) Id: ID = Field( ..., - description='ID of this operation mode. Must be unique in the scope of the DDBC.ActuatorDescription in which it is used.', + description="ID of this operation mode. Must be unique in the scope of the DDBC.ActuatorDescription in which it is used.", ) diagnostic_label: Optional[str] = Field( None, - description='Human readable name/description of the DDBC.OperationMode. This element is only intended for diagnostic purposes and not for HMI applications.', + description="Human readable name/description of the DDBC.OperationMode. This element is only intended for diagnostic purposes and not for HMI applications.", ) power_ranges: List[PowerRange] = Field( ..., - description='The power produced or consumed by this operation mode. The start of each PowerRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1. In the array there must be at least one PowerRange, and at most one PowerRange per CommodityQuantity.', + description="The power produced or consumed by this operation mode. The start of each PowerRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1. In the array there must be at least one PowerRange, and at most one PowerRange per CommodityQuantity.", max_length=10, min_length=1, ) supply_range: NumberRange = Field( ..., - description='The supply rate this DDBC.OperationMode can deliver for the CEM to match the demand rate. The start of the NumberRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1.', + description="The supply rate this DDBC.OperationMode can deliver for the CEM to match the demand rate. The start of the NumberRange is associated with an operation_mode_factor of 0, the end is associated with an operation_mode_factor of 1.", ) running_costs: Optional[NumberRange] = Field( None, - description='Additional costs per second (e.g. wear, services) associated with this operation mode in the currency defined by the ResourceManagerDetails, excluding the commodity cost. The range is expressing uncertainty and is not linked to the operation_mode_factor.', + description="Additional costs per second (e.g. wear, services) associated with this operation mode in the currency defined by the ResourceManagerDetails, excluding the commodity cost. The range is expressing uncertainty and is not linked to the operation_mode_factor.", ) abnormal_condition_only: bool = Field( ..., - description='Indicates if this DDBC.OperationMode may only be used during an abnormal condition.', + description="Indicates if this DDBC.OperationMode may only be used during an abnormal condition.", ) class ResourceManagerDetails(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['ResourceManagerDetails'] = 'ResourceManagerDetails' + message_type: Literal["ResourceManagerDetails"] = "ResourceManagerDetails" message_id: ID resource_id: ID = Field( ..., - description='Identifier of the Resource Manager. Must be unique within the scope of the CEM.', + description="Identifier of the Resource Manager. Must be unique within the scope of the CEM.", ) - name: Optional[str] = Field(None, description='Human readable name given by user') + name: Optional[str] = Field(None, description="Human readable name given by user") roles: List[Role] = Field( ..., - description='Each Resource Manager provides one or more energy Roles', + description="Each Resource Manager provides one or more energy Roles", max_length=3, min_length=1, ) - manufacturer: Optional[str] = Field(None, description='Name of Manufacturer') + manufacturer: Optional[str] = Field(None, description="Name of Manufacturer") model: Optional[str] = Field( None, - description='Name of the model of the device (provided by the manufacturer)', + description="Name of the model of the device (provided by the manufacturer)", ) serial_number: Optional[str] = Field( - None, description='Serial number of the device (provided by the manufacturer)' + None, description="Serial number of the device (provided by the manufacturer)" ) firmware_version: Optional[str] = Field( None, - description='Version identifier of the firmware used in the device (provided by the manufacturer)', + description="Version identifier of the firmware used in the device (provided by the manufacturer)", ) instruction_processing_delay: Duration = Field( ..., - description='The average time the combination of Resource Manager and HBES/BACS/SASS or (Smart) device needs to process and execute an instruction', + description="The average time the combination of Resource Manager and HBES/BACS/SASS or (Smart) device needs to process and execute an instruction", ) available_control_types: List[ControlType] = Field( ..., - description='The control types supported by this Resource Manager.', + description="The control types supported by this Resource Manager.", max_length=5, min_length=1, ) currency: Optional[Currency] = Field( None, - description='Currency to be used for all information regarding costs. Mandatory if cost information is published.', + description="Currency to be used for all information regarding costs. Mandatory if cost information is published.", ) provides_forecast: bool = Field( ..., - description='Indicates whether the ResourceManager is able to provide PowerForecasts', + description="Indicates whether the ResourceManager is able to provide PowerForecasts", ) provides_power_measurement_types: List[CommodityQuantity] = Field( ..., - description='Array of all CommodityQuantities that this Resource Manager can provide measurements for. ', + description="Array of all CommodityQuantities that this Resource Manager can provide measurements for. ", max_length=10, min_length=1, ) @@ -1266,16 +1266,16 @@ class ResourceManagerDetails(BaseModel): class PowerMeasurement(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['PowerMeasurement'] = 'PowerMeasurement' + message_type: Literal["PowerMeasurement"] = "PowerMeasurement" message_id: ID measurement_timestamp: AwareDatetime = Field( - ..., description='Timestamp when PowerValues were measured.' + ..., description="Timestamp when PowerValues were measured." ) values: List[PowerValue] = Field( ..., - description='Array of measured PowerValues. Must contain at least one item and at most one item per ‘commodity_quantity’ (defined inside the PowerValue).', + description="Array of measured PowerValues. Must contain at least one item and at most one item per ‘commodity_quantity’ (defined inside the PowerValue).", max_length=10, min_length=1, ) @@ -1283,16 +1283,16 @@ class PowerMeasurement(BaseModel): class PowerForecast(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['PowerForecast'] = 'PowerForecast' + message_type: Literal["PowerForecast"] = "PowerForecast" message_id: ID start_time: AwareDatetime = Field( - ..., description='Start time of time period that is covered by the profile.' + ..., description="Start time of time period that is covered by the profile." ) elements: List[PowerForecastElement] = Field( ..., - description='Elements of which this forecast consists. Contains at least one element. Elements must be placed in chronological order.', + description="Elements of which this forecast consists. Contains at least one element. Elements must be placed in chronological order.", max_length=288, min_length=1, ) @@ -1300,27 +1300,27 @@ class PowerForecast(BaseModel): class PEBCPowerConstraints(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['PEBC.PowerConstraints'] = 'PEBC.PowerConstraints' + message_type: Literal["PEBC.PowerConstraints"] = "PEBC.PowerConstraints" message_id: ID id: ID = Field( ..., - description='Identifier of this PEBC.PowerConstraints. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + description="Identifier of this PEBC.PowerConstraints. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.", ) valid_from: AwareDatetime = Field( - ..., description='Moment this PEBC.PowerConstraints start to be valid' + ..., description="Moment this PEBC.PowerConstraints start to be valid" ) valid_until: Optional[AwareDatetime] = Field( None, - description='Moment until this PEBC.PowerConstraints is valid. If valid_until is not present, there is no determined end time of this PEBC.PowerConstraints.', + description="Moment until this PEBC.PowerConstraints is valid. If valid_until is not present, there is no determined end time of this PEBC.PowerConstraints.", ) consequence_type: PEBCPowerEnvelopeConsequenceType = Field( - ..., description='Type of consequence of limiting power' + ..., description="Type of consequence of limiting power" ) allowed_limit_ranges: List[PEBCAllowedLimitRange] = Field( ..., - description='The actual constraints. There shall be at least one PEBC.AllowedLimitRange for the UPPER_LIMIT and at least one AllowedLimitRange for the LOWER_LIMIT. It is allowed to have multiple PEBC.AllowedLimitRange objects with identical CommodityQuantities and LimitTypes.', + description="The actual constraints. There shall be at least one PEBC.AllowedLimitRange for the UPPER_LIMIT and at least one AllowedLimitRange for the LOWER_LIMIT. It is allowed to have multiple PEBC.AllowedLimitRange objects with identical CommodityQuantities and LimitTypes.", max_length=100, min_length=2, ) @@ -1328,29 +1328,29 @@ class PEBCPowerConstraints(BaseModel): class PEBCInstruction(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['PEBC.Instruction'] = 'PEBC.Instruction' + message_type: Literal["PEBC.Instruction"] = "PEBC.Instruction" message_id: ID id: ID = Field( ..., - description='Identifier of this PEBC.Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + description="Identifier of this PEBC.Instruction. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.", ) execution_time: AwareDatetime = Field( ..., - description='Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.', + description="Indicates the moment the execution of the instruction shall start. When the specified execution time is in the past, execution must start as soon as possible.", ) abnormal_condition: bool = Field( ..., - description='Indicates if this is an instruction during an abnormal condition.', + description="Indicates if this is an instruction during an abnormal condition.", ) power_constraints_id: ID = Field( ..., - description='Identifier of the PEBC.PowerConstraints this PEBC.Instruction was based on.', + description="Identifier of the PEBC.PowerConstraints this PEBC.Instruction was based on.", ) power_envelopes: List[PEBCPowerEnvelope] = Field( ..., - description='The PEBC.PowerEnvelope(s) that should be followed by the Resource Manager. There shall be at least one PEBC.PowerEnvelope, but at most one PEBC.PowerEnvelope for each CommodityQuantity.', + description="The PEBC.PowerEnvelope(s) that should be followed by the Resource Manager. There shall be at least one PEBC.PowerEnvelope, but at most one PEBC.PowerEnvelope for each CommodityQuantity.", max_length=10, min_length=1, ) @@ -1358,13 +1358,13 @@ class PEBCInstruction(BaseModel): class PPBCPowerProfileStatus(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['PPBC.PowerProfileStatus'] = 'PPBC.PowerProfileStatus' + message_type: Literal["PPBC.PowerProfileStatus"] = "PPBC.PowerProfileStatus" message_id: ID sequence_container_status: List[PPBCPowerSequenceContainerStatus] = Field( ..., - description='Array with status information for all PPBC.PowerSequenceContainers in the PPBC.PowerProfileDefinition.', + description="Array with status information for all PPBC.PowerSequenceContainers in the PPBC.PowerProfileDefinition.", max_length=1000, min_length=1, ) @@ -1372,29 +1372,29 @@ class PPBCPowerProfileStatus(BaseModel): class OMBCSystemDescription(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['OMBC.SystemDescription'] = 'OMBC.SystemDescription' + message_type: Literal["OMBC.SystemDescription"] = "OMBC.SystemDescription" message_id: ID valid_from: AwareDatetime = Field( ..., - description='Moment this OMBC.SystemDescription starts to be valid. If the system description is immediately valid, the DateTimeStamp should be now or in the past.', + description="Moment this OMBC.SystemDescription starts to be valid. If the system description is immediately valid, the DateTimeStamp should be now or in the past.", ) operation_modes: List[OMBCOperationMode] = Field( ..., - description='OMBC.OperationModes available for the CEM in order to coordinate the device behaviour.', + description="OMBC.OperationModes available for the CEM in order to coordinate the device behaviour.", max_length=100, min_length=1, ) transitions: List[Transition] = Field( ..., - description='Possible transitions to switch from one OMBC.OperationMode to another.', + description="Possible transitions to switch from one OMBC.OperationMode to another.", max_length=1000, min_length=0, ) timers: List[Timer] = Field( ..., - description='Timers that control when certain transitions can be made.', + description="Timers that control when certain transitions can be made.", max_length=1000, min_length=0, ) @@ -1402,89 +1402,89 @@ class OMBCSystemDescription(BaseModel): class PPBCPowerSequence(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) id: ID = Field( ..., - description='ID of the PPBC.PowerSequence. Must be unique in the scope of the PPBC.PowerSequnceContainer in which it is used.', + description="ID of the PPBC.PowerSequence. Must be unique in the scope of the PPBC.PowerSequnceContainer in which it is used.", ) elements: List[PPBCPowerSequenceElement] = Field( ..., - description='List of PPBC.PowerSequenceElements. Shall contain at least one element. Elements must be placed in chronological order.', + description="List of PPBC.PowerSequenceElements. Shall contain at least one element. Elements must be placed in chronological order.", max_length=288, min_length=1, ) is_interruptible: bool = Field( ..., - description='Indicates whether the option of pausing a sequence is available.', + description="Indicates whether the option of pausing a sequence is available.", ) max_pause_before: Optional[Duration] = Field( None, - description='The maximum duration for which a device can be paused between the end of the previous running sequence and the start of this one', + description="The maximum duration for which a device can be paused between the end of the previous running sequence and the start of this one", ) abnormal_condition_only: bool = Field( ..., - description='Indicates if this PPBC.PowerSequence may only be used during an abnormal condition', + description="Indicates if this PPBC.PowerSequence may only be used during an abnormal condition", ) class FRBCOperationMode(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) id: ID = Field( ..., - description='ID of the FRBC.OperationMode. Must be unique in the scope of the FRBC.ActuatorDescription in which it is used.', + description="ID of the FRBC.OperationMode. Must be unique in the scope of the FRBC.ActuatorDescription in which it is used.", ) diagnostic_label: Optional[str] = Field( None, - description='Human readable name/description of the FRBC.OperationMode. This element is only intended for diagnostic purposes and not for HMI applications.', + description="Human readable name/description of the FRBC.OperationMode. This element is only intended for diagnostic purposes and not for HMI applications.", ) elements: List[FRBCOperationModeElement] = Field( ..., - description='List of FRBC.OperationModeElements, which describe the properties of this FRBC.OperationMode depending on the fill_level. The fill_level_ranges of the items in the Array must be contiguous.', + description="List of FRBC.OperationModeElements, which describe the properties of this FRBC.OperationMode depending on the fill_level. The fill_level_ranges of the items in the Array must be contiguous.", max_length=100, min_length=1, ) abnormal_condition_only: bool = Field( ..., - description='Indicates if this FRBC.OperationMode may only be used during an abnormal condition', + description="Indicates if this FRBC.OperationMode may only be used during an abnormal condition", ) class DDBCActuatorDescription(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) id: ID = Field( ..., - description='ID of this DDBC.ActuatorDescription. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + description="ID of this DDBC.ActuatorDescription. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.", ) diagnostic_label: Optional[str] = Field( None, - description='Human readable name/description of the actuator. This element is only intended for diagnostic purposes and not for HMI applications.', + description="Human readable name/description of the actuator. This element is only intended for diagnostic purposes and not for HMI applications.", ) supported_commodites: List[Commodity] = Field( ..., - description='Commodities supported by the operation modes of this actuator. There shall be at least one commodity', + description="Commodities supported by the operation modes of this actuator. There shall be at least one commodity", max_length=4, min_length=1, ) operation_modes: List[DDBCOperationMode] = Field( ..., - description='List of all Operation Modes that are available for this actuator. There shall be at least one DDBC.OperationMode.', + description="List of all Operation Modes that are available for this actuator. There shall be at least one DDBC.OperationMode.", max_length=100, min_length=1, ) transitions: List[Transition] = Field( ..., - description='List of Transitions between Operation Modes. Shall contain at least one Transition.', + description="List of Transitions between Operation Modes. Shall contain at least one Transition.", max_length=1000, min_length=0, ) timers: List[Timer] = Field( ..., - description='List of Timers associated with Transitions for this Actuator. Can be empty.', + description="List of Timers associated with Transitions for this Actuator. Can be empty.", max_length=1000, min_length=0, ) @@ -1492,40 +1492,40 @@ class DDBCActuatorDescription(BaseModel): class DDBCSystemDescription(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['DDBC.SystemDescription'] = 'DDBC.SystemDescription' + message_type: Literal["DDBC.SystemDescription"] = "DDBC.SystemDescription" message_id: ID valid_from: AwareDatetime = Field( ..., - description='Moment this DDBC.SystemDescription starts to be valid. If the system description is immediately valid, the DateTimeStamp should be now or in the past.', + description="Moment this DDBC.SystemDescription starts to be valid. If the system description is immediately valid, the DateTimeStamp should be now or in the past.", ) actuators: List[DDBCActuatorDescription] = Field( ..., - description='List of all available actuators in the system. Must contain at least one DDBC.ActuatorAggregated.', + description="List of all available actuators in the system. Must contain at least one DDBC.ActuatorAggregated.", max_length=10, min_length=1, ) present_demand_rate: NumberRange = Field( - ..., description='Present demand rate that needs to be satisfied by the system' + ..., description="Present demand rate that needs to be satisfied by the system" ) provides_average_demand_rate_forecast: bool = Field( ..., - description='Indicates whether the Resource Manager could provide a demand rate forecast through the DDBC.AverageDemandRateForecast.', + description="Indicates whether the Resource Manager could provide a demand rate forecast through the DDBC.AverageDemandRateForecast.", ) class PPBCPowerSequenceContainer(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) id: ID = Field( ..., - description='ID of the PPBC.PowerSequenceContainer. Must be unique in the scope of the PPBC.PowerProfileDefinition in which it is used.', + description="ID of the PPBC.PowerSequenceContainer. Must be unique in the scope of the PPBC.PowerProfileDefinition in which it is used.", ) power_sequences: List[PPBCPowerSequence] = Field( ..., - description='List of alternative Sequences where one could be chosen by the CEM', + description="List of alternative Sequences where one could be chosen by the CEM", max_length=288, min_length=1, ) @@ -1533,37 +1533,37 @@ class PPBCPowerSequenceContainer(BaseModel): class FRBCActuatorDescription(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) id: ID = Field( ..., - description='ID of the Actuator. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + description="ID of the Actuator. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.", ) diagnostic_label: Optional[str] = Field( None, - description='Human readable name/description for the actuator. This element is only intended for diagnostic purposes and not for HMI applications.', + description="Human readable name/description for the actuator. This element is only intended for diagnostic purposes and not for HMI applications.", ) supported_commodities: List[Commodity] = Field( ..., - description='List of all supported Commodities.', + description="List of all supported Commodities.", max_length=4, min_length=1, ) operation_modes: List[FRBCOperationMode] = Field( ..., - description='Provided FRBC.OperationModes associated with this actuator', + description="Provided FRBC.OperationModes associated with this actuator", max_length=100, min_length=1, ) transitions: List[Transition] = Field( ..., - description='Possible transitions between FRBC.OperationModes associated with this actuator.', + description="Possible transitions between FRBC.OperationModes associated with this actuator.", max_length=1000, min_length=0, ) timers: List[Timer] = Field( ..., - description='List of Timers associated with this actuator', + description="List of Timers associated with this actuator", max_length=1000, min_length=0, ) @@ -1571,25 +1571,25 @@ class FRBCActuatorDescription(BaseModel): class PPBCPowerProfileDefinition(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['PPBC.PowerProfileDefinition'] = 'PPBC.PowerProfileDefinition' + message_type: Literal["PPBC.PowerProfileDefinition"] = "PPBC.PowerProfileDefinition" message_id: ID id: ID = Field( ..., - description='ID of the PPBC.PowerProfileDefinition. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.', + description="ID of the PPBC.PowerProfileDefinition. Must be unique in the scope of the Resource Manager, for at least the duration of the session between Resource Manager and CEM.", ) start_time: AwareDatetime = Field( ..., - description='Indicates the first possible time the first PPBC.PowerSequence could start', + description="Indicates the first possible time the first PPBC.PowerSequence could start", ) end_time: AwareDatetime = Field( ..., - description='Indicates when the last PPBC.PowerSequence shall be finished at the latest', + description="Indicates when the last PPBC.PowerSequence shall be finished at the latest", ) power_sequences_containers: List[PPBCPowerSequenceContainer] = Field( ..., - description='The PPBC.PowerSequenceContainers that make up this PPBC.PowerProfileDefinition. There shall be at least one PPBC.PowerSequenceContainer that includes at least one PPBC.PowerSequence. PPBC.PowerSequenceContainers must be placed in chronological order.', + description="The PPBC.PowerSequenceContainers that make up this PPBC.PowerProfileDefinition. There shall be at least one PPBC.PowerSequenceContainer that includes at least one PPBC.PowerSequence. PPBC.PowerSequenceContainers must be placed in chronological order.", max_length=1000, min_length=1, ) @@ -1597,15 +1597,15 @@ class PPBCPowerProfileDefinition(BaseModel): class FRBCSystemDescription(BaseModel): model_config = ConfigDict( - extra='forbid', + extra="forbid", ) - message_type: Literal['FRBC.SystemDescription'] = 'FRBC.SystemDescription' + message_type: Literal["FRBC.SystemDescription"] = "FRBC.SystemDescription" message_id: ID valid_from: AwareDatetime = Field( ..., - description='Moment this FRBC.SystemDescription starts to be valid. If the system description is immediately valid, the DateTimeStamp should be now or in the past.', + description="Moment this FRBC.SystemDescription starts to be valid. If the system description is immediately valid, the DateTimeStamp should be now or in the past.", ) actuators: List[FRBCActuatorDescription] = Field( - ..., description='Details of all Actuators.', max_length=10, min_length=1 + ..., description="Details of all Actuators.", max_length=10, min_length=1 ) - storage: FRBCStorageDescription = Field(..., description='Details of the storage.') + storage: FRBCStorageDescription = Field(..., description="Details of the storage.") diff --git a/src/s2python/message.py b/src/s2python/message.py index aafc009..a3c9851 100644 --- a/src/s2python/message.py +++ b/src/s2python/message.py @@ -8,11 +8,18 @@ FRBCStorageStatus, FRBCSystemDescription, FRBCTimerStatus, - FRBCUsageForecast + FRBCUsageForecast, ) from s2python.ppbc import ( PPBCScheduleInstruction, ) +from s2python.ombc import ( + OMBCInstruction, + OMBCOperationMode, + OMBCTimerStatus, + OMBCStatus, + OMBCSystemDescription, +) from s2python.common import ( Handshake, @@ -24,7 +31,7 @@ ResourceManagerDetails, RevokeObject, SelectControlType, - SessionRequest + SessionRequest, ) S2Message = Union[ @@ -37,6 +44,11 @@ FRBCTimerStatus, FRBCUsageForecast, PPBCScheduleInstruction, + OMBCInstruction, + OMBCOperationMode, + OMBCTimerStatus, + OMBCStatus, + OMBCSystemDescription, Handshake, HandshakeResponse, InstructionStatusUpdate, diff --git a/src/s2python/ppbc/ppbc_end_interruption_instruction.py b/src/s2python/ppbc/ppbc_end_interruption_instruction.py index 2b098f1..786a447 100644 --- a/src/s2python/ppbc/ppbc_end_interruption_instruction.py +++ b/src/s2python/ppbc/ppbc_end_interruption_instruction.py @@ -12,7 +12,8 @@ @catch_and_convert_exceptions class PPBCEndInterruptionInstruction( - GenPPBCEndInterruptionInstruction, S2MessageComponent["PPBCEndInterruptionInstruction"] + GenPPBCEndInterruptionInstruction, + S2MessageComponent["PPBCEndInterruptionInstruction"], ): model_config = GenPPBCEndInterruptionInstruction.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/ppbc/ppbc_power_sequence_container_status.py b/src/s2python/ppbc/ppbc_power_sequence_container_status.py index 19e897d..43fe112 100644 --- a/src/s2python/ppbc/ppbc_power_sequence_container_status.py +++ b/src/s2python/ppbc/ppbc_power_sequence_container_status.py @@ -13,7 +13,8 @@ @catch_and_convert_exceptions class PPBCPowerSequenceContainerStatus( - GenPPBCPowerSequenceContainerStatus, S2MessageComponent["PPBCPowerSequenceContainerStatus"] + GenPPBCPowerSequenceContainerStatus, + S2MessageComponent["PPBCPowerSequenceContainerStatus"], ): model_config = GenPPBCPowerSequenceContainerStatus.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/ppbc/ppbc_start_interruption_instruction.py b/src/s2python/ppbc/ppbc_start_interruption_instruction.py index 0924021..7305663 100644 --- a/src/s2python/ppbc/ppbc_start_interruption_instruction.py +++ b/src/s2python/ppbc/ppbc_start_interruption_instruction.py @@ -12,7 +12,8 @@ @catch_and_convert_exceptions class PPBCStartInterruptionInstruction( - GenPPBCStartInterruptionInstruction, S2MessageComponent["PPBCStartInterruptionInstruction"] + GenPPBCStartInterruptionInstruction, + S2MessageComponent["PPBCStartInterruptionInstruction"], ): model_config = GenPPBCStartInterruptionInstruction.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/s2_connection.py b/src/s2python/s2_connection.py index 5864203..d2311ed 100644 --- a/src/s2python/s2_connection.py +++ b/src/s2python/s2_connection.py @@ -8,7 +8,10 @@ from typing import Optional, List, Type, Dict, Callable, Awaitable, Union import websockets -from websockets.asyncio.client import ClientConnection as WSConnection, connect as ws_connect +from websockets.asyncio.client import ( + ClientConnection as WSConnection, + connect as ws_connect, +) from s2python.common import ( ReceptionStatusValues, @@ -55,7 +58,8 @@ def to_resource_manager_details( ) -> ResourceManagerDetails: return ResourceManagerDetails( available_control_types=[ - control_type.get_protocol_control_type() for control_type in control_types + control_type.get_protocol_control_type() + for control_type in control_types ], currency=self.currency, firmware_version=self.firmware_version, @@ -170,7 +174,9 @@ def do_message() -> None: type(msg), ) - def register_handler(self, msg_type: Type[S2Message], handler: S2MessageHandler) -> None: + def register_handler( + self, msg_type: Type[S2Message], handler: S2MessageHandler + ) -> None: """Register a coroutine function or a normal function as the handler for a specific S2 message type. :param msg_type: The S2 message type to attach the handler to. @@ -222,9 +228,13 @@ def __init__( # pylint: disable=too-many-arguments self.role = role self.asset_details = asset_details - self._handlers.register_handler(SelectControlType, self.handle_select_control_type_as_rm) + self._handlers.register_handler( + SelectControlType, self.handle_select_control_type_as_rm + ) self._handlers.register_handler(Handshake, self.handle_handshake) - self._handlers.register_handler(HandshakeResponse, self.handle_handshake_response_as_rm) + self._handlers.register_handler( + HandshakeResponse, self.handle_handshake_response_as_rm + ) def start_as_rm(self) -> None: self._run_eventloop(self._run_as_rm()) @@ -304,7 +314,10 @@ async def wait_till_connection_restart() -> None: await task except asyncio.CancelledError: pass - except (websockets.ConnectionClosedError, websockets.ConnectionClosedOK): + except ( + websockets.ConnectionClosedError, + websockets.ConnectionClosedOK, + ): logger.info("The other party closed the websocket connection.") for task in pending: @@ -326,10 +339,14 @@ async def _connect_ws(self) -> None: async def _connect_as_rm(self) -> None: await self.send_msg_and_await_reception_status_async( Handshake( - message_id=uuid.uuid4(), role=self.role, supported_protocol_versions=[S2_VERSION] + message_id=uuid.uuid4(), + role=self.role, + supported_protocol_versions=[S2_VERSION], ) ) - logger.debug("Send handshake to CEM. Expecting Handshake and HandshakeResponse from CEM.") + logger.debug( + "Send handshake to CEM. Expecting Handshake and HandshakeResponse from CEM." + ) await self._handle_received_messages() @@ -338,7 +355,8 @@ async def handle_handshake( ) -> None: if not isinstance(message, Handshake): logger.error( - "Handler for Handshake received a message of the wrong type: %s", type(message) + "Handler for Handshake received a message of the wrong type: %s", + type(message), ) return @@ -361,7 +379,9 @@ async def handle_handshake_response_as_rm( logger.debug("Received HandshakeResponse %s", message.to_json()) - logger.debug("CEM selected to use version %s", message.selected_protocol_version) + logger.debug( + "CEM selected to use version %s", message.selected_protocol_version + ) await send_okay logger.debug("Handshake complete. Sending first ResourceManagerDetails.") @@ -381,22 +401,29 @@ async def handle_select_control_type_as_rm( await send_okay - logger.debug("CEM selected control type %s. Activating control type.", message.control_type) + logger.debug( + "CEM selected control type %s. Activating control type.", + message.control_type, + ) control_types_by_protocol_name = { c.get_protocol_control_type(): c for c in self.control_types } - selected_control_type: Optional[S2ControlType] = control_types_by_protocol_name.get( - message.control_type + selected_control_type: Optional[S2ControlType] = ( + control_types_by_protocol_name.get(message.control_type) ) if self._current_control_type is not None: - await self._eventloop.run_in_executor(None, self._current_control_type.deactivate, self) + await self._eventloop.run_in_executor( + None, self._current_control_type.deactivate, self + ) self._current_control_type = selected_control_type if self._current_control_type is not None: - await self._eventloop.run_in_executor(None, self._current_control_type.activate, self) + await self._eventloop.run_in_executor( + None, self._current_control_type.activate, self + ) self._current_control_type.register_handlers(self._handlers) async def _receive_messages(self) -> None: @@ -465,9 +492,14 @@ async def _send_and_forget(self, s2_msg: S2Message) -> None: self._restart_connection_event.set() async def respond_with_reception_status( - self, subject_message_id: str, status: ReceptionStatusValues, diagnostic_label: str + self, + subject_message_id: str, + status: ReceptionStatusValues, + diagnostic_label: str, ) -> None: - logger.debug("Responding to message %s with status %s", subject_message_id, status) + logger.debug( + "Responding to message %s with status %s", subject_message_id, status + ) await self._send_and_forget( ReceptionStatus( subject_message_id=subject_message_id, @@ -477,15 +509,23 @@ async def respond_with_reception_status( ) def respond_with_reception_status_sync( - self, subject_message_id: str, status: ReceptionStatusValues, diagnostic_label: str + self, + subject_message_id: str, + status: ReceptionStatusValues, + diagnostic_label: str, ) -> None: asyncio.run_coroutine_threadsafe( - self.respond_with_reception_status(subject_message_id, status, diagnostic_label), + self.respond_with_reception_status( + subject_message_id, status, diagnostic_label + ), self._eventloop, ).result() async def send_msg_and_await_reception_status_async( - self, s2_msg: S2Message, timeout_reception_status: float = 5.0, raise_on_error: bool = True + self, + s2_msg: S2Message, + timeout_reception_status: float = 5.0, + raise_on_error: bool = True, ) -> ReceptionStatus: await self._send_and_forget(s2_msg) logger.debug( @@ -506,12 +546,17 @@ async def send_msg_and_await_reception_status_async( raise if reception_status.status != ReceptionStatusValues.OK and raise_on_error: - raise RuntimeError(f"ReceptionStatus was not OK but rather {reception_status.status}") + raise RuntimeError( + f"ReceptionStatus was not OK but rather {reception_status.status}" + ) return reception_status def send_msg_and_await_reception_status_sync( - self, s2_msg: S2Message, timeout_reception_status: float = 5.0, raise_on_error: bool = True + self, + s2_msg: S2Message, + timeout_reception_status: float = 5.0, + raise_on_error: bool = True, ) -> ReceptionStatus: return asyncio.run_coroutine_threadsafe( self.send_msg_and_await_reception_status_async( diff --git a/src/s2python/s2_control_type.py b/src/s2python/s2_control_type.py index d503a69..78c0685 100644 --- a/src/s2python/s2_control_type.py +++ b/src/s2python/s2_control_type.py @@ -66,6 +66,7 @@ def activate(self, conn: "S2Connection") -> None: def deactivate(self, conn: "S2Connection") -> None: """Overwrite with the actual deactivation logic of your Resource Manager for this particular control type.""" + class OMBCControlType(S2ControlType): def get_protocol_control_type(self) -> ProtocolControlType: return ProtocolControlType.OPERATION_MODE_BASED_CONTROL @@ -86,6 +87,7 @@ def activate(self, conn: "S2Connection") -> None: def deactivate(self, conn: "S2Connection") -> None: """Overwrite with the actual deactivation logic of your Resource Manager for this particular control type.""" + class NoControlControlType(S2ControlType): def get_protocol_control_type(self) -> ProtocolControlType: return ProtocolControlType.NOT_CONTROLABLE diff --git a/src/s2python/s2_validation_error.py b/src/s2python/s2_validation_error.py index 8ab7664..dc43419 100644 --- a/src/s2python/s2_validation_error.py +++ b/src/s2python/s2_validation_error.py @@ -10,4 +10,6 @@ class S2ValidationError(Exception): class_: Optional[Type] obj: object msg: str - pydantic_validation_error: Union[ValidationErrorV1, ValidationError, TypeError, None] + pydantic_validation_error: Union[ + ValidationErrorV1, ValidationError, TypeError, None + ] diff --git a/src/s2python/validate_values_mixin.py b/src/s2python/validate_values_mixin.py index cc9c6fd..05f09ab 100644 --- a/src/s2python/validate_values_mixin.py +++ b/src/s2python/validate_values_mixin.py @@ -1,7 +1,20 @@ -from typing import TypeVar, Generic, Type, Callable, Any, Union, AbstractSet, Mapping, List, Dict +from typing import ( + TypeVar, + Generic, + Type, + Callable, + Any, + Union, + AbstractSet, + Mapping, + List, + Dict, +) from pydantic import BaseModel, ValidationError # pylint: disable=no-name-in-module -from pydantic.v1.error_wrappers import display_errors # pylint: disable=no-name-in-module +from pydantic.v1.error_wrappers import ( + display_errors, +) # pylint: disable=no-name-in-module from s2python.s2_validation_error import S2ValidationError @@ -59,7 +72,9 @@ def inner(*args: List[Any], **kwargs: Dict[str, Any]) -> Any: return inner -def catch_and_convert_exceptions(input_class: Type[S2MessageComponent[B_co]]) -> Type[S2MessageComponent[B_co]]: +def catch_and_convert_exceptions( + input_class: Type[S2MessageComponent[B_co]], +) -> Type[S2MessageComponent[B_co]]: input_class.__init__ = convert_to_s2exception(input_class.__init__) # type: ignore[method-assign] input_class.__setattr__ = convert_to_s2exception(input_class.__setattr__) # type: ignore[method-assign] input_class.model_validate_json = convert_to_s2exception( # type: ignore[method-assign] diff --git a/tests/unit/common/handshake_test.py b/tests/unit/common/handshake_test.py index e4d78e9..715e360 100644 --- a/tests/unit/common/handshake_test.py +++ b/tests/unit/common/handshake_test.py @@ -17,7 +17,9 @@ def test__from_json__happy_path(self): handshake = Handshake.from_json(json_str) # Assert - self.assertEqual(handshake.message_id, uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced3")) + self.assertEqual( + handshake.message_id, uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced3") + ) self.assertEqual(handshake.role, EnergyManagementRole.RM) self.assertEqual(handshake.supported_protocol_versions, ["v1", "v2"]) diff --git a/tests/unit/common/instruction_status_update_test.py b/tests/unit/common/instruction_status_update_test.py index ef9283a..91b81f2 100644 --- a/tests/unit/common/instruction_status_update_test.py +++ b/tests/unit/common/instruction_status_update_test.py @@ -30,7 +30,9 @@ def test__from_json__happy_path(self): instruction_status_update.instruction_id, uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced4"), ) - self.assertEqual(instruction_status_update.status_type, InstructionStatus.SUCCEEDED) + self.assertEqual( + instruction_status_update.status_type, InstructionStatus.SUCCEEDED + ) self.assertEqual( instruction_status_update.timestamp, datetime(2023, 8, 2, 12, 48, 42, tzinfo=offset(timedelta(hours=1))), @@ -42,7 +44,9 @@ def test__to_json__happy_path(self): message_id=uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced3"), instruction_id=uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced4"), status_type=InstructionStatus.SUCCEEDED, - timestamp=timezone("Europe/Amsterdam").localize(datetime(2023, 8, 2, 12, 48, 42)), + timestamp=timezone("Europe/Amsterdam").localize( + datetime(2023, 8, 2, 12, 48, 42) + ), ) # Act diff --git a/tests/unit/common/number_range_test.py b/tests/unit/common/number_range_test.py index eedb729..e597113 100644 --- a/tests/unit/common/number_range_test.py +++ b/tests/unit/common/number_range_test.py @@ -27,7 +27,9 @@ def test__from_json__happy_path_equals(self): number_range = NumberRange.from_json(json_str) # Assert - self.assertEqual(number_range, NumberRange(start_of_range=4.0, end_of_range=5.0)) + self.assertEqual( + number_range, NumberRange(start_of_range=4.0, end_of_range=5.0) + ) def test__from_json__format_validation_error(self): # Arrange @@ -45,7 +47,9 @@ def test__from_json__end_of_range_smaller_than_start(self): number_range = NumberRange.from_json(json_str) # Assert - self.assertEqual(number_range, NumberRange(start_of_range=6.0, end_of_range=5.0)) + self.assertEqual( + number_range, NumberRange(start_of_range=6.0, end_of_range=5.0) + ) def test__to_json__happy_path(self): # Arrange diff --git a/tests/unit/common/power_forecast_element_test.py b/tests/unit/common/power_forecast_element_test.py index 116c3b9..8a039e4 100644 --- a/tests/unit/common/power_forecast_element_test.py +++ b/tests/unit/common/power_forecast_element_test.py @@ -54,6 +54,8 @@ def test__to_json__happy_path(self): # Assert expected_json = { "duration": 4000, - "power_values": [{"commodity_quantity": "NATURAL_GAS.FLOW_RATE", "value_expected": 500.2}], + "power_values": [ + {"commodity_quantity": "NATURAL_GAS.FLOW_RATE", "value_expected": 500.2} + ], } self.assertEqual(json.loads(json_str), expected_json) diff --git a/tests/unit/common/power_forecast_value_test.py b/tests/unit/common/power_forecast_value_test.py index d7c37e4..682d16c 100644 --- a/tests/unit/common/power_forecast_value_test.py +++ b/tests/unit/common/power_forecast_value_test.py @@ -17,10 +17,14 @@ def test__from_json__happy_path(self): "value_upper_limit": 600}""" # Act - power_forecast_value: PowerForecastValue = PowerForecastValue.from_json(json_str) + power_forecast_value: PowerForecastValue = PowerForecastValue.from_json( + json_str + ) # Assert - self.assertEqual(power_forecast_value.commodity_quantity, CommodityQuantity.HEAT_FLOW_RATE) + self.assertEqual( + power_forecast_value.commodity_quantity, CommodityQuantity.HEAT_FLOW_RATE + ) self.assertEqual(power_forecast_value.value_lower_limit, 450.3) self.assertEqual(power_forecast_value.value_lower_95PPR, 470.4) self.assertEqual(power_forecast_value.value_lower_68PPR, 480.3) @@ -68,5 +72,8 @@ def test__to_json__only_value_expected(self): json_str = power_forecast_value.to_json() # Assert - expected_json = {"commodity_quantity": "HEAT.TEMPERATURE", "value_expected": 500.2} + expected_json = { + "commodity_quantity": "HEAT.TEMPERATURE", + "value_expected": 500.2, + } self.assertEqual(json.loads(json_str), expected_json) diff --git a/tests/unit/common/power_measurement_test.py b/tests/unit/common/power_measurement_test.py index 037fa07..a8c555c 100644 --- a/tests/unit/common/power_measurement_test.py +++ b/tests/unit/common/power_measurement_test.py @@ -30,15 +30,25 @@ def test__from_json__happy_path(self): ) self.assertEqual( power_measurement.values, - [PowerValue(commodity_quantity=CommodityQuantity.OIL_FLOW_RATE, value=42.42)], + [ + PowerValue( + commodity_quantity=CommodityQuantity.OIL_FLOW_RATE, value=42.42 + ) + ], ) def test__to_json__happy_path(self): # Arrange power_measurement = PowerMeasurement( - values=[PowerValue(commodity_quantity=CommodityQuantity.OIL_FLOW_RATE, value=42.42)], + values=[ + PowerValue( + commodity_quantity=CommodityQuantity.OIL_FLOW_RATE, value=42.42 + ) + ], message_id=uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced8"), - measurement_timestamp=datetime(2023, 8, 3, 12, 48, 42, tzinfo=offset(timedelta(hours=1))), + measurement_timestamp=datetime( + 2023, 8, 3, 12, 48, 42, tzinfo=offset(timedelta(hours=1)) + ), ) # Act diff --git a/tests/unit/common/transition_test.py b/tests/unit/common/transition_test.py index 0c9dc9e..3e0a3a5 100644 --- a/tests/unit/common/transition_test.py +++ b/tests/unit/common/transition_test.py @@ -25,9 +25,15 @@ def test__from_json__happy_path_full(self): transition: Transition = Transition.from_json(json_str) # Assert - self.assertEqual(transition.id, uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced3")) - self.assertEqual(transition.from_, uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced2")) - self.assertEqual(transition.to, uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced1")) + self.assertEqual( + transition.id, uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced3") + ) + self.assertEqual( + transition.from_, uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced2") + ) + self.assertEqual( + transition.to, uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced1") + ) self.assertEqual( transition.start_timers, [ @@ -41,7 +47,9 @@ def test__from_json__happy_path_full(self): ) self.assertEqual(transition.transition_costs, 4.3) assert transition.transition_duration is not None - self.assertEqual(transition.transition_duration.to_timedelta(), timedelta(seconds=1.5)) + self.assertEqual( + transition.transition_duration.to_timedelta(), timedelta(seconds=1.5) + ) self.assertEqual(transition.abnormal_condition_only, False) def test__from_json__happy_path_min(self): @@ -59,9 +67,15 @@ def test__from_json__happy_path_min(self): transition: Transition = Transition.from_json(json_str) # Assert - self.assertEqual(transition.id, uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced3")) - self.assertEqual(transition.from_, uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced2")) - self.assertEqual(transition.to, uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced1")) + self.assertEqual( + transition.id, uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced3") + ) + self.assertEqual( + transition.from_, uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced2") + ) + self.assertEqual( + transition.to, uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced1") + ) self.assertEqual(transition.start_timers, []) self.assertEqual(transition.blocking_timers, []) self.assertEqual(transition.transition_costs, None) @@ -106,7 +120,9 @@ def test__to_json__happy_path(self): "to": uuid.UUID("2bdec96b-be3b-4ba9-afa0-c4a0632cced1"), "start_timers": [], "blocking_timers": [], - "transition_duration": Duration.from_timedelta(timedelta(minutes=1, seconds=1)), + "transition_duration": Duration.from_timedelta( + timedelta(minutes=1, seconds=1) + ), "abnormal_condition_only": False, } ) diff --git a/tests/unit/frbc/frbc_actuator_status_test.py b/tests/unit/frbc/frbc_actuator_status_test.py index b3bb5c8..2538381 100644 --- a/tests/unit/frbc/frbc_actuator_status_test.py +++ b/tests/unit/frbc/frbc_actuator_status_test.py @@ -65,7 +65,9 @@ def test__to_json__happy_path_full(self): message_id=uuid.UUID("07f3d559-63c5-4369-a9e0-deed4195f651"), message_type="FRBC.ActuatorStatus", operation_mode_factor=6919.960475850124, - previous_operation_mode_id=uuid.UUID("2ed8f7de-cbaa-4cab-9d25-6792317aa284"), + previous_operation_mode_id=uuid.UUID( + "2ed8f7de-cbaa-4cab-9d25-6792317aa284" + ), transition_timestamp=datetime( year=2020, month=1, diff --git a/tests/unit/frbc/frbc_fill_level_target_profile_element_test.py b/tests/unit/frbc/frbc_fill_level_target_profile_element_test.py index 62f51df..f3ea375 100644 --- a/tests/unit/frbc/frbc_fill_level_target_profile_element_test.py +++ b/tests/unit/frbc/frbc_fill_level_target_profile_element_test.py @@ -21,8 +21,8 @@ def test__from_json__happy_path_full(self): """ # Act - frbc_fill_level_target_profile_element = FRBCFillLevelTargetProfileElement.from_json( - json_str + frbc_fill_level_target_profile_element = ( + FRBCFillLevelTargetProfileElement.from_json(json_str) ) # Assert diff --git a/tests/unit/frbc/frbc_fill_level_target_profile_test.py b/tests/unit/frbc/frbc_fill_level_target_profile_test.py index 046a0bc..5f2f2b3 100644 --- a/tests/unit/frbc/frbc_fill_level_target_profile_test.py +++ b/tests/unit/frbc/frbc_fill_level_target_profile_test.py @@ -47,7 +47,9 @@ def test__from_json__happy_path_full(self): frbc_fill_level_target_profile.message_id, uuid.UUID("04a6c8af-ca8d-420c-9c11-e96a70fe82b1"), ) - self.assertEqual(frbc_fill_level_target_profile.message_type, "FRBC.FillLevelTargetProfile") + self.assertEqual( + frbc_fill_level_target_profile.message_type, "FRBC.FillLevelTargetProfile" + ) self.assertEqual( frbc_fill_level_target_profile.start_time, datetime( diff --git a/tests/unit/frbc/frbc_leakage_behaviour_element_test.py b/tests/unit/frbc/frbc_leakage_behaviour_element_test.py index 79f480a..08a5364 100644 --- a/tests/unit/frbc/frbc_leakage_behaviour_element_test.py +++ b/tests/unit/frbc/frbc_leakage_behaviour_element_test.py @@ -27,9 +27,13 @@ def test__from_json__happy_path_full(self): # Assert self.assertEqual( frbc_leakage_behaviour_element.fill_level_range, - NumberRange(end_of_range=40192.498918818455, start_of_range=29234.82582981918), + NumberRange( + end_of_range=40192.498918818455, start_of_range=29234.82582981918 + ), + ) + self.assertEqual( + frbc_leakage_behaviour_element.leakage_rate, 1170.4041485129987 ) - self.assertEqual(frbc_leakage_behaviour_element.leakage_rate, 1170.4041485129987) def test__to_json__happy_path_full(self): # Arrange diff --git a/tests/unit/frbc/frbc_system_description_test.py b/tests/unit/frbc/frbc_system_description_test.py index 9950ea7..0ad8bfd 100644 --- a/tests/unit/frbc/frbc_system_description_test.py +++ b/tests/unit/frbc/frbc_system_description_test.py @@ -151,7 +151,9 @@ def test__from_json__happy_path_full(self): timers=[ Timer( diagnostic_label="some-test-string4315", - duration=Duration.from_timedelta(timedelta(milliseconds=14099)), + duration=Duration.from_timedelta( + timedelta(milliseconds=14099) + ), id=uuid.UUID("e1ff9e58-935b-4765-92e3-5e7679f73eb6"), ) ], @@ -169,7 +171,9 @@ def test__from_json__happy_path_full(self): FRBCStorageDescription( diagnostic_label="some-test-string8418", fill_level_label="some-test-string9512", - fill_level_range=NumberRange(end_of_range=20876.752745956997, start_of_range=18324.0229135081), + fill_level_range=NumberRange( + end_of_range=20876.752745956997, start_of_range=18324.0229135081 + ), provides_fill_level_target_profile=False, provides_leakage_behaviour=True, provides_usage_forecast=False, @@ -244,7 +248,9 @@ def test__to_json__happy_path_full(self): timers=[ Timer( diagnostic_label="some-test-string4315", - duration=Duration.from_timedelta(timedelta(milliseconds=14099)), + duration=Duration.from_timedelta( + timedelta(milliseconds=14099) + ), id=uuid.UUID("e1ff9e58-935b-4765-92e3-5e7679f73eb6"), ) ], @@ -256,7 +262,9 @@ def test__to_json__happy_path_full(self): storage=FRBCStorageDescription( diagnostic_label="some-test-string8418", fill_level_label="some-test-string9512", - fill_level_range=NumberRange(end_of_range=20876.752745956997, start_of_range=18324.0229135081), + fill_level_range=NumberRange( + end_of_range=20876.752745956997, start_of_range=18324.0229135081 + ), provides_fill_level_target_profile=False, provides_leakage_behaviour=True, provides_usage_forecast=False, diff --git a/tests/unit/reception_status_awaiter_test.py b/tests/unit/reception_status_awaiter_test.py index 167966d..318bb9f 100644 --- a/tests/unit/reception_status_awaiter_test.py +++ b/tests/unit/reception_status_awaiter_test.py @@ -29,7 +29,9 @@ async def test__wait_for_reception_status__receive_while_waiting(self): ) # Act - wait_task = asyncio.create_task(awaiter.wait_for_reception_status(message_id, 1.0)) + wait_task = asyncio.create_task( + awaiter.wait_for_reception_status(message_id, 1.0) + ) should_be_waiting_still = not wait_task.done() await awaiter.receive_reception_status(s2_reception_status) await wait_task @@ -53,7 +55,9 @@ async def test__wait_for_reception_status__already_received(self): # Act await awaiter.receive_reception_status(s2_reception_status) - received_s2_reception_status = await awaiter.wait_for_reception_status(message_id, 1.0) + received_s2_reception_status = await awaiter.wait_for_reception_status( + message_id, 1.0 + ) # Assert expected_s2_reception_status = ReceptionStatus( @@ -70,8 +74,12 @@ async def test__wait_for_reception_status__multiple_receive_while_waiting(self): ) # Act - wait_task_1 = asyncio.create_task(awaiter.wait_for_reception_status(message_id, 1.0)) - wait_task_2 = asyncio.create_task(awaiter.wait_for_reception_status(message_id, 1.0)) + wait_task_1 = asyncio.create_task( + awaiter.wait_for_reception_status(message_id, 1.0) + ) + wait_task_2 = asyncio.create_task( + awaiter.wait_for_reception_status(message_id, 1.0) + ) should_be_waiting_still_1 = not wait_task_1.done() should_be_waiting_still_2 = not wait_task_2.done() await awaiter.receive_reception_status(s2_reception_status) From 2f267ac529ea463b8efe7d12b6ad373e54a15489 Mon Sep 17 00:00:00 2001 From: Vlad Iftime Date: Sun, 13 Apr 2025 14:36:43 +0200 Subject: [PATCH 12/14] Chore: OMBC arguments fixed Signed-off-by: Vlad Iftime --- src/s2python/ombc/ombc_instruction.py | 2 +- src/s2python/ombc/ombc_operation_mode.py | 2 +- src/s2python/ombc/ombc_status.py | 2 +- src/s2python/ombc/ombc_system_description.py | 4 +--- src/s2python/ombc/ombc_timer_status.py | 2 +- 5 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/s2python/ombc/ombc_instruction.py b/src/s2python/ombc/ombc_instruction.py index 18800e2..6131916 100644 --- a/src/s2python/ombc/ombc_instruction.py +++ b/src/s2python/ombc/ombc_instruction.py @@ -8,7 +8,7 @@ @catch_and_convert_exceptions -class OMBCInstruction(GenOMBCInstruction, S2MessageComponent["OMBCInstruction"]): +class OMBCInstruction(GenOMBCInstruction, S2MessageComponent): model_config = GenOMBCInstruction.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/ombc/ombc_operation_mode.py b/src/s2python/ombc/ombc_operation_mode.py index 1a9586f..4c2b778 100644 --- a/src/s2python/ombc/ombc_operation_mode.py +++ b/src/s2python/ombc/ombc_operation_mode.py @@ -12,7 +12,7 @@ @catch_and_convert_exceptions -class OMBCOperationMode(GenOMBCOperationMode, S2MessageComponent["OMBCOperationMode"]): +class OMBCOperationMode(GenOMBCOperationMode, S2MessageComponent): model_config = GenOMBCOperationMode.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/ombc/ombc_status.py b/src/s2python/ombc/ombc_status.py index 3c0f6ec..c782c25 100644 --- a/src/s2python/ombc/ombc_status.py +++ b/src/s2python/ombc/ombc_status.py @@ -9,7 +9,7 @@ @catch_and_convert_exceptions -class OMBCStatus(GenOMBCStatus, S2MessageComponent["OMBCStatus"]): +class OMBCStatus(GenOMBCStatus, S2MessageComponent): model_config = GenOMBCStatus.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/ombc/ombc_system_description.py b/src/s2python/ombc/ombc_system_description.py index 694cf4b..efb4826 100644 --- a/src/s2python/ombc/ombc_system_description.py +++ b/src/s2python/ombc/ombc_system_description.py @@ -13,9 +13,7 @@ @catch_and_convert_exceptions -class OMBCSystemDescription( - GenOMBCSystemDescription, S2MessageComponent["OMBCSystemDescription"] -): +class OMBCSystemDescription(GenOMBCSystemDescription, S2MessageComponent): model_config = GenOMBCSystemDescription.model_config model_config["validate_assignment"] = True diff --git a/src/s2python/ombc/ombc_timer_status.py b/src/s2python/ombc/ombc_timer_status.py index 2c530e7..906ea7d 100644 --- a/src/s2python/ombc/ombc_timer_status.py +++ b/src/s2python/ombc/ombc_timer_status.py @@ -9,7 +9,7 @@ @catch_and_convert_exceptions -class OMBCTimerStatus(GenOMBCTimerStatus, S2MessageComponent["OMBCTimerStatus"]): +class OMBCTimerStatus(GenOMBCTimerStatus, S2MessageComponent): model_config = GenOMBCTimerStatus.model_config model_config["validate_assignment"] = True From 807bffd4887f46ee5072bfd58dd2c3452cd5bffd Mon Sep 17 00:00:00 2001 From: Vlad Iftime Date: Sun, 13 Apr 2025 14:47:12 +0200 Subject: [PATCH 13/14] Chore: Fixing failing tests Signed-off-by: Vlad Iftime --- src/s2python/message.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/s2python/message.py b/src/s2python/message.py index 0de8ea2..915a59c 100644 --- a/src/s2python/message.py +++ b/src/s2python/message.py @@ -89,6 +89,10 @@ FRBCSystemDescription, FRBCTimerStatus, FRBCUsageForecast, + OMBCInstruction, + OMBCOperationMode, + OMBCTimerStatus, + OMBCOperationMode, PEBCPowerConstraints, PPBCEndInterruptionInstruction, PPBCPowerProfileDefinition, From 745106254791d69185d54b047d1d71d9eb6315dd Mon Sep 17 00:00:00 2001 From: Vlad Iftime Date: Sun, 13 Apr 2025 14:52:40 +0200 Subject: [PATCH 14/14] Chore: Fixing failing tests Signed-off-by: Vlad Iftime --- src/s2python/message.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/s2python/message.py b/src/s2python/message.py index 915a59c..3467a57 100644 --- a/src/s2python/message.py +++ b/src/s2python/message.py @@ -89,10 +89,10 @@ FRBCSystemDescription, FRBCTimerStatus, FRBCUsageForecast, - OMBCInstruction, - OMBCOperationMode, + OMBCSystemDescription, + OMBCStatus, OMBCTimerStatus, - OMBCOperationMode, + OMBCInstruction, PEBCPowerConstraints, PPBCEndInterruptionInstruction, PPBCPowerProfileDefinition, @@ -104,7 +104,6 @@ SelectControlType, SessionRequest, DDBCActuatorStatus, - FRBCInstruction, PEBCEnergyConstraint, PEBCInstruction, Handshake, @@ -126,6 +125,7 @@ FRBCOperationModeElement, FRBCStorageDescription, FRBCUsageForecastElement, + OMBCOperationMode, PEBCAllowedLimitRange, PEBCPowerEnvelope, PEBCPowerEnvelopeElement,