frequenz-client-microgrid 0.6.1__tar.gz → 0.8.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 (31) hide show
  1. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/PKG-INFO +25 -24
  2. frequenz_client_microgrid-0.8.0/RELEASE_NOTES.md +18 -0
  3. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/pyproject.toml +24 -24
  4. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/__init__.py +3 -1
  5. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_client.py +199 -28
  6. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_component.py +6 -3
  7. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_component_data.py +6 -5
  8. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_connection.py +5 -3
  9. frequenz_client_microgrid-0.8.0/src/frequenz/client/microgrid/_lifetime.py +52 -0
  10. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_metadata.py +3 -1
  11. frequenz_client_microgrid-0.8.0/src/frequenz/client/microgrid/_sensor_proto.py +190 -0
  12. frequenz_client_microgrid-0.8.0/src/frequenz/client/microgrid/_util.py +47 -0
  13. frequenz_client_microgrid-0.8.0/src/frequenz/client/microgrid/id.py +218 -0
  14. frequenz_client_microgrid-0.8.0/src/frequenz/client/microgrid/metrics.py +61 -0
  15. frequenz_client_microgrid-0.8.0/src/frequenz/client/microgrid/sensor.py +234 -0
  16. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz_client_microgrid.egg-info/PKG-INFO +25 -24
  17. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz_client_microgrid.egg-info/SOURCES.txt +6 -0
  18. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz_client_microgrid.egg-info/requires.txt +22 -22
  19. frequenz_client_microgrid-0.6.1/RELEASE_NOTES.md +0 -5
  20. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/LICENSE +0 -0
  21. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/MANIFEST.in +0 -0
  22. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/README.md +0 -0
  23. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/setup.cfg +0 -0
  24. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_component_error.py +0 -0
  25. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_component_states.py +0 -0
  26. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_constants.py +0 -0
  27. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_exception.py +0 -0
  28. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/conftest.py +0 -0
  29. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/py.typed +0 -0
  30. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz_client_microgrid.egg-info/dependency_links.txt +0 -0
  31. {frequenz_client_microgrid-0.6.1 → frequenz_client_microgrid-0.8.0}/src/frequenz_client_microgrid.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: frequenz-client-microgrid
3
- Version: 0.6.1
3
+ Version: 0.8.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
@@ -24,50 +24,51 @@ License-File: LICENSE
24
24
  Requires-Dist: frequenz-api-microgrid<0.16.0,>=0.15.3
25
25
  Requires-Dist: frequenz-channels<2.0.0,>=1.0.0-rc1
26
26
  Requires-Dist: frequenz-client-base<0.10.0,>=0.8.0
27
- Requires-Dist: grpcio<2,>=1.54.2
28
- Requires-Dist: protobuf<6,>=4.21.6
27
+ Requires-Dist: grpcio<2,>=1.59.0
28
+ Requires-Dist: protobuf<7,>=4.21.6
29
29
  Requires-Dist: timezonefinder<7,>=6.2.0
30
- Requires-Dist: typing-extensions<5,>=4.5.0
30
+ Requires-Dist: typing-extensions<5,>=4.6.0
31
31
  Provides-Extra: dev-flake8
32
- Requires-Dist: flake8==7.1.1; extra == "dev-flake8"
32
+ Requires-Dist: flake8==7.2.0; extra == "dev-flake8"
33
33
  Requires-Dist: flake8-docstrings==1.7.0; extra == "dev-flake8"
34
34
  Requires-Dist: flake8-pyproject==1.2.3; extra == "dev-flake8"
35
- Requires-Dist: pydoclint==0.6.0; extra == "dev-flake8"
35
+ Requires-Dist: pydoclint==0.6.6; extra == "dev-flake8"
36
36
  Requires-Dist: pydocstyle==6.3.0; extra == "dev-flake8"
37
37
  Provides-Extra: dev-formatting
38
38
  Requires-Dist: black==25.1.0; extra == "dev-formatting"
39
- Requires-Dist: isort==6.0.0; extra == "dev-formatting"
39
+ Requires-Dist: isort==6.0.1; extra == "dev-formatting"
40
40
  Provides-Extra: dev-mkdocs
41
41
  Requires-Dist: black==25.1.0; extra == "dev-mkdocs"
