frequenz-client-microgrid 0.3.0__tar.gz → 0.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/PKG-INFO +1 -1
  2. frequenz-client-microgrid-0.5.0/RELEASE_NOTES.md +10 -0
  3. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/pyproject.toml +26 -20
  4. frequenz-client-microgrid-0.5.0/src/frequenz/client/microgrid/__init__.py +115 -0
  5. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/src/frequenz/client/microgrid/_client.py +107 -119
  6. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/src/frequenz/client/microgrid/_component.py +24 -26
  7. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/src/frequenz/client/microgrid/_component_data.py +30 -32
  8. frequenz-client-microgrid-0.5.0/src/frequenz/client/microgrid/_component_error.py +213 -0
  9. frequenz-client-microgrid-0.5.0/src/frequenz/client/microgrid/_component_states.py +253 -0
  10. frequenz-client-microgrid-0.5.0/src/frequenz/client/microgrid/_exception.py +50 -0
  11. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/src/frequenz_client_microgrid.egg-info/PKG-INFO +1 -1
  12. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/src/frequenz_client_microgrid.egg-info/SOURCES.txt +2 -0
  13. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/src/frequenz_client_microgrid.egg-info/requires.txt +22 -21
  14. frequenz-client-microgrid-0.3.0/RELEASE_NOTES.md +0 -5
  15. frequenz-client-microgrid-0.3.0/src/frequenz/client/microgrid/__init__.py +0 -52
  16. frequenz-client-microgrid-0.3.0/src/frequenz/client/microgrid/_component_states.py +0 -96
  17. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/LICENSE +0 -0
  18. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/MANIFEST.in +0 -0
  19. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/README.md +0 -0
  20. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/setup.cfg +0 -0
  21. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/src/frequenz/client/microgrid/_connection.py +0 -0
  22. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/src/frequenz/client/microgrid/_constants.py +0 -0
  23. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/src/frequenz/client/microgrid/_metadata.py +0 -0
  24. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/src/frequenz/client/microgrid/conftest.py +0 -0
  25. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/src/frequenz/client/microgrid/py.typed +0 -0
  26. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/src/frequenz_client_microgrid.egg-info/dependency_links.txt +0 -0
  27. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.5.0}/src/frequenz_client_microgrid.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: frequenz-client-microgrid
3
- Version: 0.3.0
3
+ Version: 0.5.0
4
4
  Summary: Microgrid API client for Python
5
5
  Author-email: Frequenz Energy-as-a-Service GmbH <floss@frequenz.com>
6
6
  License: MIT
@@ -0,0 +1,10 @@
1
+ # Frequenz Microgrid API Client Release Notes
2
+
3
+ ## Upgrading
4
+
5
+ - This release stops using `betterproto` and `grpclib` as backend for gRPC and goes back to using Google's `grpcio` and `protobuf`.
6
+
7
+ If your code was using `betterproto` and `grpclib`, it now needs to be ported to use `grpcio` and `protobuf` too. Remember to also remove any `betterproto` and `grpclib` dependencies from your project.
8
+
9
+ - We are now using base-client v0.6.0.
10
+
@@ -38,9 +38,9 @@ requires-python = ">= 3.11, < 4"
38
38
  dependencies = [
39
39
  "frequenz-api-microgrid >= 0.15.3, < 0.16.0",
40
40
  "frequenz-channels >= 1.0.0-rc1, < 2.0.0",
41
- "frequenz-client-base >= 0.3.0, < 0.4.0",
41
+ "frequenz-client-base >= 0.6.0, < 0.7",
42
42
  "grpcio >= 1.54.2, < 2",
43
- "protobuf >= 4.21.6, < 5",
43
+ "protobuf >= 4.21.6, < 6",
44
44
  "timezonefinder >= 6.2.0, < 7",
45
45
  "typing-extensions >= 4.5.0, < 5",
46
46
  ]
@@ -52,42 +52,43 @@ email = "floss@frequenz.com"
52
52
 
53
53
  [project.optional-dependencies]
54
54
  dev-flake8 = [
55
- "flake8 == 7.0.0",
55
+ "flake8 == 7.1.1",
56
56
  "flake8-docstrings == 1.7.0",
57
57
  "flake8-pyproject == 1.2.3", # For reading the flake8 config from pyproject.toml
58
- "pydoclint == 0.4.1",
58
+ "pydoclint == 0.5.6",
59
59
  "pydocstyle == 6.3.0",
60
60
  ]
