frequenz-client-microgrid 0.3.0__tar.gz → 0.4.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.4.0}/PKG-INFO +1 -1
  2. frequenz-client-microgrid-0.4.0/RELEASE_NOTES.md +60 -0
  3. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/pyproject.toml +5 -10
  4. frequenz-client-microgrid-0.4.0/src/frequenz/client/microgrid/__init__.py +113 -0
  5. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/src/frequenz/client/microgrid/_client.py +110 -143
  6. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/src/frequenz/client/microgrid/_component.py +21 -26
  7. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/src/frequenz/client/microgrid/_component_data.py +35 -37
  8. frequenz-client-microgrid-0.4.0/src/frequenz/client/microgrid/_component_error.py +213 -0
  9. frequenz-client-microgrid-0.4.0/src/frequenz/client/microgrid/_component_states.py +255 -0
  10. frequenz-client-microgrid-0.4.0/src/frequenz/client/microgrid/_exception.py +582 -0
  11. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/src/frequenz_client_microgrid.egg-info/PKG-INFO +1 -1
  12. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/src/frequenz_client_microgrid.egg-info/SOURCES.txt +2 -0
  13. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/src/frequenz_client_microgrid.egg-info/requires.txt +4 -5
  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.4.0}/LICENSE +0 -0
  18. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/MANIFEST.in +0 -0
  19. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/README.md +0 -0
  20. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/setup.cfg +0 -0
  21. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/src/frequenz/client/microgrid/_connection.py +0 -0
  22. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/src/frequenz/client/microgrid/_constants.py +0 -0
  23. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/src/frequenz/client/microgrid/_metadata.py +0 -0
  24. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/src/frequenz/client/microgrid/conftest.py +0 -0
  25. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/src/frequenz/client/microgrid/py.typed +0 -0
  26. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.0}/src/frequenz_client_microgrid.egg-info/dependency_links.txt +0 -0
  27. {frequenz-client-microgrid-0.3.0 → frequenz-client-microgrid-0.4.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.4.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,60 @@
1
+ # Frequenz Microgrid API Client Release Notes
2
+
3
+ ## Summary
4
+
5
+ This release migrates to use `betterproto` and `grpclib` instead of `grpcio` and `protobuf` internally. It also stops *leaking* these internal libraries to downstream users. It should now be possible to use the client without having to use `grpclib` or `betterproto` directly.
6
+
7
+ ## Upgrading
8
+
9
+ - The client now uses a string URL to connect to the server, the `grpc_channel` and `target` arguments are now replaced by `server_url`. The current accepted format is `grpc://hostname[:<port:int=9090>][?ssl=<ssl:bool=false>]`, meaning that the `port` and `ssl` are optional and default to 9090 and `false` respectively. You will have to adapt the way you connect to the server in your code.
10
+
11
+ - The client is now using [`grpclib`](https://pypi.org/project/grpclib/) to connect to the server instead of [`grpcio`](https://pypi.org/project/grpcio/). You might need to adapt your code if you are using `grpcio` directly.
12
+
13
+ - The client now doesn't raise `grpc.aio.RpcError` exceptions anymore. Instead, it raises its own exceptions, one per gRPC error status code, all inheriting from `GrpcError`, which in turn inherits from `ClientError` (as any other exception raised by this library in the future). `GrpcError`s have the `grpclib.GRPCError` as their `__cause__`. You might need to adapt your error handling code to catch these specific exceptions instead of `grpc.aio.RpcError`.
14
+
15
+ You can also access the underlying `grpclib.GRPCError` using the `grpc_error` attribute for `GrpStatusError` exceptions, but it is discouraged because it makes downstream projects dependant on `grpclib` too
16
+
17
+ - The client now uses protobuf/grpc bindings generated [betterproto](https://github.com/danielgtaylor/python-betterproto) ([frequenz-microgrid-betterproto](https://github.com/frequenz-floss/frequenz-microgrid-betterproto-python)) instead of [grpcio](https://pypi.org/project/grpcio/) ([frequenz-api-microgrid](https://github.com/frequenz-floss/frequenz-api-microgrid)). If you were using the bindings directly, you might need to do some minor adjustments to your code.
18
+
19
+ - If an unknown EV charger component state is received, it will now be set to `EVChargerComponentState.UNKNOWN` instead of `EVChargerComponentState.UNSPECIFIED`.
20
+
21
+ ## New Features
22
+
23
+ - The client now raises more specific exceptions based on the gRPC status code, so you can more easily handle different types of errors.
24
+
25
+ For example:
26
+
27
+ ```python
28
+ try:
29
+ connections = await client.connections()
30
+ except OperationTimedOut:
31
+ ...
32
+ ```
33
+
34
+ instead of:
35
+
36
+ ```python
37
+ try:
38
+ connections = await client.connections()
39
+ except grpc.aio.RpcError as e:
40
+ if e.code() == grpc.StatusCode.DEADLINE_EXCEEDED:
41
+ ...
42
+ ```
43
+
44
+ - We now expose component errors as part of the streamed component data:
45
+
46
+ * `BatteryData.errors`
47
+ * `InverterData.errors`
48
+
49
+ - We now expose component states as part of the streamed component data:
50
+
51
+ * `BatteryData.component_state` and `BatteryData.relay_state`
52
+ * `InverterData.component_state`
53
+
54
+ - Added the missing `EVChargerComponentState.UNKNOWN` state.
55
+
56
+ ## Bug Fixes
57
+
58
+ - Fix a leakage of `GrpcStreamBroadcaster` instances.
59
+ - The user-passed retry strategy was not properly used by the data streaming methods.
60
+ - The client `set_bounds()` method might have not done anything and if it did, errors were not properly raised.
@@ -2,11 +2,7 @@
2
2
  # Copyright © 2024 Frequenz Energy-as-a-Service GmbH
3
3
 
4
4
  [build-system]
5
- requires = [
6
- "setuptools == 68.1.0",
7
- "setuptools_scm[toml] == 7.1.0",
8
- "frequenz-repo-config[lib] == 0.9.1",
9
- ]
5
+ requires = ["setuptools == 68.1.0", "setuptools_scm[toml] == 7.1.0"]
10
6
  build-backend = "setuptools.build_meta"
11
7
 
12
8
  [project]
@@ -36,11 +32,10 @@ classifiers = [
36
32
  ]
37
33
  requires-python = ">= 3.11, < 4"
38
34
  dependencies = [
39
- "frequenz-api-microgrid >= 0.15.3, < 0.16.0",
35
+ "betterproto == 2.0.0b6",
40
36
  "frequenz-channels >= 1.0.0-rc1, < 2.0.0",
41
- "frequenz-client-base >= 0.3.0, < 0.4.0",
42
- "grpcio >= 1.54.2, < 2",
43
- "protobuf >= 4.21.6, < 5",
37
+ "frequenz-client-base[grpclib] >= 0.4.0, < 0.5",
38
+ "frequenz-microgrid-betterproto >= 0.15.3.1, < 0.16",
44
39
  "timezonefinder >= 6.2.0, < 7",
45
40
  "typing-extensions >= 4.5.0, < 5",
46
41
  ]
@@ -76,7 +71,7 @@ dev-mypy = [
76
71
  # For checking the noxfile, docs/ script, and tests
77
72
  "frequenz-client-microgrid[dev-mkdocs,dev-noxfile,dev-pytest]",
78
73
  ]
79
- dev-noxfile = ["nox == 2023.4.22", "frequenz-repo-config[lib] == 0.9.1"]
74
+ dev-noxfile = ["nox == 2024.4.15", "frequenz-repo-config[lib] == 0.9.1"]
80
75
  dev-pylint = [
81
76
  "pylint == 3.1.0",
82
77
  # For checking the noxfile, docs/ script, and tests
@@ -0,0 +1,113 @@
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
+ ClientError,
45
+ DataLoss,
46
+ EntityAlreadyExists,
47
+ EntityNotFound,
48
+ GrpcError,
49
+ InternalError,
50
+ InvalidArgument,
51
+ OperationAborted,
52
+ OperationCancelled,
53
+ OperationNotImplemented,
54
+ OperationOutOfRange,
55
+ OperationPreconditionFailed,
56
+ OperationTimedOut,
57
+ OperationUnauthenticated,
58
+ PermissionDenied,
59
+ ResourceExhausted,
60
+ ServiceUnavailable,
61
+ UnknownError,
62
+ UnrecognizedGrpcStatus,
63
+ )
64
+ from ._metadata import Location, Metadata
65
+
66
+ __all__ = [
67
+ "ApiClient",
68
+ "BatteryComponentState",
69
+ "BatteryData",
70
+ "BatteryError",
71
+ "BatteryErrorCode",
72
+ "BatteryRelayState",
73
+ "ClientError",
74
+ "Component",
75
+ "ComponentCategory",
76
+ "ComponentData",
77
+ "ComponentMetadata",
78
+ "ComponentMetricId",
79
+ "ComponentType",
80
+ "Connection",
81
+ "DataLoss",
82
+ "EVChargerCableState",
83
+ "EVChargerComponentState",
84
+ "EVChargerData",
85
+ "EntityAlreadyExists",
86
+ "EntityNotFound",
87
+ "ErrorLevel",
88
+ "Fuse",
89
+ "GridMetadata",
90
+ "GrpcError",
91
+ "InternalError",
92
+ "InvalidArgument",
93
+ "InverterComponentState",
94
+ "InverterData",
95
+ "InverterError",
96
+ "InverterErrorCode",
97
+ "InverterType",
98
+ "Location",
99
+ "Metadata",
100
+ "MeterData",
101
+ "OperationAborted",
102
+ "OperationCancelled",
103
+ "OperationNotImplemented",
104
+ "OperationOutOfRange",
105
+ "OperationPreconditionFailed",
106
+ "OperationTimedOut",
107
+ "OperationUnauthenticated",
108
+ "PermissionDenied",
109
+ "ResourceExhausted",
110
+ "ServiceUnavailable",
111
+ "UnknownError",
112
+ "UnrecognizedGrpcStatus",
113
+ ]
@@ -5,33 +5,19 @@
5
5
 
6
6
  import asyncio
7
7
  import logging
8
- from collections.abc import Awaitable, Callable, Iterable
9
- from typing import Any, TypeVar, cast
10
-
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
8
+ from collections.abc import Callable, Iterable, Set
9
+ from typing import Any, TypeVar
30
10
 
31
- # pylint: enable=no-name-in-module
11
+ import grpclib
12
+ import grpclib.client
13
+ from betterproto.lib.google import protobuf as pb_google
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 frequenz.microgrid.betterproto.frequenz.api import microgrid as pb_microgrid
17
+ from frequenz.microgrid.betterproto.frequenz.api.common import (
18
+ components as pb_components,
19
+ )
20
+ from frequenz.microgrid.betterproto.frequenz.api.common import metrics as pb_metrics
35
21
 
36
22
  from ._component import (
37
23
  Component,
@@ -49,6 +35,7 @@ from ._component_data import (
49
35
  )
50
36
  from ._connection import Connection
51
37
  from ._constants import RECEIVER_MAX_SIZE
38
+ from ._exception import ClientError
52
39
  from ._metadata import Location, Metadata
53
40
 
54
41
  DEFAULT_GRPC_CALL_TIMEOUT = 60.0
@@ -61,32 +48,41 @@ _logger = logging.getLogger(__name__)
61
48
 
62
49
 
63
50
  class ApiClient:
64
- """Microgrid API client implementation using gRPC as the underlying protocol."""
51
+ """A microgrid API client."""
65
52
 
66
53
  def __init__(
67
54
  self,
68
- grpc_channel: grpc.aio.Channel,
69
- target: str,
70
- retry_strategy: retry.Strategy = retry.LinearBackoff(),
55
+ server_url: str,
56
+ *,
57
+ retry_strategy: retry.Strategy | None = None,
71
58
  ) -> None:
72
59
  """Initialize the class instance.
73
60
 
74
61
  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
62
+ server_url: The location of the microgrid API server in the form of a URL.
63
+ The following format is expected:
64
+ "grpc://hostname{:`port`}{?ssl=`ssl`}",
65
+ where the `port` should be an int between 0 and 65535 (defaulting to
66
+ 9090) and `ssl` should be a boolean (defaulting to `false`).
67
+ For example: `grpc://localhost:1090?ssl=true`.
78
68
  retry_strategy: The retry strategy to use to reconnect when the connection
79
- to the streaming method is lost.
69
+ to the streaming method is lost. By default a linear backoff strategy
70
+ is used.
80
71
  """
81
- self.target = target
82
- """The location (as "host:port") of the microgrid API gRPC server."""
72
+ self._server_url = server_url
73
+ """The location of the microgrid API server as a URL."""
83
74
 
84
- self.api = MicrogridStub(grpc_channel)
75
+ self.api = pb_microgrid.MicrogridStub(channel.parse_grpc_uri(server_url))
85
76
  """The gRPC stub for the microgrid API."""
86
77
 
87
78
  self._broadcasters: dict[int, streaming.GrpcStreamBroadcaster[Any, Any]] = {}
88
79
  self._retry_strategy = retry_strategy
89
80
 
81
+ @property
82
+ def server_url(self) -> str:
83
+ """The server location in URL format."""
84
+ return self._server_url
85
+
90
86
  async def components(self) -> Iterable[Component]:
91
87
  """Fetch all the components present in the microgrid.
92
88
 
@@ -94,38 +90,25 @@ class ApiClient:
94
90
  Iterator whose elements are all the components in the microgrid.
95
91
 
96
92
  Raises:
97
- AioRpcError: if connection to Microgrid API cannot be established or
98
- when the api call exceeded timeout
93
+ ClientError: If the are any errors communicating with the Microgrid API,
94
+ most likely a subclass of
95
+ [GrpcError][frequenz.client.microgrid.GrpcError].
99
96
  """
100
97
  try:
101
- # grpc.aio is missing types and mypy thinks this is not awaitable,
102
- # but it is
103
- component_list = await cast(
104
- Awaitable[PbComponentList],
105
- self.api.ListComponents(
106
- PbComponentFilter(),
107
- timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
108
- ),
98
+ component_list = await self.api.list_components(
99
+ pb_microgrid.ComponentFilter(),
100
+ timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
109
101
  )
102
+ except grpclib.GRPCError as grpc_error:
103
+ raise ClientError.from_grpc_error(
104
+ server_url=self._server_url,
105
+ operation="list_components",
106
+ grpc_error=grpc_error,
107
+ ) from grpc_error
110
108
 
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
109
  components_only = filter(
128
- lambda c: c.category is not PbComponentCategory.COMPONENT_CATEGORY_SENSOR,
110
+ lambda c: c.category
111
+ is not pb_components.ComponentCategory.COMPONENT_CATEGORY_SENSOR,
129
112
  component_list.components,
130
113
  )
131
114
  result: Iterable[Component] = map(
@@ -149,16 +132,13 @@ class ApiClient:
149
132
  Returns:
150
133
  the microgrid metadata.
151
134
  """
152
- microgrid_metadata: PbMicrogridMetadata | None = None
135
+ microgrid_metadata: pb_microgrid.MicrogridMetadata | None = None
153
136
  try:
154
- microgrid_metadata = await cast(
155
- Awaitable[PbMicrogridMetadata],
156
- self.api.GetMicrogridMetadata(
157
- Empty(),
158
- timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
159
- ),
137
+ microgrid_metadata = await self.api.get_microgrid_metadata(
138
+ pb_google.Empty(),
139
+ timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
160
140
  )
161
- except grpc.aio.AioRpcError:
141
+ except grpclib.GRPCError:
162
142
  _logger.exception("The microgrid metadata is not available.")
163
143
 
164
144
  if not microgrid_metadata:
@@ -175,8 +155,8 @@ class ApiClient:
175
155
 
176
156
  async def connections(
177
157
  self,
178
- starts: set[int] | None = None,
179
- ends: set[int] | None = None,
158
+ starts: Set[int] = frozenset(),
159
+ ends: Set[int] = frozenset(),
180
160
  ) -> Iterable[Connection]:
181
161
  """Fetch the connections between components in the microgrid.
182
162
 
@@ -190,33 +170,27 @@ class ApiClient:
190
170
  Microgrid connections matching the provided start and end filters.
191
171
 
192
172
  Raises:
193
- AioRpcError: if connection to Microgrid API cannot be established or
194
- when the api call exceeded timeout
173
+ ClientError: If the are any errors communicating with the Microgrid API,
174
+ most likely a subclass of
175
+ [GrpcError][frequenz.client.microgrid.GrpcError].
195
176
  """
196
- connection_filter = PbConnectionFilter(starts=starts, ends=ends)
177
+ connection_filter = pb_microgrid.ConnectionFilter(
178
+ starts=list(starts), ends=list(ends)
179
+ )
197
180
  try:
198
181
  valid_components, all_connections = await asyncio.gather(
199
182
  self.components(),
200
- # grpc.aio is missing types and mypy thinks this is not
201
- # awaitable, but it is
202
- cast(
203
- Awaitable[PbConnectionList],
204
- self.api.ListConnections(
205
- connection_filter,
206
- timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
207
- ),
183
+ self.api.list_connections(
184
+ connection_filter,
185
+ timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
208
186
  ),
209
187
  )
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
- )
188
+ except grpclib.GRPCError as grpc_error:
189
+ raise ClientError.from_grpc_error(
190
+ server_url=self._server_url,
191
+ operation="list_connections",
192
+ grpc_error=grpc_error,
193
+ ) from grpc_error
220
194
  # Filter out the components filtered in `components` method.
221
195
  # id=0 is an exception indicating grid component.
222
196
  valid_ids = {c.component_id for c in valid_components}
@@ -238,7 +212,7 @@ class ApiClient:
238
212
  *,
239
213
  component_id: int,
240
214
  expected_category: ComponentCategory,
241
- transform: Callable[[PbComponentData], _ComponentDataT],
215
+ transform: Callable[[pb_microgrid.ComponentData], _ComponentDataT],
242
216
  maxsize: int,
243
217
  ) -> Receiver[_ComponentDataT]:
244
218
  """Return a new broadcaster receiver for a given `component_id`.
@@ -261,20 +235,17 @@ class ApiClient:
261
235
  expected_category,
262
236
  )
263
237
 
264
- broadcaster = self._broadcasters.setdefault(
265
- component_id,
266
- streaming.GrpcStreamBroadcaster(
238
+ broadcaster = self._broadcasters.get(component_id)
239
+ if broadcaster is None:
240
+ broadcaster = streaming.GrpcStreamBroadcaster(
267
241
  f"raw-component-data-{component_id}",
268
- # We need to cast here because grpc says StreamComponentData is
269
- # a grpc.CallIterator[PbComponentData], not a
270
- # grpc.aio.UnaryStreamCall[..., PbComponentData].
271
- lambda: cast(
272
- grpc.aio.UnaryStreamCall[Any, PbComponentData],
273
- self.api.StreamComponentData(PbComponentIdParam(id=component_id)),
242
+ lambda: self.api.stream_component_data(
243
+ pb_microgrid.ComponentIdParam(id=component_id)
274
244
  ),
275
245
  transform,
276
- ),
277
- )
246
+ retry_strategy=self._retry_strategy,
247
+ )
248
+ self._broadcasters[component_id] = broadcaster
278
249
  return broadcaster.new_receiver(maxsize=maxsize)
279
250
 
280
251
  async def _expect_category(
@@ -305,8 +276,8 @@ class ApiClient:
305
276
 
306
277
  if comp.category != expected_category:
307
278
  raise ValueError(
308
- f"Component id {component_id} is a {comp.category}"
309
- f", not a {expected_category}."
279
+ f"Component id {component_id} is a {comp.category.name.lower()}"
280
+ f", not a {expected_category.name.lower()}."
310
281
  )
311
282
 
312
283
  async def meter_data( # noqa: DOC502 (ValueError is raised indirectly by _expect_category)
@@ -418,27 +389,23 @@ class ApiClient:
418
389
  power_w: power to set for the component.
419
390
 
420
391
  Raises:
421
- AioRpcError: if connection to Microgrid API cannot be established or
422
- when the api call exceeded timeout
392
+ ClientError: If the are any errors communicating with the Microgrid API,
393
+ most likely a subclass of
394
+ [GrpcError][frequenz.client.microgrid.GrpcError].
423
395
  """
424
396
  try:
425
- await cast(
426
- Awaitable[PbSetPowerActiveParam],
427
- self.api.SetPowerActive(
428
- PbSetPowerActiveParam(component_id=component_id, power=power_w),
429
- timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
397
+ await self.api.set_power_active(
398
+ pb_microgrid.SetPowerActiveParam(
399
+ component_id=component_id, power=power_w
430
400
  ),
401
+ timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
431
402
  )
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
- )
403
+ except grpclib.GRPCError as grpc_error:
404
+ raise ClientError.from_grpc_error(
405
+ server_url=self._server_url,
406
+ operation="set_power_active",
407
+ grpc_error=grpc_error,
408
+ ) from grpc_error
442
409
 
443
410
  async def set_bounds(
444
411
  self,
@@ -446,7 +413,7 @@ class ApiClient:
446
413
  lower: float,
447
414
  upper: float,
448
415
  ) -> None:
449
- """Send `PbSetBoundsParam`s received from a channel to the Microgrid service.
416
+ """Send `SetBoundsParam`s received from a channel to the Microgrid service.
450
417
 
451
418
  Args:
452
419
  component_id: ID of the component to set bounds for.
@@ -456,30 +423,30 @@ class ApiClient:
456
423
  Raises:
457
424
  ValueError: when upper bound is less than 0, or when lower bound is
458
425
  greater than 0.
459
- grpc.aio.AioRpcError: if connection to Microgrid API cannot be established
460
- or when the api call exceeded timeout
426
+ ClientError: If the are any errors communicating with the Microgrid API,
427
+ most likely a subclass of
428
+ [GrpcError][frequenz.client.microgrid.GrpcError].
461
429
  """
462
- api_details = f"Microgrid API: {self.target}."
463
430
  if upper < 0:
464
431
  raise ValueError(f"Upper bound {upper} must be greater than or equal to 0.")
465
432
  if lower > 0:
466
- raise ValueError(f"Lower bound {upper} must be less than or equal to 0.")
433
+ raise ValueError(f"Lower bound {lower} must be less than or equal to 0.")
467
434
 
468
- target_metric = PbSetBoundsParam.TargetMetric.TARGET_METRIC_POWER_ACTIVE
435
+ target_metric = (
436
+ pb_microgrid.SetBoundsParamTargetMetric.TARGET_METRIC_POWER_ACTIVE
437
+ )
469
438
  try:
470
- self.api.AddInclusionBounds(
471
- PbSetBoundsParam(
439
+ await self.api.add_inclusion_bounds(
440
+ pb_microgrid.SetBoundsParam(
472
441
  component_id=component_id,
473
442
  target_metric=target_metric,
474
- bounds=PbBounds(lower=lower, upper=upper),
443
+ bounds=pb_metrics.Bounds(lower=lower, upper=upper),
475
444
  ),
445
+ timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
476
446
  )
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
447
+ except grpclib.GRPCError as grpc_error:
448
+ raise ClientError.from_grpc_error(
449
+ server_url=self._server_url,
450
+ operation="add_inclusion_bounds",
451
+ grpc_error=grpc_error,
452
+ ) from grpc_error