42
- Requires-Dist: Markdown==3.7; extra == "dev-mkdocs"
42
+ Requires-Dist: Markdown==3.8; extra == "dev-mkdocs"
43
43
  Requires-Dist: mike==2.1.3; extra == "dev-mkdocs"
44
44
  Requires-Dist: mkdocs-gen-files==0.5.0; extra == "dev-mkdocs"
45
- Requires-Dist: mkdocs-literate-nav==0.6.1; extra == "dev-mkdocs"
45
+ Requires-Dist: mkdocs-literate-nav==0.6.2; extra == "dev-mkdocs"
46
46
  Requires-Dist: mkdocs-macros-plugin==1.3.7; extra == "dev-mkdocs"
47
- Requires-Dist: mkdocs-material==9.6.2; extra == "dev-mkdocs"
48
- Requires-Dist: mkdocstrings[python]==0.28.0; extra == "dev-mkdocs"
49
- Requires-Dist: mkdocstrings-python==1.14.6; extra == "dev-mkdocs"
50
- Requires-Dist: frequenz-repo-config[lib]==0.12.2; extra == "dev-mkdocs"
47
+ Requires-Dist: mkdocs-material==9.6.12; extra == "dev-mkdocs"
48
+ Requires-Dist: mkdocstrings[python]==0.29.1; extra == "dev-mkdocs"
49
+ Requires-Dist: mkdocstrings-python==1.16.10; extra == "dev-mkdocs"
50
+ Requires-Dist: frequenz-repo-config[lib]==0.13.3; extra == "dev-mkdocs"
51
51
  Provides-Extra: dev-mypy
52
- Requires-Dist: mypy==1.14.1; extra == "dev-mypy"
53
- Requires-Dist: grpc-stubs==1.53.0.5; extra == "dev-mypy"
54
- Requires-Dist: types-Markdown==3.7.0.20241204; extra == "dev-mypy"
55
- Requires-Dist: types-protobuf==5.29.1.20241207; extra == "dev-mypy"
52
+ Requires-Dist: mypy==1.15.0; extra == "dev-mypy"
53
+ Requires-Dist: grpc-stubs==1.53.0.6; extra == "dev-mypy"
54
+ Requires-Dist: types-Markdown==3.8.0.20250415; extra == "dev-mypy"
55
+ Requires-Dist: types-protobuf==5.29.1.20250403; extra == "dev-mypy"
56
56
  Requires-Dist: frequenz-client-microgrid[dev-mkdocs,dev-noxfile,dev-pytest]; extra == "dev-mypy"
57
57
  Provides-Extra: dev-noxfile
58
- Requires-Dist: nox==2024.10.9; extra == "dev-noxfile"
59
- Requires-Dist: frequenz-repo-config[lib]==0.12.2; extra == "dev-noxfile"
58
+ Requires-Dist: nox==2025.5.1; extra == "dev-noxfile"
59
+ Requires-Dist: frequenz-repo-config[lib]==0.13.3; extra == "dev-noxfile"
60
60
  Provides-Extra: dev-pylint
61
- Requires-Dist: pylint==3.3.4; extra == "dev-pylint"
61
+ Requires-Dist: pylint==3.3.6; extra == "dev-pylint"
62
62
  Requires-Dist: frequenz-client-microgrid[dev-mkdocs,dev-noxfile,dev-pytest]; extra == "dev-pylint"
63
63
  Provides-Extra: dev-pytest
64
- Requires-Dist: pytest==8.3.4; extra == "dev-pytest"
65
- Requires-Dist: frequenz-repo-config[extra-lint-examples]==0.12.2; extra == "dev-pytest"
64
+ Requires-Dist: pytest==8.3.5; extra == "dev-pytest"
65
+ Requires-Dist: frequenz-repo-config[extra-lint-examples]==0.13.3; extra == "dev-pytest"
66
66
  Requires-Dist: pytest-mock==3.14.0; extra == "dev-pytest"
67
- Requires-Dist: pytest-asyncio==0.25.3; extra == "dev-pytest"
67
+ Requires-Dist: pytest-asyncio==0.26.0; extra == "dev-pytest"
68
68
  Requires-Dist: async-solipsism==0.7; extra == "dev-pytest"
69
69
  Provides-Extra: dev