61
- dev-formatting = ["black == 24.2.0", "isort == 5.13.2"]
61
+ dev-formatting = ["black == 24.8.0", "isort == 5.13.2"]
62
62
  dev-mkdocs = [
63
- "black == 24.2.0",
64
- "Markdown==3.5.2",
65
- "mike == 2.0.0",
63
+ "black == 24.8.0",
64
+ "Markdown==3.7",
65
+ "mike == 2.1.3",
66
66
  "mkdocs-gen-files == 0.5.0",
67
67
  "mkdocs-literate-nav == 0.6.1",
68
68
  "mkdocs-macros-plugin == 1.0.5",
69
- "mkdocs-material == 9.5.12",
70
- "mkdocstrings[python] == 0.24.1",
71
- "frequenz-repo-config[lib] == 0.9.1",
69
+ "mkdocs-material == 9.5.33",
70
+ "mkdocstrings[python] == 0.25.2",
71
+ "mkdocstrings-python == 1.10.8",
72
+ "frequenz-repo-config[lib] == 0.10.0",
72
73
  ]
73
74
  dev-mypy = [
74
- "mypy == 1.8.0",
75
- "types-Markdown == 3.5.0.20240129",
75
+ "mypy == 1.11.2",
76
+ "types-Markdown == 3.7.0.20240822",
76
77
  # For checking the noxfile, docs/ script, and tests
77
78
  "frequenz-client-microgrid[dev-mkdocs,dev-noxfile,dev-pytest]",
78
79
  ]
79
- dev-noxfile = ["nox == 2023.4.22", "frequenz-repo-config[lib] == 0.9.1"]
80
+ dev-noxfile = ["nox == 2024.4.15", "frequenz-repo-config[lib] == 0.10.0"]
80
81
  dev-pylint = [
81
- "pylint == 3.1.0",
82
+ "pylint == 3.2.6",
82
83
  # For checking the noxfile, docs/ script, and tests
83
84
  "frequenz-client-microgrid[dev-mkdocs,dev-noxfile,dev-pytest]",
84
85
  ]
85
86
  dev-pytest = [
86
- "pytest == 8.0.2",
87
- "frequenz-repo-config[extra-lint-examples] == 0.9.1",
88
- "pytest-mock == 3.12.0",
89
- "pytest-asyncio == 0.23.5",
90
- "async-solipsism == 0.5",
87
+ "pytest == 8.3.2",
88
+ "frequenz-repo-config[extra-lint-examples] == 0.10.0",
89
+ "pytest-mock == 3.14.0",
90
+ "pytest-asyncio == 0.24.0",
91
+ "async-solipsism == 0.7",
91
92
  ]
