Skip to content

Commit 5454cd6

Browse files
committed
Use protobuf modules instead of an alias per symbol
Now that we disabled `pylint`s `no-name-in-module` we can just use the protobuf modules instead of having to declare one alias per each symbol we need. We did this before just so we only need to use a `pylint` `disable=no-name-in-module` one time in the import instead each time we **used** the symbol. Signed-off-by: Leandro Lucarella <[email protected]>
1 parent c6968c0 commit 5454cd6

File tree

8 files changed

+365
-325
lines changed

8 files changed

+365
-325
lines changed

src/frequenz/client/microgrid/_client.py

Lines changed: 28 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,8 @@
99
from typing import Any, TypeVar, cast
1010

1111
import grpc.aio
12-
from frequenz.api.common.components_pb2 import ComponentCategory as PbComponentCategory
13-
from frequenz.api.common.metrics_pb2 import Bounds as PbBounds
14-
from frequenz.api.microgrid.microgrid_pb2 import ComponentData as PbComponentData
15-
from frequenz.api.microgrid.microgrid_pb2 import ComponentFilter as PbComponentFilter
16-
from frequenz.api.microgrid.microgrid_pb2 import ComponentIdParam as PbComponentIdParam
17-
from frequenz.api.microgrid.microgrid_pb2 import ComponentList as PbComponentList
18-
from frequenz.api.microgrid.microgrid_pb2 import ConnectionFilter as PbConnectionFilter
19-
from frequenz.api.microgrid.microgrid_pb2 import ConnectionList as PbConnectionList
20-
from frequenz.api.microgrid.microgrid_pb2 import (
21-
MicrogridMetadata as PbMicrogridMetadata,
22-
)
23-
from frequenz.api.microgrid.microgrid_pb2 import SetBoundsParam as PbSetBoundsParam
24-
from frequenz.api.microgrid.microgrid_pb2 import (
25-
SetPowerActiveParam as PbSetPowerActiveParam,
26-
)
27-
from frequenz.api.microgrid.microgrid_pb2_grpc import MicrogridStub
12+
from frequenz.api.common import components_pb2, metrics_pb2
13+
from frequenz.api.microgrid import microgrid_pb2, microgrid_pb2_grpc
2814
from frequenz.channels import Receiver
2915
from frequenz.client.base import channel, retry, streaming
3016
from google.protobuf.empty_pb2 import Empty
@@ -83,7 +69,7 @@ def __init__(
8369
self._server_url = server_url
8470
"""The location of the microgrid API server as a URL."""
8571

86-
self.api = MicrogridStub(channel.parse_grpc_uri(server_url))
72+
self.api = microgrid_pb2_grpc.MicrogridStub(channel.parse_grpc_uri(server_url))
8773
"""The gRPC stub for the microgrid API."""
8874

8975
self._broadcasters: dict[int, streaming.GrpcStreamBroadcaster[Any, Any]] = {}
@@ -109,9 +95,9 @@ async def components(self) -> Iterable[Component]:
10995
# grpc.aio is missing types and mypy thinks this is not awaitable,
11096
# but it is
11197
component_list = await cast(
112-
Awaitable[PbComponentList],
98+
Awaitable[microgrid_pb2.ComponentList],
11399
self.api.ListComponents(
114-
PbComponentFilter(),
100+
microgrid_pb2.ComponentFilter(),
115101
timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
116102
),
117103
)
@@ -123,7 +109,8 @@ async def components(self) -> Iterable[Component]:
123109
) from grpc_error
124110

