-
Notifications
You must be signed in to change notification settings - Fork 21
Extract mixin from PV and EV component managers #1403
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
simonvoelcker
wants to merge
2
commits into
frequenz-floss:v1.x.x
Choose a base branch
from
simonvoelcker:extract-set-power
base: v1.x.x
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
113 changes: 113 additions & 0 deletions
113
src/frequenz/sdk/microgrid/_power_distributing/_component_managers/_set_power_mixin.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| # License: MIT | ||
| # Copyright © 2026 Frequenz Energy-as-a-Service GmbH | ||
|
|
||
| """Mixin for setting component powers via microgrid API.""" | ||
|
|
||
| import asyncio | ||
| import logging | ||
| from datetime import datetime, timedelta | ||
|
|
||
| from frequenz.client.base.exception import ApiClientError | ||
| from frequenz.client.common.microgrid.components import ComponentId | ||
| from frequenz.quantities import Power | ||
|
|
||
| from ... import connection_manager | ||
|
|
||
| from ..request import Request | ||
| from ..result import PartialFailure, Result, Success | ||
|
|
||
| _logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class SetPowerMixin: | ||
| """Mixin for setting component powers via microgrid API.""" | ||
|
|
||
| @staticmethod | ||
| async def _set_api_power( # pylint: disable=too-many-locals,too-many-arguments | ||
| *, | ||
| request: Request, | ||
| target_power: Power, | ||
| allocations: dict[ComponentId, Power], | ||
| api_request_timeout: timedelta, | ||
| remaining_power: Power, | ||
| component_category: str, | ||
| ) -> Result: | ||
| """Send the component power changes to the microgrid API. | ||
|
|
||
| Args: | ||
| request: Set-power request sent to the `PowerDistributingActor`. | ||
| target_power: The requested power. | ||
| allocations: A dictionary containing the new power allocations for | ||
| each component. | ||
| api_request_timeout: The timeout for the API request. | ||
| remaining_power: Any excess (remaining) power. | ||
| component_category: Component category name, for display purposes. | ||
|
|
||
| Returns: | ||
| Power distribution result, corresponding to the result of the API | ||
| request. | ||
| """ | ||
| api_client = connection_manager.get().api_client | ||
| tasks: dict[ComponentId, asyncio.Task[datetime | None]] = {} | ||
| for component_id, power in allocations.items(): | ||
| tasks[component_id] = asyncio.create_task( | ||
| api_client.set_component_power_active(component_id, power.as_watts()) | ||
| ) | ||
| _, pending = await asyncio.wait( | ||
| tasks.values(), | ||
| timeout=api_request_timeout.total_seconds(), | ||
| return_when=asyncio.ALL_COMPLETED, | ||
| ) | ||
| # collect the timed out tasks and cancel them while keeping the | ||
| # exceptions, so that they can be processed later. | ||
| for task in pending: | ||
| task.cancel() | ||
| await asyncio.gather(*pending, return_exceptions=True) | ||
|
|
||
| failed_components: set[ComponentId] = set() | ||
| succeeded_components: set[ComponentId] = set() | ||
| failed_power = Power.zero() | ||
| for component_id, task in tasks.items(): | ||
| try: | ||
| task.result() | ||
| except asyncio.CancelledError: | ||
| _logger.warning( | ||
| "Timeout while setting power to %s %s", | ||
| component_category, | ||
| component_id, | ||
| ) | ||
| except ApiClientError as exc: | ||
| _logger.warning( | ||
| "Got a client error while setting power to %s %s: %s", | ||
| component_category, | ||
| component_id, | ||
| exc, | ||
| ) | ||
| except Exception: # pylint: disable=broad-except | ||
| _logger.exception( | ||
| "Unknown error while setting power to %s: %s", | ||
| component_category, | ||
| component_id, | ||
| ) | ||
| else: | ||
| succeeded_components.add(component_id) | ||
| continue | ||
|
|
||
| failed_components.add(component_id) | ||
| failed_power += allocations[component_id] | ||
|
|
||
| if failed_components: | ||
| return PartialFailure( | ||
| failed_components=failed_components, | ||
| succeeded_components=succeeded_components, | ||
| failed_power=failed_power, | ||
| succeeded_power=target_power - failed_power - remaining_power, | ||
| excess_power=remaining_power, | ||
| request=request, | ||
| ) | ||
| return Success( | ||
| succeeded_components=succeeded_components, | ||
| succeeded_power=target_power - remaining_power, | ||
| excess_power=remaining_power, | ||
| request=request, | ||
| ) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Optional, but I wonder if this should just be a function instead, the mixin is a lot of machinary for a static method that doesn't need self.