92
93
  dev = [
93
94
  "frequenz-client-microgrid[dev-mkdocs,dev-flake8,dev-formatting,dev-mkdocs,dev-mypy,dev-noxfile,dev-pylint,dev-pytest]",
@@ -143,8 +144,13 @@ disable = [
143
144
  # pylint's unsubscriptable check is buggy and is not needed because
144
145
  # it is a type-check, for which we already have mypy.
145
146
  "unsubscriptable-object",
147
+ # Checked by mypy
148
+ "no-member",
149
+ "no-name-in-module",
146
150
  # Checked by flake8
151
+ "f-string-without-interpolation",
147
152
  "line-too-long",
153
+ "missing-function-docstring",
148
154
  "redefined-outer-name",
149
155
  "unnecessary-lambda-assignment",
150
156
  "unused-import",
@@ -0,0 +1,115 @@
1
+ # License: MIT
2
+ # Copyright © 2022 Frequenz Energy-as-a-Service GmbH
3
+
4
+ """Client to connect to the Microgrid API.
5
+
6
+ This package provides a low-level interface for interacting with the microgrid API.
7
+ """
8
+
9
+
10
+ from ._client import ApiClient
11
+ from ._component import (
12
+ Component,
13
+ ComponentCategory,
14
+ ComponentMetadata,
15
+ ComponentMetricId,
16
+ ComponentType,
17
+ Fuse,
18
+ GridMetadata,
19
+ InverterType,
20
+ )
21
+ from ._component_data import (
22
+ BatteryData,
23
+ ComponentData,
24
+ EVChargerData,
25
+ InverterData,
26
+ MeterData,
27
+ )
28
+ from ._component_error import (
29
+ BatteryError,
30
+ BatteryErrorCode,
31
+ ErrorLevel,
32
+ InverterError,
33
+ InverterErrorCode,
34
+ )
35
+ from ._component_states import (
36
+ BatteryComponentState,
37
+ BatteryRelayState,
38
+ EVChargerCableState,
39
+ EVChargerComponentState,
40
+ InverterComponentState,
41
+ )
42
+ from ._connection import Connection
43
+ from ._exception import (
44
+ ApiClientError,
45
+ ClientNotConnected,
46
+ DataLoss,
47
+ EntityAlreadyExists,
48
+ EntityNotFound,
49
+ GrpcError,
50
+ InternalError,
51
+ InvalidArgument,
52
+ OperationAborted,
53
+ OperationCancelled,
54
+ OperationNotImplemented,
55
+ OperationOutOfRange,
56
+ OperationPreconditionFailed,
57
+ OperationTimedOut,
58
+ OperationUnauthenticated,
59
+ PermissionDenied,
60
+ ResourceExhausted,
61
+ ServiceUnavailable,
62
+ UnknownError,
63
+ UnrecognizedGrpcStatus,
64
+ )
65
+ from ._metadata import Location, Metadata
66
+
67
+ __all__ = [
68
+ "ApiClient",
69
+ "ApiClientError",
70
+ "BatteryComponentState",
71
+ "BatteryData",
72
+ "BatteryError",
73
+ "BatteryErrorCode",
74
+ "BatteryRelayState",
75
+ "ClientNotConnected",
76
+ "Component",
77
+ "ComponentCategory",
78
+ "ComponentData",
79
+ "ComponentMetadata",
80
+ "ComponentMetricId",
81
+ "ComponentType",
82
+ "Connection",
83
+ "DataLoss",
84
+ "EVChargerCableState",
85
+ "EVChargerComponentState",
86
+ "EVChargerData",
87
+ "EntityAlreadyExists",
88
+ "EntityNotFound",
89
+ "ErrorLevel",
90
+ "Fuse",
91
+ "GridMetadata",
92
+ "GrpcError",
93
+ "InternalError",
94
+ "InvalidArgument",
95
+ "InverterComponentState",
96
+ "InverterData",
97
+ "InverterError",
98
+ "InverterErrorCode",
99
+ "InverterType",
100
+ "Location",
101
+ "Metadata",
102
+ "MeterData",
103
+ "OperationAborted",
104
+ "OperationCancelled",
105
+ "OperationNotImplemented",
106
+ "OperationOutOfRange",
107
+ "OperationPreconditionFailed",
108
+ "OperationTimedOut",
109
+ "OperationUnauthenticated",
110
+ "PermissionDenied",
111
+ "ResourceExhausted",
112
+ "ServiceUnavailable",
113
+ "UnknownError",
114
+ "UnrecognizedGrpcStatus",
115
+ ]
@@ -5,33 +5,16 @@
5
5
 
6
6
  import asyncio
7
7
  import logging
8
- from collections.abc import Awaitable, Callable, Iterable
8
+ from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Set
9
9
  from typing import Any, TypeVar, cast
10
10
 
11
11
  import grpc.aio
12
-
13
- # pylint: disable=no-name-in-module
14
- from frequenz.api.common.components_pb2 import ComponentCategory as PbComponentCategory
15
- from frequenz.api.common.metrics_pb2 import Bounds as PbBounds
16
- from frequenz.api.microgrid.microgrid_pb2 import ComponentData as PbComponentData
17
- from frequenz.api.microgrid.microgrid_pb2 import ComponentFilter as PbComponentFilter
18
- from frequenz.api.microgrid.microgrid_pb2 import ComponentIdParam as PbComponentIdParam
19
- from frequenz.api.microgrid.microgrid_pb2 import ComponentList as PbComponentList
20
- from frequenz.api.microgrid.microgrid_pb2 import ConnectionFilter as PbConnectionFilter
21
- from frequenz.api.microgrid.microgrid_pb2 import ConnectionList as PbConnectionList
22
- from frequenz.api.microgrid.microgrid_pb2 import (
23
- MicrogridMetadata as PbMicrogridMetadata,
24
- )
25
- from frequenz.api.microgrid.microgrid_pb2 import SetBoundsParam as PbSetBoundsParam
26
- from frequenz.api.microgrid.microgrid_pb2 import (
27
- SetPowerActiveParam as PbSetPowerActiveParam,
28
- )
29
- from frequenz.api.microgrid.microgrid_pb2_grpc import MicrogridStub
30
-
31
- # pylint: enable=no-name-in-module
12
+ from frequenz.api.common import components_pb2, metrics_pb2
13
+ from frequenz.api.microgrid import microgrid_pb2, microgrid_pb2_grpc
32
14
  from frequenz.channels import Receiver
33
- from frequenz.client.base import retry, streaming
34
- from google.protobuf.empty_pb2 import Empty # pylint: disable=no-name-in-module
15
+ from frequenz.client.base import channel, retry, streaming
16
+ from google.protobuf.empty_pb2 import Empty
17
+ from google.protobuf.timestamp_pb2 import Timestamp
35
18
 
36
19
  from ._component import (
37
20
  Component,
@@ -49,6 +32,7 @@ from ._component_data import (
49
32
  )
50
33
  from ._connection import Connection
51
34
  from ._constants import RECEIVER_MAX_SIZE
35
+ from ._exception import ApiClientError
52
36
  from ._metadata import Location, Metadata
53
37
 
54
38
  DEFAULT_GRPC_CALL_TIMEOUT = 60.0
@@ -61,32 +45,41 @@ _logger = logging.getLogger(__name__)
61
45
 
62
46
 
63
47
  class ApiClient:
64
- """Microgrid API client implementation using gRPC as the underlying protocol."""
48
+ """A microgrid API client."""
65
49
 
66
50
  def __init__(
67
51
  self,
68
- grpc_channel: grpc.aio.Channel,
69
- target: str,
70
- retry_strategy: retry.Strategy = retry.LinearBackoff(),
52
+ server_url: str,
53
+ *,
54
+ retry_strategy: retry.Strategy | None = None,
71
55
  ) -> None:
72
56
  """Initialize the class instance.
73
57
 
74
58
  Args:
75
- grpc_channel: asyncio-supporting gRPC channel
76
- target: server (host:port) to be used for asyncio-supporting gRPC
77
- channel that the client should use to contact the API
59
+ server_url: The location of the microgrid API server in the form of a URL.
60
+ The following format is expected:
61
+ "grpc://hostname{:`port`}{?ssl=`ssl`}",
62
+ where the `port` should be an int between 0 and 65535 (defaulting to
63
+ 9090) and `ssl` should be a boolean (defaulting to `false`).
64
+ For example: `grpc://localhost:1090?ssl=true`.
78
65
  retry_strategy: The retry strategy to use to reconnect when the connection
79
- to the streaming method is lost.
66
+ to the streaming method is lost. By default a linear backoff strategy
67
+ is used.
80
68
  """
81
- self.target = target
82
- """The location (as "host:port") of the microgrid API gRPC server."""
69
+ self._server_url = server_url
70
+ """The location of the microgrid API server as a URL."""
83
71
 
84
- self.api = MicrogridStub(grpc_channel)
72
+ self.api = microgrid_pb2_grpc.MicrogridStub(channel.parse_grpc_uri(server_url))
85
73
  """The gRPC stub for the microgrid API."""
86
74
 
87
75
  self._broadcasters: dict[int, streaming.GrpcStreamBroadcaster[Any, Any]] = {}
88
76
  self._retry_strategy = retry_strategy
89
77
 
78
+ @property
79
+ def server_url(self) -> str:
80
+ """The server location in URL format."""
81
+ return self._server_url
82
+
90
83
  async def components(self) -> Iterable[Component]:
91
84
  """Fetch all the components present in the microgrid.
92
85
 
@@ -94,38 +87,30 @@ class ApiClient:
94
87
  Iterator whose elements are all the components in the microgrid.
95
88
 
96
89
  Raises:
97
- AioRpcError: if connection to Microgrid API cannot be established or
98
- when the api call exceeded timeout
90
+ ApiClientError: If the are any errors communicating with the Microgrid API,
91
+ most likely a subclass of
92
+ [GrpcError][frequenz.client.microgrid.GrpcError].
99
93
  """
100
94
  try:
101
95
  # grpc.aio is missing types and mypy thinks this is not awaitable,
102
96
  # but it is
103
97
  component_list = await cast(
104
- Awaitable[PbComponentList],
98
+ Awaitable[microgrid_pb2.ComponentList],
105
99
  self.api.ListComponents(
106
- PbComponentFilter(),
100
+ microgrid_pb2.ComponentFilter(),
107
101
  timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
108
102
  ),
109
103
  )
104
+ except grpc.aio.AioRpcError as grpc_error:
105
+ raise ApiClientError.from_grpc_error(
106
+ server_url=self._server_url,
107
+ operation="ListComponents",
108
+ grpc_error=grpc_error,
109
+ ) from grpc_error
110
110
 
111
- except grpc.aio.AioRpcError as err:
112
- msg = f"Failed to list components. Microgrid API: {self.target}. Err: {err.details()}"
113
- raise grpc.aio.AioRpcError(
114
- code=err.code(),
115
- initial_metadata=err.initial_metadata(),
116
- # We need to ignore these errors for some reason, otherwise we get this
117
- # mypy error:
118
- # Argument "trailing_metadata" to "AioRpcError" has incompatible type
119
- # "tuple[_Metadatum, ...]"; expected "Metadata"
120
- # According to grpc.aio documentation, both should have the type
121
- # Metadata.
122
- # https://grpc.github.io/grpc/python/grpc_asyncio.html#grpc.aio.AioRpcError
123
- trailing_metadata=err.trailing_metadata(), # type: ignore[arg-type]
124
- details=msg,
125
- debug_error_string=err.debug_error_string(),
126
- )
127
111
  components_only = filter(
128
- lambda c: c.category is not PbComponentCategory.COMPONENT_CATEGORY_SENSOR,
112
+ lambda c: c.category
113
+ is not components_pb2.ComponentCategory.COMPONENT_CATEGORY_SENSOR,
129
114
  component_list.components,
130
115
  )
131
116
  result: Iterable[Component] = map(
@@ -149,10 +134,10 @@ class ApiClient:
149
134
  Returns:
150
135
  the microgrid metadata.
151
136
  """
152
- microgrid_metadata: PbMicrogridMetadata | None = None
137
+ microgrid_metadata: microgrid_pb2.MicrogridMetadata | None = None
153
138
  try:
154
139
  microgrid_metadata = await cast(
155
- Awaitable[PbMicrogridMetadata],
140
+ Awaitable[microgrid_pb2.MicrogridMetadata],
156
141
  self.api.GetMicrogridMetadata(
157
142
  Empty(),
158
143
  timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
@@ -175,8 +160,8 @@ class ApiClient:
175
160
 
176
161
  async def connections(
177
162
  self,
178
- starts: set[int] | None = None,
179
- ends: set[int] | None = None,
163
+ starts: Set[int] = frozenset(),
164
+ ends: Set[int] = frozenset(),
180
165
  ) -> Iterable[Connection]:
181
166
  """Fetch the connections between components in the microgrid.
182
167
 
@@ -190,33 +175,30 @@ class ApiClient:
190
175
  Microgrid connections matching the provided start and end filters.
191
176
 
192
177
  Raises:
193
- AioRpcError: if connection to Microgrid API cannot be established or
194
- when the api call exceeded timeout
178
+ ApiClientError: If the are any errors communicating with the Microgrid API,
179
+ most likely a subclass of
180
+ [GrpcError][frequenz.client.microgrid.GrpcError].
195
181
  """
196
- connection_filter = PbConnectionFilter(starts=starts, ends=ends)
182
+ connection_filter = microgrid_pb2.ConnectionFilter(starts=starts, ends=ends)
197
183
  try:
198
184
  valid_components, all_connections = await asyncio.gather(
199
185
  self.components(),
200
186
  # grpc.aio is missing types and mypy thinks this is not
201
187
  # awaitable, but it is
202
188
  cast(
203
- Awaitable[PbConnectionList],
189
+ Awaitable[microgrid_pb2.ConnectionList],
204
190
  self.api.ListConnections(
205
191
  connection_filter,
206
192
  timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
207
193
  ),
208
194
  ),
209
195
  )
210
- except grpc.aio.AioRpcError as err:
211
- msg = f"Failed to list connections. Microgrid API: {self.target}. Err: {err.details()}"
212
- raise grpc.aio.AioRpcError(
213
- code=err.code(),
214
- initial_metadata=err.initial_metadata(),
215
- # See the comment in def components() for why we need to ignore
216
- trailing_metadata=err.trailing_metadata(), # type: ignore[arg-type]
217
- details=msg,
218
- debug_error_string=err.debug_error_string(),
219
- )
196
+ except grpc.aio.AioRpcError as grpc_error:
197
+ raise ApiClientError.from_grpc_error(
198
+ server_url=self._server_url,
199
+ operation="ListConnections",
200
+ grpc_error=grpc_error,
201
+ ) from grpc_error
220
202
  # Filter out the components filtered in `components` method.
221
203
  # id=0 is an exception indicating grid component.
222
204
  valid_ids = {c.component_id for c in valid_components}
@@ -238,7 +220,7 @@ class ApiClient:
238
220
  *,
239
221
  component_id: int,
240
222
  expected_category: ComponentCategory,
241
- transform: Callable[[PbComponentData], _ComponentDataT],
223
+ transform: Callable[[microgrid_pb2.ComponentData], _ComponentDataT],
242
224
  maxsize: int,
243
225
  ) -> Receiver[_ComponentDataT]:
244
226
  """Return a new broadcaster receiver for a given `component_id`.
@@ -261,20 +243,24 @@ class ApiClient:
261
243
  expected_category,
262
244
  )
263
245
 
264
- broadcaster = self._broadcasters.setdefault(
265
- component_id,
266
- streaming.GrpcStreamBroadcaster(
246
+ broadcaster = self._broadcasters.get(component_id)
247
+ if broadcaster is None:
248
+ broadcaster = streaming.GrpcStreamBroadcaster(
267
249
  f"raw-component-data-{component_id}",
268
250
  # We need to cast here because grpc says StreamComponentData is
269
- # a grpc.CallIterator[PbComponentData], not a
270
- # grpc.aio.UnaryStreamCall[..., PbComponentData].
251
+ # a grpc.CallIterator[microgrid_pb2.ComponentData] which is not an
252
+ # AsyncIterator, but it is a grpc.aio.UnaryStreamCall[...,
253
+ # microgrid_pb2.ComponentData], which it is.
271
254
  lambda: cast(
272
- grpc.aio.UnaryStreamCall[Any, PbComponentData],
273
- self.api.StreamComponentData(PbComponentIdParam(id=component_id)),
255
+ AsyncIterator[microgrid_pb2.ComponentData],
256
+ self.api.StreamComponentData(
257
+ microgrid_pb2.ComponentIdParam(id=component_id)
258
+ ),
274
259
  ),
275
260
  transform,
276
- ),
277
- )
261
+ retry_strategy=self._retry_strategy,
262
+ )
263
+ self._broadcasters[component_id] = broadcaster
278
264
  return broadcaster.new_receiver(maxsize=maxsize)
279
265
 
280
266
  async def _expect_category(
@@ -305,8 +291,8 @@ class ApiClient:
305
291
 
306
292
  if comp.category != expected_category:
307
293
  raise ValueError(
308
- f"Component id {component_id} is a {comp.category}"
309
- f", not a {expected_category}."
294
+ f"Component id {component_id} is a {comp.category.name.lower()}"
295
+ f", not a {expected_category.name.lower()}."
310
296
  )
311
297
 
312
298
  async def meter_data( # noqa: DOC502 (ValueError is raised indirectly by _expect_category)
@@ -418,27 +404,26 @@ class ApiClient:
418
404
  power_w: power to set for the component.
419
405
 
420
406
  Raises:
421
- AioRpcError: if connection to Microgrid API cannot be established or
422
- when the api call exceeded timeout
407
+ ApiClientError: If the are any errors communicating with the Microgrid API,
408
+ most likely a subclass of
409
+ [GrpcError][frequenz.client.microgrid.GrpcError].
423
410
  """
424
411
  try:
425
412
  await cast(
426
- Awaitable[PbSetPowerActiveParam],
413
+ Awaitable[Empty],
427
414
  self.api.SetPowerActive(
428
- PbSetPowerActiveParam(component_id=component_id, power=power_w),
415
+ microgrid_pb2.SetPowerActiveParam(
416
+ component_id=component_id, power=power_w
417
+ ),
429
418
  timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
430
419
  ),
431
420
  )
432
- except grpc.aio.AioRpcError as err:
433
- msg = f"Failed to set power. Microgrid API: {self.target}. Err: {err.details()}"
434
- raise grpc.aio.AioRpcError(
435
- code=err.code(),
436
- initial_metadata=err.initial_metadata(),
437
- # See the comment in def components() for why we need to ignore
438
- trailing_metadata=err.trailing_metadata(), # type: ignore[arg-type]
439
- details=msg,
440
- debug_error_string=err.debug_error_string(),
441
- )
421
+ except grpc.aio.AioRpcError as grpc_error:
422
+ raise ApiClientError.from_grpc_error(
423
+ server_url=self._server_url,
424
+ operation="SetPowerActive",
425
+ grpc_error=grpc_error,
426
+ ) from grpc_error
442
427
 
443
428
  async def set_bounds(
444
429
  self,
@@ -446,7 +431,7 @@ class ApiClient:
446
431
  lower: float,
447
432
  upper: float,
448
433
  ) -> None:
449
- """Send `PbSetBoundsParam`s received from a channel to the Microgrid service.
434
+ """Send `SetBoundsParam`s received from a channel to the Microgrid service.
450
435
 
451
436
  Args:
452
437
  component_id: ID of the component to set bounds for.
@@ -456,30 +441,33 @@ class ApiClient:
456
441
  Raises:
457
442
  ValueError: when upper bound is less than 0, or when lower bound is
458
443
  greater than 0.
459
- grpc.aio.AioRpcError: if connection to Microgrid API cannot be established
460
- or when the api call exceeded timeout
444
+ ApiClientError: If the are any errors communicating with the Microgrid API,
445
+ most likely a subclass of
446
+ [GrpcError][frequenz.client.microgrid.GrpcError].
461
447
  """
462
- api_details = f"Microgrid API: {self.target}."
463
448
  if upper < 0:
464
449
  raise ValueError(f"Upper bound {upper} must be greater than or equal to 0.")
465
450
  if lower > 0:
466
- raise ValueError(f"Lower bound {upper} must be less than or equal to 0.")
451
+ raise ValueError(f"Lower bound {lower} must be less than or equal to 0.")
467
452
 
468
- target_metric = PbSetBoundsParam.TargetMetric.TARGET_METRIC_POWER_ACTIVE
453
+ target_metric = (
454
+ microgrid_pb2.SetBoundsParam.TargetMetric.TARGET_METRIC_POWER_ACTIVE
455
+ )
469
456
  try:
470
- self.api.AddInclusionBounds(
471
- PbSetBoundsParam(
472
- component_id=component_id,
473
- target_metric=target_metric,
474
- bounds=PbBounds(lower=lower, upper=upper),
457
+ await cast(
458
+ Awaitable[Timestamp],
459
+ self.api.AddInclusionBounds(
460
+ microgrid_pb2.SetBoundsParam(
461
+ component_id=component_id,
462
+ target_metric=target_metric,
463
+ bounds=metrics_pb2.Bounds(lower=lower, upper=upper),
464
+ ),
465
+ timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
475
466
  ),
476
467
  )
477
- except grpc.aio.AioRpcError as err:
478
- _logger.error(
479
- "set_bounds write failed: %s, for message: %s, api: %s. Err: %s",
480
- err,
481
- next,
482
- api_details,
483
- err.details(),
484
- )
485
- raise
468
+ except grpc.aio.AioRpcError as grpc_error:
469
+ raise ApiClientError.from_grpc_error(
470
+ server_url=self._server_url,
471
+ operation="AddInclusionBounds",
472
+ grpc_error=grpc_error,
473
+ ) from grpc_error