70
70
  Requires-Dist: frequenz-client-microgrid[dev-flake8,dev-formatting,dev-mkdocs,dev-mypy,dev-noxfile,dev-pylint,dev-pytest]; extra == "dev"
71
+ Dynamic: license-file
71
72
 
72
73
  # Frequenz Microgrid API Client
73
74
 
@@ -0,0 +1,18 @@
1
+ # Frequenz Microgrid API Client Release Notes
2
+
3
+ ## Summary
4
+
5
+ This release introduces sensors support and adds official support for Python 3.12. It also includes some bug fixes.
6
+
7
+ ## Upgrading
8
+
9
+ - Some minimum versions of dependencies have been bumped to support Python 3.12. You might also need to bump these dependencies in your project.
10
+
11
+ ## New Features
12
+
13
+ - The `MicrogridApiClient` can now list sensor retrieving their metadata (`list_sensors()`) and can stream sensor data (`stream_sensor_data()`).
14
+
15
+ ## Bug Fixes
16
+
17
+ - When retrieving the microgrid metadata using `metadata()`, if the location was empty in the protobuf message, a wrong location with long=0, lat=0 was used. Now the location will be properly set to `None` in that case.
18
+ - The client now does some missing cleanup (stopping background tasks) when disconnecting (and when used as a context manager).
@@ -3,9 +3,9 @@
3
3
 
4
4
  [build-system]
5
5
  requires = [
6
- "setuptools == 75.8.0",
7
- "setuptools_scm[toml] == 8.1.0",
8
- "frequenz-repo-config[lib] == 0.12.2",
6
+ "setuptools == 80.3.1",
7
+ "setuptools_scm[toml] == 8.3.1",
8
+ "frequenz-repo-config[lib] == 0.13.3",
9
9
  ]
10
10
  build-backend = "setuptools.build_meta"
11
11
 
@@ -39,10 +39,10 @@ dependencies = [
39
39
  "frequenz-api-microgrid >= 0.15.3, < 0.16.0",
40
40
  "frequenz-channels >= 1.0.0-rc1, < 2.0.0",
41
41
  "frequenz-client-base >= 0.8.0, < 0.10.0",
42
- "grpcio >= 1.54.2, < 2",
43
- "protobuf >= 4.21.6, < 6",
42
+ "grpcio >= 1.59.0, < 2",
43
+ "protobuf >= 4.21.6, < 7",
44
44
  "timezonefinder >= 6.2.0, < 7",
45
- "typing-extensions >= 4.5.0, < 5",
45
+ "typing-extensions >= 4.6.0, < 5",
46
46
  ]
47
47
  dynamic = ["version"]
48
48
 
@@ -52,44 +52,44 @@ email = "floss@frequenz.com"
52
52
 
53
53
  [project.optional-dependencies]
54
54
  dev-flake8 = [
55
- "flake8 == 7.1.1",
55
+ "flake8 == 7.2.0",
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.6.0",
58
+ "pydoclint == 0.6.6",
59
59
  "pydocstyle == 6.3.0",
60
60
  ]
61
- dev-formatting = ["black == 25.1.0", "isort == 6.0.0"]
61
+ dev-formatting = ["black == 25.1.0", "isort == 6.0.1"]
62
62
  dev-mkdocs = [
63
63
  "black == 25.1.0",
64
- "Markdown==3.7",
64
+ "Markdown==3.8",
65
65
  "mike == 2.1.3",
66
66
  "mkdocs-gen-files == 0.5.0",
67
- "mkdocs-literate-nav == 0.6.1",
67
+ "mkdocs-literate-nav == 0.6.2",
68
68
  "mkdocs-macros-plugin == 1.3.7",
69
- "mkdocs-material == 9.6.2",
70
- "mkdocstrings[python] == 0.28.0",
71
- "mkdocstrings-python == 1.14.6",
72
- "frequenz-repo-config[lib] == 0.12.2",
69
+ "mkdocs-material == 9.6.12",
70
+ "mkdocstrings[python] == 0.29.1",
71
+ "mkdocstrings-python == 1.16.10",
72
+ "frequenz-repo-config[lib] == 0.13.3",
73
73
  ]