125111
components_only = filter(
126-
lambda c: c.category is not PbComponentCategory.COMPONENT_CATEGORY_SENSOR,
112+
lambda c: c.category
113+
is not components_pb2.ComponentCategory.COMPONENT_CATEGORY_SENSOR,
127114
component_list.components,
128115
)
129116
result: Iterable[Component] = map(
@@ -147,10 +134,10 @@ async def metadata(self) -> Metadata:
147134
Returns:
148135
the microgrid metadata.
149136
"""
150-
microgrid_metadata: PbMicrogridMetadata | None = None
137+
microgrid_metadata: microgrid_pb2.MicrogridMetadata | None = None
151138
try:
152139
microgrid_metadata = await cast(
153-
Awaitable[PbMicrogridMetadata],
140+
Awaitable[microgrid_pb2.MicrogridMetadata],
154141
self.api.GetMicrogridMetadata(
155142
Empty(),
156143
timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
@@ -192,14 +179,14 @@ async def connections(
192179
most likely a subclass of
193180
[GrpcError][frequenz.client.microgrid.GrpcError].
194181
"""
195-
connection_filter = PbConnectionFilter(starts=starts, ends=ends)
182+
connection_filter = microgrid_pb2.ConnectionFilter(starts=starts, ends=ends)
196183
try:
197184
valid_components, all_connections = await asyncio.gather(
198185
self.components(),
199186
# grpc.aio is missing types and mypy thinks this is not
200187
# awaitable, but it is
201188
cast(
202-
Awaitable[PbConnectionList],
189+
Awaitable[microgrid_pb2.ConnectionList],
203190
self.api.ListConnections(
204191
connection_filter,
205192
timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
@@ -233,7 +220,7 @@ async def _new_component_data_receiver(
233220
*,
234221
component_id: int,
235222
expected_category: ComponentCategory,
236-
transform: Callable[[PbComponentData], _ComponentDataT],
223+
transform: Callable[[microgrid_pb2.ComponentData], _ComponentDataT],
237224
maxsize: int,
238225
) -> Receiver[_ComponentDataT]:
239226
"""Return a new broadcaster receiver for a given `component_id`.
@@ -261,12 +248,14 @@ async def _new_component_data_receiver(
261248
broadcaster = streaming.GrpcStreamBroadcaster(
262249
f"raw-component-data-{component_id}",
263250
# We need to cast here because grpc says StreamComponentData is
264-
# a grpc.CallIterator[PbComponentData] which is not an AsyncIterator,
265-
# but it is a grpc.aio.UnaryStreamCall[..., PbComponentData], which it
266-
# is.
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.
267254
lambda: cast(
268-
AsyncIterator[PbComponentData],
269-
self.api.StreamComponentData(PbComponentIdParam(id=component_id)),
255+
AsyncIterator[microgrid_pb2.ComponentData],
256+
self.api.StreamComponentData(
257+
microgrid_pb2.ComponentIdParam(id=component_id)
258+
),
270259
),
271260
transform,
272261
retry_strategy=self._retry_strategy,
@@ -423,7 +412,9 @@ async def set_power(self, component_id: int, power_w: float) -> None:
423412
await cast(
424413
Awaitable[Empty],
425414
self.api.SetPowerActive(
426-
PbSetPowerActiveParam(component_id=component_id, power=power_w),
415+
microgrid_pb2.SetPowerActiveParam(
416+
component_id=component_id, power=power_w
417+
),
427418
timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
428419
),
429420
)
@@ -440,7 +431,7 @@ async def set_bounds(
440431
lower: float,
441432
upper: float,
442433
) -> None:
443-
"""Send `PbSetBoundsParam`s received from a channel to the Microgrid service.
434+
"""Send `SetBoundsParam`s received from a channel to the Microgrid service.
444435
445436
Args:
446437
component_id: ID of the component to set bounds for.
@@ -459,15 +450,17 @@ async def set_bounds(
459450
if lower > 0:
460451
raise ValueError(f"Lower bound {lower} must be less than or equal to 0.")
461452

462-
target_metric = PbSetBoundsParam.TargetMetric.TARGET_METRIC_POWER_ACTIVE
453+
target_metric = (
454+
microgrid_pb2.SetBoundsParam.TargetMetric.TARGET_METRIC_POWER_ACTIVE
455+
)
463456
try:
464457
await cast(
465458
Awaitable[Timestamp],
466459
self.api.AddInclusionBounds(
467-
PbSetBoundsParam(
460+
microgrid_pb2.SetBoundsParam(
468461
component_id=component_id,
469462
target_metric=target_metric,
470-
bounds=PbBounds(lower=lower, upper=upper),
463+
bounds=metrics_pb2.Bounds(lower=lower, upper=upper),
471464
),
472465
timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
473466
),

src/frequenz/client/microgrid/_component.py

Lines changed: 24 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,8 @@
66
from dataclasses import dataclass
77
from enum import Enum
88

9-
from frequenz.api.common.components_pb2 import ComponentCategory as PbComponentCategory
10-
from frequenz.api.microgrid.grid_pb2 import Metadata as PbGridMetadata
11-
from frequenz.api.microgrid.inverter_pb2 import Metadata as PbInverterMetadata
12-
from frequenz.api.microgrid.inverter_pb2 import Type as PbInverterType
9+
from frequenz.api.common import components_pb2
10+
from frequenz.api.microgrid import grid_pb2, inverter_pb2
1311

1412

1513
class ComponentType(Enum):
@@ -19,22 +17,22 @@ class ComponentType(Enum):
1917
class InverterType(ComponentType):
2018
"""Enum representing inverter types."""
2119

22-
NONE = PbInverterType.TYPE_UNSPECIFIED
20+
NONE = inverter_pb2.Type.TYPE_UNSPECIFIED
2321
"""Unspecified inverter type."""
2422

25-
BATTERY = PbInverterType.TYPE_BATTERY
23+
BATTERY = inverter_pb2.Type.TYPE_BATTERY
2624
"""Battery inverter."""
2725

28-
SOLAR = PbInverterType.TYPE_SOLAR
26+
SOLAR = inverter_pb2.Type.TYPE_SOLAR
2927
"""Solar inverter."""
3028

31-
HYBRID = PbInverterType.TYPE_HYBRID
29+
HYBRID = inverter_pb2.Type.TYPE_HYBRID
3230
"""Hybrid inverter."""
3331

3432

3533
def component_type_from_protobuf(
36-
component_category: PbComponentCategory.ValueType,
37-
component_metadata: PbInverterMetadata,
34+
component_category: components_pb2.ComponentCategory.ValueType,
35+
component_metadata: inverter_pb2.Metadata,
3836
) -> ComponentType | None:
3937
"""Convert a protobuf InverterType message to Component enum.
4038
@@ -50,7 +48,10 @@ def component_type_from_protobuf(
5048
# ComponentType values in the protobuf definition are not unique across categories
5149
# as of v0.11.0, so we need to check the component category first, before doing any
5250
# component type checks.
53-
if component_category == PbComponentCategory.COMPONENT_CATEGORY_INVERTER:
51+
if (
52+
component_category
53+
== components_pb2.ComponentCategory.COMPONENT_CATEGORY_INVERTER
54+
):
5455
if not any(int(t.value) == int(component_metadata.type) for t in InverterType):
5556
return None
5657

@@ -62,30 +63,30 @@ def component_type_from_protobuf(
6263
class ComponentCategory(Enum):
6364
"""Possible types of microgrid component."""
6465

65-
NONE = PbComponentCategory.COMPONENT_CATEGORY_UNSPECIFIED
66+
NONE = components_pb2.ComponentCategory.COMPONENT_CATEGORY_UNSPECIFIED
6667
"""Unspecified component category."""
6768

68-
GRID = PbComponentCategory.COMPONENT_CATEGORY_GRID
69+
GRID = components_pb2.ComponentCategory.COMPONENT_CATEGORY_GRID
6970
"""Grid component."""
7071

71-
METER = PbComponentCategory.COMPONENT_CATEGORY_METER
72+
METER = components_pb2.ComponentCategory.COMPONENT_CATEGORY_METER
7273
"""Meter component."""
7374

74-
INVERTER = PbComponentCategory.COMPONENT_CATEGORY_INVERTER
75+
INVERTER = components_pb2.ComponentCategory.COMPONENT_CATEGORY_INVERTER
7576
"""Inverter component."""
7677

77-
BATTERY = PbComponentCategory.COMPONENT_CATEGORY_BATTERY
78+
BATTERY = components_pb2.ComponentCategory.COMPONENT_CATEGORY_BATTERY
7879
"""Battery component."""
7980

80-
EV_CHARGER = PbComponentCategory.COMPONENT_CATEGORY_EV_CHARGER
81+
EV_CHARGER = components_pb2.ComponentCategory.COMPONENT_CATEGORY_EV_CHARGER
8182
"""EV charger component."""
8283

83-
CHP = PbComponentCategory.COMPONENT_CATEGORY_CHP
84+
CHP = components_pb2.ComponentCategory.COMPONENT_CATEGORY_CHP
8485
"""CHP component."""
8586

8687

8788
def component_category_from_protobuf(
88-
component_category: PbComponentCategory.ValueType,
89+
component_category: components_pb2.ComponentCategory.ValueType,
8990
) -> ComponentCategory:
9091
"""Convert a protobuf ComponentCategory message to ComponentCategory enum.
9192
@@ -102,7 +103,7 @@ def component_category_from_protobuf(
102103
a valid component category as it does not form part of the
103104
microgrid itself)
104105
"""
105-
if component_category == PbComponentCategory.COMPONENT_CATEGORY_SENSOR:
106+
if component_category == components_pb2.ComponentCategory.COMPONENT_CATEGORY_SENSOR:
106107
raise ValueError("Cannot create a component from a sensor!")
107108

108109
if not any(t.value == component_category for t in ComponentCategory):
@@ -133,8 +134,8 @@ class GridMetadata(ComponentMetadata):
133134

134135

135136
def component_metadata_from_protobuf(
136-
component_category: PbComponentCategory.ValueType,
137-
component_metadata: PbGridMetadata,
137+
component_category: components_pb2.ComponentCategory.ValueType,
138+
component_metadata: grid_pb2.Metadata,
138139
) -> GridMetadata | None:
139140
"""Convert a protobuf GridMetadata message to GridMetadata class.
140141
@@ -147,7 +148,7 @@ def component_metadata_from_protobuf(
147148
Returns:
148149
GridMetadata instance corresponding to the protobuf message.
149150
"""
150-
if component_category == PbComponentCategory.COMPONENT_CATEGORY_GRID:
151+
if component_category == components_pb2.ComponentCategory.COMPONENT_CATEGORY_GRID:
151152
max_current = component_metadata.rated_fuse_current
152153
fuse = Fuse(max_current)
153154
return GridMetadata(fuse)

src/frequenz/client/microgrid/_component_data.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from datetime import datetime, timezone
99
from typing import Self
1010

11-
from frequenz.api.microgrid.microgrid_pb2 import ComponentData as PbComponentData
11+
from frequenz.api.microgrid import microgrid_pb2
1212

1313
from ._component_error import BatteryError, InverterError
1414
from ._component_states import (
@@ -35,10 +35,10 @@ class ComponentData(ABC):
3535
# data from a protobuf message. The whole protobuf message is stored as the `raw`
3636
# attribute. When `ComponentData` is not instantiated from a protobuf message,
3737
# i.e. using the constructor, `raw` will be set to `None`.
38-
raw: PbComponentData | None = field(default=None, init=False)
38+
raw: microgrid_pb2.ComponentData | None = field(default=None, init=False)
3939
"""Raw component data as decoded from the wire."""
4040

41-
def _set_raw(self, raw: PbComponentData) -> None:
41+
def _set_raw(self, raw: microgrid_pb2.ComponentData) -> None:
4242
"""Store raw protobuf message.
4343
4444
It is preferred to keep the dataclasses immutable (frozen) and make the `raw`
@@ -52,7 +52,7 @@ def _set_raw(self, raw: PbComponentData) -> None:
5252

5353
@classmethod
5454
@abstractmethod
55-
def from_proto(cls, raw: PbComponentData) -> Self:
55+
def from_proto(cls, raw: microgrid_pb2.ComponentData) -> Self:
5656
"""Create ComponentData from a protobuf message.
5757
5858
Args:
@@ -119,7 +119,7 @@ class MeterData(ComponentData):
119119
"""The AC power frequency in Hertz (Hz)."""
120120

121121
@classmethod
122-
def from_proto(cls, raw: PbComponentData) -> Self:
122+
def from_proto(cls, raw: microgrid_pb2.ComponentData) -> Self:
123123
"""Create MeterData from a protobuf message.
124124
125125
Args:
@@ -236,7 +236,7 @@ class BatteryData(ComponentData): # pylint: disable=too-many-instance-attribute
236236
"""List of errors in protobuf struct."""
237237

238238
@classmethod
239-
def from_proto(cls, raw: PbComponentData) -> Self:
239+
def from_proto(cls, raw: microgrid_pb2.ComponentData) -> Self:
240240
"""Create BatteryData from a protobuf message.
241241
242242
Args:
@@ -374,7 +374,7 @@ class InverterData(ComponentData): # pylint: disable=too-many-instance-attribut
374374
"""List of errors from the component."""
375375

376376
@classmethod
377-
def from_proto(cls, raw: PbComponentData) -> Self:
377+
def from_proto(cls, raw: microgrid_pb2.ComponentData) -> Self:
378378
"""Create InverterData from a protobuf message.
379379
380380
Args:
@@ -530,7 +530,7 @@ class EVChargerData(ComponentData): # pylint: disable=too-many-instance-attribu
530530
"""The state of the ev charger."""
531531

532532
@classmethod
533-
def from_proto(cls, raw: PbComponentData) -> Self:
533+
def from_proto(cls, raw: microgrid_pb2.ComponentData) -> Self:
534534
"""Create EVChargerData from a protobuf message.
535535
536536
Args:

0 commit comments

Comments
 (0)