|
| 1 | +# License: All rights reserved |
| 2 | +# Copyright © 2024 Frequenz Energy-as-a-Service GmbH |
| 3 | + |
| 4 | +"""Helper class to manage actors based on dispatches.""" |
| 5 | + |
| 6 | +import logging |
| 7 | +from dataclasses import dataclass |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +from frequenz.channels import Receiver, Sender |
| 11 | +from frequenz.client.dispatch.types import ComponentSelector |
| 12 | +from frequenz.sdk.actor import Actor |
| 13 | + |
| 14 | +from ._dispatch import Dispatch, RunningState |
| 15 | + |
| 16 | +_logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +@dataclass(frozen=True, kw_only=True) |
| 20 | +class DispatchUpdate: |
| 21 | + """Event emitted when the dispatch changes.""" |
| 22 | + |
| 23 | + components: ComponentSelector |
| 24 | + """Components to be used.""" |
| 25 | + |
| 26 | + dry_run: bool |
| 27 | + """Whether this is a dry run.""" |
| 28 | + |
| 29 | + options: dict[str, Any] |
| 30 | + """Additional options.""" |
| 31 | + |
| 32 | + |
| 33 | +class DispatchManagingActor(Actor): |
| 34 | + """Helper class to manage actors based on dispatches. |
| 35 | +
|
| 36 | + Example usage: |
| 37 | +
|
| 38 | + ```python |
| 39 | + import os |
| 40 | + import asyncio |
| 41 | + from frequenz.dispatch import Dispatcher, DispatchManagingActor, DispatchUpdate |
| 42 | + from frequenz.client.dispatch.types import ComponentSelector |
| 43 | + from frequenz.client.common.microgrid.components import ComponentCategory |
| 44 | +
|
| 45 | + from frequenz.channels import Receiver, Broadcast |
| 46 | +
|
| 47 | + class MyActor(Actor): |
| 48 | + def __init__(self, updates_channel: Receiver[DispatchUpdate]): |
| 49 | + super().__init__() |
| 50 | + self._updates_channel = updates_channel |
| 51 | + self._dry_run: bool |
| 52 | + self._options : dict[str, Any] |
| 53 | +
|
| 54 | + async def _run(self) -> None: |
| 55 | + while True: |
| 56 | + update = await self._updates_channel.receive() |
| 57 | + print("Received update:", update) |
| 58 | +
|
| 59 | + self.set_components(update.components) |
| 60 | + self._dry_run = update.dry_run |
| 61 | + self._options = update.options |
| 62 | +
|
| 63 | + def set_components(self, components: ComponentSelector) -> None: |
| 64 | + match components: |
| 65 | + case [int(), *_] as component_ids: |
| 66 | + print("Dispatch: Setting components to %s", components) |
| 67 | + case [ComponentCategory.BATTERY, *_]: |
| 68 | + print("Dispatch: Using all battery components") |
| 69 | + case unsupported: |
| 70 | + print( |
| 71 | + "Dispatch: Requested an unsupported selector %r, " |
| 72 | + "but only component IDs or category BATTERY are supported.", |
| 73 | + unsupported, |
| 74 | + ) |
| 75 | +
|
| 76 | + async def run(): |
| 77 | + url = os.getenv("DISPATCH_API_URL", "grpc://fz-0004.frequenz.io:50051") |
| 78 | + key = os.getenv("DISPATCH_API_KEY", "some-key") |
| 79 | +
|
| 80 | + microgrid_id = 1 |
| 81 | +
|
| 82 | + dispatcher = Dispatcher( |
| 83 | + microgrid_id=microgrid_id, |
| 84 | + server_url=url, |
| 85 | + key=key |
| 86 | + ) |
| 87 | +
|
| 88 | + # Create update channel to receive dispatch update events pre-start and mid-run |
| 89 | + dispatch_updates_channel = Broadcast[DispatchUpdate](name="dispatch_updates_channel") |
| 90 | +
|
| 91 | + # Start actor and supporting actor, give each a config channel receiver |
| 92 | + my_actor = MyActor(dispatch_updates_channel.new_receiver()) |
| 93 | +
|
| 94 | + status_receiver = dispatcher.running_status_change.new_receiver() |
| 95 | +
|
| 96 | + dispatch_runner = DispatchManagingActor( |
| 97 | + actor=my_actor, |
| 98 | + dispatch_type="EXAMPLE", |
| 99 | + running_status_receiver=status_receiver, |
| 100 | + updates_sender=dispatch_updates_channel.new_sender(), |
| 101 | + ) |
| 102 | +
|
| 103 | + await asyncio.gather(dispatcher.start(), dispatch_runner.start()) |
| 104 | + ``` |
| 105 | + """ |
| 106 | + |
| 107 | + def __init__( |
| 108 | + self, |
| 109 | + actor: Actor, |
| 110 | + dispatch_type: str, |
| 111 | + running_status_receiver: Receiver[Dispatch], |
| 112 | + updates_sender: Sender[DispatchUpdate] | None = None, |
| 113 | + ) -> None: |
| 114 | + """Initialize the dispatch handler. |
| 115 | +
|
| 116 | + Args: |
| 117 | + actor: The actor to manage. |
| 118 | + dispatch_type: The type of dispatches to handle. |
| 119 | + running_status_receiver: The receiver for dispatch running status changes. |
| 120 | + updates_sender: The sender for dispatch events |
| 121 | + """ |
| 122 | + super().__init__() |
| 123 | + self._dispatch_rx = running_status_receiver |
| 124 | + self._actor = actor |
| 125 | + self._dispatch_type = dispatch_type |
| 126 | + self._updates_sender = updates_sender |
| 127 | + |
| 128 | + def _start_actor(self) -> None: |
| 129 | + """Start the actor.""" |
| 130 | + if self._actor.is_running: |
| 131 | + _logger.warning("Actor %s is already running", self._actor.name) |
| 132 | + else: |
| 133 | + self._actor.start() |
| 134 | + |
| 135 | + async def _stop_actor(self, msg: str) -> None: |
| 136 | + """Stop the actor. |
| 137 | +
|
| 138 | + Args: |
| 139 | + msg: The message to be passed to the actor being stopped. |
| 140 | + """ |
| 141 | + if self._actor.is_running: |
| 142 | + await self._actor.stop(msg) |
| 143 | + else: |
| 144 | + _logger.warning("Actor %s is not running", self._actor.name) |
| 145 | + |
| 146 | + async def _run(self) -> None: |
| 147 | + """Wait for dispatches and handle them.""" |
| 148 | + async for dispatch in self._dispatch_rx: |
| 149 | + await self._handle_dispatch(dispatch=dispatch) |
| 150 | + |
| 151 | + async def _handle_dispatch(self, dispatch: Dispatch) -> None: |
| 152 | + """Handle a dispatch. |
| 153 | +
|
| 154 | + Args: |
| 155 | + dispatch: The dispatch to handle. |
| 156 | + """ |
| 157 | + running = dispatch.running(self._dispatch_type) |
| 158 | + match running: |
| 159 | + case RunningState.STOPPED: |
| 160 | + _logger.info("Stopped by dispatch %s", dispatch.id) |
| 161 | + await self._stop_actor("Dispatch stopped") |
| 162 | + case RunningState.RUNNING: |
| 163 | + if self._updates_sender is not None: |
| 164 | + _logger.info("Updated by dispatch %s", dispatch.id) |
| 165 | + await self._updates_sender.send( |
| 166 | + DispatchUpdate( |
| 167 | + components=dispatch.selector, |
| 168 | + dry_run=dispatch.dry_run, |
| 169 | + options=dispatch.payload, |
| 170 | + ) |
| 171 | + ) |
| 172 | + |
| 173 | + _logger.info("Started by dispatch %s", dispatch.id) |
| 174 | + self._start_actor() |
| 175 | + case RunningState.DIFFERENT_TYPE: |
| 176 | + _logger.debug( |
| 177 | + "Unknown dispatch! Ignoring dispatch of type %s", dispatch.type |
| 178 | + ) |
0 commit comments