74
74
  dev-mypy = [
75
- "mypy == 1.14.1",
76
- "grpc-stubs == 1.53.0.5",
77
- "types-Markdown == 3.7.0.20241204",
78
- "types-protobuf == 5.29.1.20241207",
75
+ "mypy == 1.15.0",
76
+ "grpc-stubs == 1.53.0.6",
77
+ "types-Markdown == 3.8.0.20250415",
78
+ "types-protobuf == 5.29.1.20250403",
79
79
  # For checking the noxfile, docs/ script, and tests
80
80
  "frequenz-client-microgrid[dev-mkdocs,dev-noxfile,dev-pytest]",
81
81
  ]
82
- dev-noxfile = ["nox == 2024.10.9", "frequenz-repo-config[lib] == 0.12.2"]
82
+ dev-noxfile = ["nox == 2025.5.1", "frequenz-repo-config[lib] == 0.13.3"]
83
83
  dev-pylint = [
84
- "pylint == 3.3.4",
84
+ "pylint == 3.3.6",
85
85
  # For checking the noxfile, docs/ script, and tests
86
86
  "frequenz-client-microgrid[dev-mkdocs,dev-noxfile,dev-pytest]",
87
87
  ]
88
88
  dev-pytest = [
89
- "pytest == 8.3.4",
90
- "frequenz-repo-config[extra-lint-examples] == 0.12.2",
89
+ "pytest == 8.3.5",
90
+ "frequenz-repo-config[extra-lint-examples] == 0.13.3",
91
91
  "pytest-mock == 3.14.0",
92
- "pytest-asyncio == 0.25.3",
92
+ "pytest-asyncio == 0.26.0",
93
93
  "async-solipsism == 0.7",
94
94
  ]
