|
7 | 7 |
|
8 | 8 | import asyncio |
9 | 9 | import itertools |
| 10 | +import math |
10 | 11 | from dataclasses import replace |
11 | | -from typing import Any |
| 12 | +from datetime import datetime, timedelta |
| 13 | +from typing import Any, assert_never |
12 | 14 |
|
13 | | -from frequenz.api.microgrid.v1 import microgrid_pb2_grpc |
14 | | -from frequenz.client.base import channel, client, retry, streaming |
| 15 | +from frequenz.api.microgrid.v1 import microgrid_pb2, microgrid_pb2_grpc |
| 16 | +from frequenz.client.base import channel, client, conversion, retry, streaming |
15 | 17 | from frequenz.client.common.microgrid.components import ComponentId |
16 | 18 | from google.protobuf.empty_pb2 import Empty |
17 | 19 | from typing_extensions import override |
18 | 20 |
|
19 | 21 | from ._exception import ClientNotConnected |
20 | 22 | from ._microgrid_info import MicrogridInfo |
21 | 23 | from ._microgrid_info_proto import microgrid_info_from_proto |
| 24 | +from .component._component import Component |
22 | 25 |
|
23 | 26 | DEFAULT_GRPC_CALL_TIMEOUT = 60.0 |
24 | 27 | """The default timeout for gRPC calls made by this client (in seconds).""" |
@@ -153,3 +156,182 @@ async def get_microgrid_info( # noqa: DOC502 (raises ApiClientError indirectly) |
153 | 156 | ) |
154 | 157 |
|
155 | 158 | return microgrid_info_from_proto(microgrid.microgrid) |
| 159 | + |
| 160 | + async def set_component_power_active( # noqa: DOC502 (raises ApiClientError indirectly) |
| 161 | + self, |
| 162 | + component: ComponentId | Component, |
| 163 | + power: float, |
| 164 | + *, |
| 165 | + request_lifetime: timedelta | None = None, |
| 166 | + validate_arguments: bool = True, |
| 167 | + ) -> datetime | None: |
| 168 | + """Set the active power output of a component. |
| 169 | +
|
| 170 | + The power output can be negative or positive, depending on whether the component |
| 171 | + is supposed to be discharging or charging, respectively. |
| 172 | +
|
| 173 | + The power output is specified in watts. |
| 174 | +
|
| 175 | + The return value is the timestamp until which the given power command will |
| 176 | + stay in effect. After this timestamp, the component's active power will be |
| 177 | + set to 0, if the API receives no further command to change it before then. |
| 178 | + By default, this timestamp will be set to the current time plus 60 seconds. |
| 179 | +
|
| 180 | + Note: |
| 181 | + The target component may have a resolution of more than 1 W. E.g., an |
| 182 | + inverter may have a resolution of 88 W. In such cases, the magnitude of |
| 183 | + power will be floored to the nearest multiple of the resolution. |
| 184 | +
|
| 185 | + Args: |
| 186 | + component: The component to set the output active power of. |
| 187 | + power: The output active power level, in watts. Negative values are for |
| 188 | + discharging, and positive values are for charging. |
| 189 | + request_lifetime: The duration, until which the request will stay in effect. |
| 190 | + This duration has to be between 10 seconds and 15 minutes (including |
| 191 | + both limits), otherwise the request will be rejected. It has |
| 192 | + a resolution of a second, so fractions of a second will be rounded for |
| 193 | + `timedelta` objects, and it is interpreted as seconds for `int` objects. |
| 194 | + If not provided, it usually defaults to 60 seconds. |
| 195 | + validate_arguments: Whether to validate the arguments before sending the |
| 196 | + request. If `True` a `ValueError` will be raised if an argument is |
| 197 | + invalid without even sending the request to the server, if `False`, the |
| 198 | + request will be sent without validation. |
| 199 | +
|
| 200 | + Returns: |
| 201 | + The timestamp until which the given power command will stay in effect, or |
| 202 | + `None` if it was not provided by the server. |
| 203 | +
|
| 204 | + Raises: |
| 205 | + ApiClientError: If there are any errors communicating with the Microgrid API, |
| 206 | + most likely a subclass of |
| 207 | + [GrpcError][frequenz.client.microgrid.GrpcError]. |
| 208 | + """ |
| 209 | + lifetime_seconds = _delta_to_seconds(request_lifetime) |
| 210 | + |
| 211 | + if validate_arguments: |
| 212 | + _validate_set_power_args(power=power, request_lifetime=lifetime_seconds) |
| 213 | + |
| 214 | + response = await client.call_stub_method( |
| 215 | + self, |
| 216 | + lambda: self.stub.SetComponentPowerActive( |
| 217 | + microgrid_pb2.SetComponentPowerActiveRequest( |
| 218 | + component_id=_get_component_id(component), |
| 219 | + power=power, |
| 220 | + request_lifetime=lifetime_seconds, |
| 221 | + ), |
| 222 | + timeout=DEFAULT_GRPC_CALL_TIMEOUT, |
| 223 | + ), |
| 224 | + method_name="SetComponentPowerActive", |
| 225 | + ) |
| 226 | + |
| 227 | + if response.HasField("valid_until"): |
| 228 | + return conversion.to_datetime(response.valid_until) |
| 229 | + |
| 230 | + return None |
| 231 | + |
| 232 | + async def set_component_power_reactive( # noqa: DOC502 (raises ApiClientError indirectly) |
| 233 | + self, |
| 234 | + component: ComponentId | Component, |
| 235 | + power: float, |
| 236 | + *, |
| 237 | + request_lifetime: timedelta | None = None, |
| 238 | + validate_arguments: bool = True, |
| 239 | + ) -> datetime | None: |
| 240 | + """Set the reactive power output of a component. |
| 241 | +
|
| 242 | + We follow the polarity specified in the IEEE 1459-2010 standard |
| 243 | + definitions, where: |
| 244 | +
|
| 245 | + - Positive reactive is inductive (current is lagging the voltage) |
| 246 | + - Negative reactive is capacitive (current is leading the voltage) |
| 247 | +
|
| 248 | + The power output is specified in VAr. |
| 249 | +
|
| 250 | + The return value is the timestamp until which the given power command will |
| 251 | + stay in effect. After this timestamp, the component's reactive power will |
| 252 | + be set to 0, if the API receives no further command to change it before |
| 253 | + then. By default, this timestamp will be set to the current time plus 60 |
| 254 | + seconds. |
| 255 | +
|
| 256 | + Note: |
| 257 | + The target component may have a resolution of more than 1 VAr. E.g., an |
| 258 | + inverter may have a resolution of 88 VAr. In such cases, the magnitude of |
| 259 | + power will be floored to the nearest multiple of the resolution. |
| 260 | +
|
| 261 | + Args: |
| 262 | + component: The component to set the output reactive power of. |
| 263 | + power: The output reactive power level, in VAr. The standard of polarity is |
| 264 | + as per the IEEE 1459-2010 standard definitions: positive reactive is |
| 265 | + inductive (current is lagging the voltage); negative reactive is |
| 266 | + capacitive (current is leading the voltage). |
| 267 | + request_lifetime: The duration, until which the request will stay in effect. |
| 268 | + This duration has to be between 10 seconds and 15 minutes (including |
| 269 | + both limits), otherwise the request will be rejected. It has |
| 270 | + a resolution of a second, so fractions of a second will be rounded for |
| 271 | + `timedelta` objects, and it is interpreted as seconds for `int` objects. |
| 272 | + If not provided, it usually defaults to 60 seconds. |
| 273 | + validate_arguments: Whether to validate the arguments before sending the |
| 274 | + request. If `True` a `ValueError` will be raised if an argument is |
| 275 | + invalid without even sending the request to the server, if `False`, the |
| 276 | + request will be sent without validation. |
| 277 | +
|
| 278 | + Returns: |
| 279 | + The timestamp until which the given power command will stay in effect, or |
| 280 | + `None` if it was not provided by the server. |
| 281 | +
|
| 282 | + Raises: |
| 283 | + ApiClientError: If there are any errors communicating with the Microgrid API, |
| 284 | + most likely a subclass of |
| 285 | + [GrpcError][frequenz.client.microgrid.GrpcError]. |
| 286 | + """ |
| 287 | + lifetime_seconds = _delta_to_seconds(request_lifetime) |
| 288 | + |
| 289 | + if validate_arguments: |
| 290 | + _validate_set_power_args(power=power, request_lifetime=lifetime_seconds) |
| 291 | + |
| 292 | + response = await client.call_stub_method( |
| 293 | + self, |
| 294 | + lambda: self.stub.SetComponentPowerReactive( |
| 295 | + microgrid_pb2.SetComponentPowerReactiveRequest( |
| 296 | + component_id=_get_component_id(component), |
| 297 | + power=power, |
| 298 | + request_lifetime=lifetime_seconds, |
| 299 | + ), |
| 300 | + timeout=DEFAULT_GRPC_CALL_TIMEOUT, |
| 301 | + ), |
| 302 | + method_name="SetComponentPowerReactive", |
| 303 | + ) |
| 304 | + |
| 305 | + if response.HasField("valid_until"): |
| 306 | + return conversion.to_datetime(response.valid_until) |
| 307 | + |
| 308 | + return None |
| 309 | + |
| 310 | + |
| 311 | +def _get_component_id(component: ComponentId | Component) -> int: |
| 312 | + """Get the component ID from a component or component ID.""" |
| 313 | + match component: |
| 314 | + case ComponentId(): |
| 315 | + return int(component) |
| 316 | + case Component(): |
| 317 | + return int(component.id) |
| 318 | + case unexpected: |
| 319 | + assert_never(unexpected) |
| 320 | + |
| 321 | + |
| 322 | +def _delta_to_seconds(delta: timedelta | None) -> int | None: |
| 323 | + """Convert a `timedelta` to seconds (or `None` if `None`).""" |
| 324 | + return round(delta.total_seconds()) if delta is not None else None |
| 325 | + |
| 326 | + |
| 327 | +def _validate_set_power_args(*, power: float, request_lifetime: int | None) -> None: |
| 328 | + """Validate the request lifetime.""" |
| 329 | + if math.isnan(power): |
| 330 | + raise ValueError("power cannot be NaN") |
| 331 | + if request_lifetime is not None: |
| 332 | + minimum_lifetime = 10 # 10 seconds |
| 333 | + maximum_lifetime = 900 # 15 minutes |
| 334 | + if not minimum_lifetime <= request_lifetime <= maximum_lifetime: |
| 335 | + raise ValueError( |
| 336 | + "request_lifetime must be between 10 seconds and 15 minutes" |
| 337 | + ) |
0 commit comments