95
95
  dev = [
@@ -62,10 +62,10 @@ from ._exception import (
62
62
  UnknownError,
63
63
  UnrecognizedGrpcStatus,
64
64
  )
65
+ from ._lifetime import Lifetime
65
66
  from ._metadata import Location, Metadata
66
67
 
67
68
  __all__ = [
68
- "MicrogridApiClient",
69
69
  "ApiClientError",
70
70
  "BatteryComponentState",
71
71
  "BatteryData",
@@ -97,9 +97,11 @@ __all__ = [
97
97
  "InverterError",
98
98
  "InverterErrorCode",
99
99
  "InverterType",
100
+ "Lifetime",
100
101
  "Location",
101
102
  "Metadata",
102
103
  "MeterData",
104
+ "MicrogridApiClient",
103
105
  "OperationAborted",
104
106
  "OperationCancelled",
105
107
  "OperationNotImplemented",
@@ -6,16 +6,19 @@
6
6
  from __future__ import annotations
7
7
 
8
8
  import asyncio
9
+ import itertools
9
10
  import logging
10
11
  from collections.abc import Callable, Iterable, Set
11
12
  from dataclasses import replace
12
- from typing import Any, TypeVar
13
+ from functools import partial
14
+ from typing import Any, NotRequired, TypedDict, TypeVar, assert_never
13
15
 
14
16
  from frequenz.api.common import components_pb2, metrics_pb2
15
- from frequenz.api.microgrid import microgrid_pb2, microgrid_pb2_grpc
17
+ from frequenz.api.microgrid import microgrid_pb2, microgrid_pb2_grpc, sensor_pb2
16
18
  from frequenz.channels import Receiver
17
19
  from frequenz.client.base import channel, client, retry, streaming
18
20
  from google.protobuf.empty_pb2 import Empty
21
+ from typing_extensions import override
19
22
 
20
23
  from ._component import (
21
24
  Component,
@@ -35,6 +38,9 @@ from ._connection import Connection
35
38
  from ._constants import RECEIVER_MAX_SIZE
36
39
  from ._exception import ApiClientError, ClientNotConnected
37
40
  from ._metadata import Location, Metadata
41
+ from ._sensor_proto import sensor_data_samples_from_proto, sensor_from_proto
42
+ from .id import ComponentId, MicrogridId, SensorId
43
+ from .sensor import Sensor, SensorDataSamples, SensorMetric
38
44
 
39
45
  DEFAULT_GRPC_CALL_TIMEOUT = 60.0
40
46
  """The default timeout for gRPC calls made by this client (in seconds)."""
@@ -91,7 +97,15 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
91
97
  connect=connect,
92
98
  channel_defaults=channel_defaults,
93
99
  )
94
- self._broadcasters: dict[int, streaming.GrpcStreamBroadcaster[Any, Any]] = {}
100
+ self._broadcasters: dict[
101
+ ComponentId, streaming.GrpcStreamBroadcaster[Any, Any]
102
+ ] = {}
103
+ self._sensor_data_broadcasters: dict[
104
+ str,
105
+ streaming.GrpcStreamBroadcaster[
106
+ microgrid_pb2.ComponentData, SensorDataSamples
107
+ ],
108
+ ] = {}
95
109
  self._retry_strategy = retry_strategy
96
110
 
97
111
  @property
@@ -105,6 +119,42 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
105
119
  # type-checker, so it can only be used for type hints.
106
120
  return self._stub # type: ignore
107
121
 
122
+ @override
123
+ async def __aexit__(
124
+ self,
125
+ exc_type: type[BaseException] | None,
126
+ exc_val: BaseException | None,
127
+ exc_tb: Any | None,
128
+ ) -> bool | None:
129
+ """Close the gRPC channel and stop all broadcasters."""
130
+ exceptions = list(
131
+ exc
132
+ for exc in await asyncio.gather(
133
+ *(
134
+ broadcaster.stop()
135
+ for broadcaster in itertools.chain(
136
+ self._broadcasters.values(),
137
+ self._sensor_data_broadcasters.values(),
138
+ )
139
+ ),
140
+ return_exceptions=True,
141
+ )
142
+ if isinstance(exc, BaseException)
143
+ )
144
+ self._broadcasters.clear()
145
+ self._sensor_data_broadcasters.clear()
146
+
147
+ result = None
148
+ try:
149
+ result = await super().__aexit__(exc_type, exc_val, exc_tb)
150
+ except Exception as exc: # pylint: disable=broad-except
151
+ exceptions.append(exc)
152
+ if exceptions:
153
+ raise BaseExceptionGroup(
154
+ "Error while disconnecting from the microgrid API", exceptions
155
+ )
156
+ return result
157
+
108
158
  async def components( # noqa: DOC502 (raises ApiClientError indirectly)
109
159
  self,
110
160
  ) -> Iterable[Component]:
@@ -134,7 +184,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
134
184
  )
135
185
  result: Iterable[Component] = map(
136
186
  lambda c: Component(
137
- c.id,
187
+ ComponentId(c.id),
138
188
  component_category_from_protobuf(c.category),
139
189
  component_type_from_protobuf(c.category, c.inverter),
140
190
  component_metadata_from_protobuf(c.category, c.grid),
@@ -144,6 +194,33 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
144
194
 
145
195
  return result
146
196
 
197
+ async def list_sensors( # noqa: DOC502 (raises ApiClientError indirectly)
198
+ self,
199
+ ) -> Iterable[Sensor]:
200
+ """Fetch all the sensors present in the microgrid.
201
+
202
+ Returns:
203
+ Iterator whose elements are all the sensors in the microgrid.
204
+
205
+ Raises:
206
+ ApiClientError: If the are any errors communicating with the Microgrid API,
207
+ most likely a subclass of
208
+ [GrpcError][frequenz.client.microgrid.GrpcError].
209
+ """
210
+ component_list = await client.call_stub_method(
211
+ self,
212
+ lambda: self.stub.ListComponents(
213
+ microgrid_pb2.ComponentFilter(
214
+ categories=[
215
+ components_pb2.ComponentCategory.COMPONENT_CATEGORY_SENSOR
216
+ ]
217
+ ),
218
+ timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
219
+ ),
220
+ method_name="ListComponents",
221
+ )
222
+ return map(sensor_from_proto, component_list.components)
223
+
147
224
  async def metadata(self) -> Metadata:
148
225
  """Fetch the microgrid metadata.
149
226
 
@@ -170,18 +247,20 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
170
247
  return Metadata()
171
248
 
172
249
  location: Location | None = None
173
- if microgrid_metadata.location:
250
+ if microgrid_metadata.HasField("location"):
174
251
  location = Location(
175
252
  latitude=microgrid_metadata.location.latitude,
176
253
  longitude=microgrid_metadata.location.longitude,
177
254
  )
178
255
 
179
- return Metadata(microgrid_id=microgrid_metadata.microgrid_id, location=location)
256
+ return Metadata(
257
+ microgrid_id=MicrogridId(microgrid_metadata.microgrid_id), location=location
258
+ )
180
259
 
181
260
  async def connections( # noqa: DOC502 (raises ApiClientError indirectly)
182
261
  self,
183
- starts: Set[int] = frozenset(),
184
- ends: Set[int] = frozenset(),
262
+ starts: Set[ComponentId] = frozenset(),
263
+ ends: Set[ComponentId] = frozenset(),
185
264
  ) -> Iterable[Connection]:
186
265
  """Fetch the connections between components in the microgrid.
187
266
 
@@ -199,7 +278,13 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
199
278
  most likely a subclass of
200
279
  [GrpcError][frequenz.client.microgrid.GrpcError].
201
280
  """
202
- connection_filter = microgrid_pb2.ConnectionFilter(starts=starts, ends=ends)
281
+ # Convert ComponentId to raw int for the API call
282
+ start_ids = {int(start) for start in starts}
283
+ end_ids = {int(end) for end in ends}
284
+
285
+ connection_filter = microgrid_pb2.ConnectionFilter(
286
+ starts=start_ids, ends=end_ids
287
+ )
203
288
  valid_components, all_connections = await asyncio.gather(
204
289
  self.components(),
205
290
  client.call_stub_method(
@@ -214,7 +299,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
214
299
 
215
300
  # Filter out the components filtered in `components` method.
216
301
  # id=0 is an exception indicating grid component.
217
- valid_ids = {c.component_id for c in valid_components}
302
+ valid_ids = {int(c.component_id) for c in valid_components}
218
303
  valid_ids.add(0)
219
304
 
220
305
  connections = filter(
@@ -223,7 +308,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
223
308
  )
224
309
 
225
310
  result: Iterable[Connection] = map(
226
- lambda c: Connection(c.start, c.end), connections
311
+ lambda c: Connection(ComponentId(c.start), ComponentId(c.end)), connections
227
312
  )
228
313
 
229
314
  return result
@@ -231,7 +316,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
231
316
  async def _new_component_data_receiver(
232
317
  self,
233
318
  *,
234
- component_id: int,
319
+ component_id: ComponentId,
235
320
  expected_category: ComponentCategory,
236
321
  transform: Callable[[microgrid_pb2.ComponentData], _ComponentDataT],
237
322
  maxsize: int,
@@ -262,7 +347,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
262
347
  f"raw-component-data-{component_id}",
263
348
  lambda: aiter(
264
349
  self.stub.StreamComponentData(
265
- microgrid_pb2.ComponentIdParam(id=component_id)
350
+ microgrid_pb2.ComponentIdParam(id=int(component_id))
266
351
  )
267
352
  ),
268
353
  transform,
@@ -276,7 +361,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
276
361
 
277
362
  async def _expect_category(
278
363
  self,
279
- component_id: int,
364
+ component_id: ComponentId,
280
365
  expected_category: ComponentCategory,
281
366
  ) -> None:
282
367
  """Check if the given component_id is of the expected type.
@@ -296,19 +381,17 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
296
381
  if comp.component_id == component_id
297
382
  )
298
383
  except StopIteration as exc:
299
- raise ValueError(
300
- f"Unable to find component with id {component_id}"
301
- ) from exc
384
+ raise ValueError(f"Unable to find {component_id}") from exc
302
385
 
303
386
  if comp.category != expected_category:
304
387
  raise ValueError(
305
- f"Component id {component_id} is a {comp.category.name.lower()}"
388
+ f"{component_id} is a {comp.category.name.lower()}"
306
389
  f", not a {expected_category.name.lower()}."
307
390
  )
308
391
 
309
392
  async def meter_data( # noqa: DOC502 (ValueError is raised indirectly by _expect_category)
310
393
  self,
311
- component_id: int,
394
+ component_id: ComponentId,
312
395
  maxsize: int = RECEIVER_MAX_SIZE,
313
396
  ) -> Receiver[MeterData]:
314
397
  """Return a channel receiver that provides a `MeterData` stream.
@@ -332,7 +415,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
332
415
 
333
416
  async def battery_data( # noqa: DOC502 (ValueError is raised indirectly by _expect_category)
334
417
  self,
335
- component_id: int,
418
+ component_id: ComponentId,
336
419
  maxsize: int = RECEIVER_MAX_SIZE,
337
420
  ) -> Receiver[BatteryData]:
338
421
  """Return a channel receiver that provides a `BatteryData` stream.
@@ -356,7 +439,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
356
439
 
357
440
  async def inverter_data( # noqa: DOC502 (ValueError is raised indirectly by _expect_category)
358
441
  self,
359
- component_id: int,
442
+ component_id: ComponentId,
360
443
  maxsize: int = RECEIVER_MAX_SIZE,
361
444
  ) -> Receiver[InverterData]:
362
445
  """Return a channel receiver that provides an `InverterData` stream.
@@ -380,7 +463,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
380
463
 
381
464
  async def ev_charger_data( # noqa: DOC502 (ValueError is raised indirectly by _expect_category)
382
465
  self,
383
- component_id: int,
466
+ component_id: ComponentId,
384
467
  maxsize: int = RECEIVER_MAX_SIZE,
385
468
  ) -> Receiver[EVChargerData]:
386
469
  """Return a channel receiver that provides an `EvChargeData` stream.
@@ -403,7 +486,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
403
486
  )
404
487
 
405
488
  async def set_power( # noqa: DOC502 (raises ApiClientError indirectly)
406
- self, component_id: int, power_w: float
489
+ self, component_id: ComponentId, power_w: float
407
490
  ) -> None:
408
491
  """Send request to the Microgrid to set power for component.
409
492
 
@@ -425,7 +508,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
425
508
  self,
426
509
  lambda: self.stub.SetPowerActive(
427
510
  microgrid_pb2.SetPowerActiveParam(
428
- component_id=component_id, power=power_w
511
+ component_id=int(component_id), power=power_w
429
512
  ),
430
513
  timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
431
514
  ),
@@ -433,7 +516,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
433
516
  )
434
517
 
435
518
  async def set_reactive_power( # noqa: DOC502 (raises ApiClientError indirectly)
436
- self, component_id: int, reactive_power_var: float
519
+ self, component_id: ComponentId, reactive_power_var: float
437
520
  ) -> None:
438
521
  """Send request to the Microgrid to set reactive power for component.
439
522
 
@@ -453,7 +536,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
453
536
  self,
454
537
  lambda: self.stub.SetPowerReactive(
455
538
  microgrid_pb2.SetPowerReactiveParam(
456
- component_id=component_id, power=reactive_power_var
539
+ component_id=int(component_id), power=reactive_power_var
457
540
  ),
458
541
  timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
459
542
  ),
@@ -462,7 +545,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
462
545
 
463
546
  async def set_bounds( # noqa: DOC503 (raises ApiClientError indirectly)
464
547
  self,
465
- component_id: int,
548
+ component_id: ComponentId,
466
549
  lower: float,
467
550
  upper: float,
468
551
  ) -> None:
@@ -492,7 +575,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
492
575
  self,
493
576
  lambda: self.stub.AddInclusionBounds(
494
577
  microgrid_pb2.SetBoundsParam(
495
- component_id=component_id,
578
+ component_id=int(component_id),
496
579
  target_metric=target_metric,
497
580
  bounds=metrics_pb2.Bounds(lower=lower, upper=upper),
498
581
  ),
@@ -500,3 +583,91 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
500
583
  ),
501
584
  method_name="AddInclusionBounds",
502
585
  )
586
+
587
+ # noqa: DOC502 (Raises ApiClientError indirectly)
588
+ def stream_sensor_data(
589
+ self,
590
+ sensor: SensorId | Sensor,
591
+ metrics: Iterable[SensorMetric | int] | None = None,
592
+ *,
593
+ buffer_size: int = 50,
594
+ ) -> Receiver[SensorDataSamples]:
595
+ """Stream data samples from a sensor.
596
+
597
+ Warning:
598
+ Sensors may not support all metrics. If a sensor does not support
599
+ a given metric, then the returned data stream will not contain that metric.
600
+
601
+ There is no way to tell if a metric is not being received because the
602
+ sensor does not support it or because there is a transient issue when
603
+ retrieving the metric from the sensor.
604
+
605
+ The supported metrics by a sensor can even change with time, for example,
606
+ if a sensor is updated with new firmware.
607
+
608
+ Args:
609
+ sensor: The sensor to stream data from.
610
+ metrics: If not `None`, only the specified metrics will be retrieved.
611
+ Otherwise all available metrics will be retrieved.
612
+ buffer_size: The maximum number of messages to buffer in the returned
613
+ receiver. After this limit is reached, the oldest messages will be
614
+ dropped.
615
+
616
+ Returns:
617
+ A receiver to retrieve data from the sensor.
618
+ """
619
+ sensor_id = _get_sensor_id(sensor)
620
+ key = str(sensor_id)
621
+
622
+ class _ExtraArgs(TypedDict):
623
+ metrics: NotRequired[frozenset[sensor_pb2.SensorMetric.ValueType]]
624
+
625
+ extra_args: _ExtraArgs = {}
626
+ if metrics is not None:
627
+ extra_args["metrics"] = frozenset(
628
+ [_get_sensor_metric_value(m) for m in metrics]
629
+ )
630
+ # We use the frozenset because iterables are not hashable
631
+ key += f"{hash(extra_args['metrics'])}"
632
+
633
+ broadcaster = self._sensor_data_broadcasters.get(key)
634
+ if broadcaster is None:
635
+ client_id = hex(id(self))[2:]
636
+ stream_name = f"microgrid-client-{client_id}-sensor-data-{key}"
637
+ broadcaster = streaming.GrpcStreamBroadcaster(
638
+ stream_name,
639
+ lambda: aiter(
640
+ self.stub.StreamComponentData(
641
+ microgrid_pb2.ComponentIdParam(id=sensor_id),
642
+ timeout=DEFAULT_GRPC_CALL_TIMEOUT,
643
+ )
644
+ ),
645
+ partial(sensor_data_samples_from_proto, **extra_args),
646
+ retry_strategy=self._retry_strategy,
647
+ )
648
+ self._sensor_data_broadcasters[key] = broadcaster
649
+ return broadcaster.new_receiver(maxsize=buffer_size)
650
+
651
+
652
+ def _get_sensor_id(sensor: SensorId | Sensor) -> int:
653
+ """Get the sensor ID from a sensor or sensor ID."""
654
+ match sensor:
655
+ case SensorId():
656
+ return int(sensor)
657
+ case Sensor():
658
+ return int(sensor.id)
659
+ case unexpected:
660
+ assert_never(unexpected)
661
+
662
+
663
+ def _get_sensor_metric_value(
664
+ metric: SensorMetric | int,
665
+ ) -> sensor_pb2.SensorMetric.ValueType:
666
+ """Get the sensor metric ID from a sensor metric or sensor metric ID."""
667
+ match metric:
668
+ case SensorMetric():
669
+ return sensor_pb2.SensorMetric.ValueType(metric.value)
670
+ case int():
671
+ return sensor_pb2.SensorMetric.ValueType(metric)
672
+ case unexpected:
673
+ assert_never(unexpected)
@@ -9,6 +9,8 @@ from enum import Enum
9
9
  from frequenz.api.common import components_pb2
10
10
  from frequenz.api.microgrid import grid_pb2, inverter_pb2
11
11
 
12
+ from .id import ComponentId
13
+
12
14
 
13
15
  class ComponentType(Enum):
14
16
  """A base class from which individual component types are derived."""
@@ -160,7 +162,7 @@ def component_metadata_from_protobuf(
160
162
  class Component:
161
163
  """Metadata for a single microgrid component."""
162
164
 
163
- component_id: int
165
+ component_id: ComponentId
164
166
  """The ID of this component."""
165
167
 
166
168
  category: ComponentCategory
@@ -180,8 +182,9 @@ class Component:
180
182
  == 0` and `type` is `GRID`, `False` otherwise
181
183
  """
182
184
  return (
183
- self.component_id > 0 and any(t == self.category for t in ComponentCategory)
184
- ) or (self.component_id == 0 and self.category == ComponentCategory.GRID)
185
+ int(self.component_id) > 0
186
+ and any(t == self.category for t in ComponentCategory)
187
+ ) or (int(self.component_id) == 0 and self.category == ComponentCategory.GRID)
185
188
 
186
189
  def __hash__(self) -> int:
187
190
  """Compute a hash of this instance, obtained by hashing the `component_id` field.