frequenz-client-microgrid 0.7.0__tar.gz → 0.9.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 (32) hide show
  1. {frequenz_client_microgrid-0.7.0/src/frequenz_client_microgrid.egg-info → frequenz_client_microgrid-0.9.0}/PKG-INFO +27 -25
  2. frequenz_client_microgrid-0.9.0/RELEASE_NOTES.md +14 -0
  3. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/pyproject.toml +35 -26
  4. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/src/frequenz/client/microgrid/__init__.py +2 -3
  5. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/src/frequenz/client/microgrid/_client.py +168 -4
  6. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/src/frequenz/client/microgrid/_component.py +1 -2
  7. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/src/frequenz/client/microgrid/_component_data.py +1 -1
  8. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/src/frequenz/client/microgrid/_connection.py +1 -1
  9. frequenz_client_microgrid-0.9.0/src/frequenz/client/microgrid/_lifetime.py +52 -0
  10. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/src/frequenz/client/microgrid/_metadata.py +1 -2
  11. frequenz_client_microgrid-0.9.0/src/frequenz/client/microgrid/_sensor_proto.py +190 -0
  12. frequenz_client_microgrid-0.9.0/src/frequenz/client/microgrid/_util.py +47 -0
  13. frequenz_client_microgrid-0.9.0/src/frequenz/client/microgrid/metrics.py +61 -0
  14. frequenz_client_microgrid-0.9.0/src/frequenz/client/microgrid/sensor.py +234 -0
  15. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0/src/frequenz_client_microgrid.egg-info}/PKG-INFO +27 -25
  16. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/src/frequenz_client_microgrid.egg-info/SOURCES.txt +5 -1
  17. frequenz_client_microgrid-0.9.0/src/frequenz_client_microgrid.egg-info/requires.txt +56 -0
  18. frequenz_client_microgrid-0.7.0/RELEASE_NOTES.md +0 -14
  19. frequenz_client_microgrid-0.7.0/src/frequenz/client/microgrid/_id.py +0 -107
  20. frequenz_client_microgrid-0.7.0/src/frequenz_client_microgrid.egg-info/requires.txt +0 -55
  21. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/LICENSE +0 -0
  22. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/MANIFEST.in +0 -0
  23. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/README.md +0 -0
  24. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/setup.cfg +0 -0
  25. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/src/frequenz/client/microgrid/_component_error.py +0 -0
  26. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/src/frequenz/client/microgrid/_component_states.py +0 -0
  27. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/src/frequenz/client/microgrid/_constants.py +0 -0
  28. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/src/frequenz/client/microgrid/_exception.py +0 -0
  29. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/src/frequenz/client/microgrid/conftest.py +0 -0
  30. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/src/frequenz/client/microgrid/py.typed +0 -0
  31. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.0}/src/frequenz_client_microgrid.egg-info/dependency_links.txt +0 -0
  32. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.9.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.7.0
3
+ Version: 0.9.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
@@ -21,53 +21,55 @@ Classifier: Typing :: Typed
21
21
  Requires-Python: <4,>=3.11
22
22
  Description-Content-Type: text/markdown
23
23
  License-File: LICENSE
24
- Requires-Dist: frequenz-api-microgrid<0.16.0,>=0.15.3
24
+ Requires-Dist: frequenz-api-microgrid<0.16.0,>=0.15.5
25
25
  Requires-Dist: frequenz-channels<2.0.0,>=1.0.0-rc1
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
26
+ Requires-Dist: frequenz-client-base<0.12.0,>=0.8.0
27
+ Requires-Dist: frequenz-client-common<0.4.0,>=0.3.2
28
+ Requires-Dist: grpcio<2,>=1.63.0
29
+ Requires-Dist: protobuf<7,>=5.26.1
29
30
  Requires-Dist: timezonefinder<7,>=6.2.0
30
- Requires-Dist: typing-extensions<5,>=4.5.0
31
+ Requires-Dist: typing-extensions<5,>=4.13.0
31
32
  Provides-Extra: dev-flake8
32
- Requires-Dist: flake8==7.1.2; extra == "dev-flake8"
33
+ Requires-Dist: flake8==7.2.0; extra == "dev-flake8"
33
34
  Requires-Dist: flake8-docstrings==1.7.0; extra == "dev-flake8"
34
35
  Requires-Dist: flake8-pyproject==1.2.3; extra == "dev-flake8"
35
- Requires-Dist: pydoclint==0.6.2; extra == "dev-flake8"
36
+ Requires-Dist: pydoclint==0.6.6; extra == "dev-flake8"
36
37
  Requires-Dist: pydocstyle==6.3.0; extra == "dev-flake8"
37
38
  Provides-Extra: dev-formatting
38
39
  Requires-Dist: black==25.1.0; extra == "dev-formatting"
39
40
  Requires-Dist: isort==6.0.1; extra == "dev-formatting"
40
41
  Provides-Extra: dev-mkdocs
41
42
  Requires-Dist: black==25.1.0; extra == "dev-mkdocs"
42
- Requires-Dist: Markdown==3.7; extra == "dev-mkdocs"
43
+ Requires-Dist: Markdown==3.8; extra == "dev-mkdocs"
43
44
  Requires-Dist: mike==2.1.3; extra == "dev-mkdocs"
44
45
  Requires-Dist: mkdocs-gen-files==0.5.0; extra == "dev-mkdocs"
45
- Requires-Dist: mkdocs-literate-nav==0.6.1; extra == "dev-mkdocs"
46
+ Requires-Dist: mkdocs-literate-nav==0.6.2; extra == "dev-mkdocs"
46
47
  Requires-Dist: mkdocs-macros-plugin==1.3.7; extra == "dev-mkdocs"
47
- Requires-Dist: mkdocs-material==9.6.7; extra == "dev-mkdocs"
48
- Requires-Dist: mkdocstrings[python]==0.28.2; extra == "dev-mkdocs"
49
- Requires-Dist: mkdocstrings-python==1.16.2; extra == "dev-mkdocs"
50
- Requires-Dist: frequenz-repo-config[lib]==0.12.3; extra == "dev-mkdocs"
48
+ Requires-Dist: mkdocs-material==9.6.14; extra == "dev-mkdocs"
49
+ Requires-Dist: mkdocstrings[python]==0.29.1; extra == "dev-mkdocs"
50
+ Requires-Dist: mkdocstrings-python==1.16.11; extra == "dev-mkdocs"
51
+ Requires-Dist: frequenz-repo-config[lib]==0.13.4; extra == "dev-mkdocs"
51
52
  Provides-Extra: dev-mypy
52
- Requires-Dist: mypy==1.15.0; 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.20250208; extra == "dev-mypy"
53
+ Requires-Dist: mypy==1.16.0; extra == "dev-mypy"
54
+ Requires-Dist: grpc-stubs==1.53.0.6; extra == "dev-mypy"
55
+ Requires-Dist: types-Markdown==3.8.0.20250415; extra == "dev-mypy"
56
+ Requires-Dist: types-protobuf==6.30.2.20250516; extra == "dev-mypy"
56
57
  Requires-Dist: frequenz-client-microgrid[dev-mkdocs,dev-noxfile,dev-pytest]; extra == "dev-mypy"
57
58
  Provides-Extra: dev-noxfile
58
- Requires-Dist: nox==2025.2.9; extra == "dev-noxfile"
59
- Requires-Dist: frequenz-repo-config[lib]==0.12.3; extra == "dev-noxfile"
59
+ Requires-Dist: nox==2025.5.1; extra == "dev-noxfile"
60
+ Requires-Dist: frequenz-repo-config[lib]==0.13.4; extra == "dev-noxfile"
60
61
  Provides-Extra: dev-pylint
61
- Requires-Dist: pylint==3.3.4; extra == "dev-pylint"
62
+ Requires-Dist: pylint==3.3.7; extra == "dev-pylint"
62
63
  Requires-Dist: frequenz-client-microgrid[dev-mkdocs,dev-noxfile,dev-pytest]; extra == "dev-pylint"
63
64
  Provides-Extra: dev-pytest
64
65
  Requires-Dist: pytest==8.3.5; extra == "dev-pytest"
65
- Requires-Dist: frequenz-repo-config[extra-lint-examples]==0.12.3; extra == "dev-pytest"
66
- Requires-Dist: pytest-mock==3.14.0; extra == "dev-pytest"
67
- Requires-Dist: pytest-asyncio==0.25.3; extra == "dev-pytest"
66
+ Requires-Dist: frequenz-repo-config[extra-lint-examples]==0.13.4; extra == "dev-pytest"
67
+ Requires-Dist: pytest-mock==3.14.1; extra == "dev-pytest"
68
+ Requires-Dist: pytest-asyncio==0.26.0; extra == "dev-pytest"
68
69
  Requires-Dist: async-solipsism==0.7; extra == "dev-pytest"
69
70
  Provides-Extra: dev
70
71
  Requires-Dist: frequenz-client-microgrid[dev-flake8,dev-formatting,dev-mkdocs,dev-mypy,dev-noxfile,dev-pylint,dev-pytest]; extra == "dev"
72
+ Dynamic: license-file
71
73
 
72
74
  # Frequenz Microgrid API Client
73
75
 
@@ -0,0 +1,14 @@
1
+ # Frequenz Microgrid API Client Release Notes
2
+
3
+ ## Summary
4
+
5
+ This is a small release to allow for easier interoperability between different APIs.
6
+
7
+ ## Upgrading
8
+
9
+ - Some minimum dependency versions are bumped, so you might need to update your dependencies as well.
10
+ - The IDs (`MicrogridId`, `ComponentId`, `SensorId`) are now imported from `frequenz-client-common`. Please add it to your dependencies if you haven't already, then you can replace your imports:
11
+
12
+ * `from frequenz.client.microgrid import MicrogridId` -> `from frequenz.client.common.microgrid import MicrogridId`
13
+ * `from frequenz.client.microgrid import ComponentId` -> `from frequenz.client.common.microgrid.components import ComponentId`
14
+ * `from frequenz.client.microgrid import SensorId` -> `from frequenz.client.common.microgrid.sensors import SensorId`
@@ -3,9 +3,9 @@
3
3
 
4
4
  [build-system]
5
5
  requires = [
6
- "setuptools == 75.8.2",
7
- "setuptools_scm[toml] == 8.2.0",
8
- "frequenz-repo-config[lib] == 0.12.3",
6
+ "setuptools == 80.9.0",
7
+ "setuptools_scm[toml] == 8.3.1",
8
+ "frequenz-repo-config[lib] == 0.13.4",
9
9
  ]
10
10
  build-backend = "setuptools.build_meta"
11
11
 
@@ -36,13 +36,14 @@ classifiers = [
36
36
  ]
37
37
  requires-python = ">= 3.11, < 4"
38
38
  dependencies = [
39
- "frequenz-api-microgrid >= 0.15.3, < 0.16.0",
39
+ "frequenz-api-microgrid >= 0.15.5, < 0.16.0",
40
40
  "frequenz-channels >= 1.0.0-rc1, < 2.0.0",
41
- "frequenz-client-base >= 0.8.0, < 0.10.0",
42
- "grpcio >= 1.54.2, < 2",
43
- "protobuf >= 4.21.6, < 6",
41
+ "frequenz-client-base >= 0.8.0, < 0.12.0",
42
+ "frequenz-client-common >= 0.3.2, < 0.4.0",
43
+ "grpcio >= 1.63.0, < 2",
44
+ "protobuf >= 5.26.1, < 7",
44
45
  "timezonefinder >= 6.2.0, < 7",
45
- "typing-extensions >= 4.5.0, < 5",
46
+ "typing-extensions >= 4.13.0, < 5",
46
47
  ]
47
48
  dynamic = ["version"]
48
49
 
@@ -52,44 +53,44 @@ email = "floss@frequenz.com"
52
53
 
53
54
  [project.optional-dependencies]
54
55
  dev-flake8 = [
55
- "flake8 == 7.1.2",
56
+ "flake8 == 7.2.0",
56
57
  "flake8-docstrings == 1.7.0",
57
58
  "flake8-pyproject == 1.2.3", # For reading the flake8 config from pyproject.toml
58
- "pydoclint == 0.6.2",
59
+ "pydoclint == 0.6.6",
59
60
  "pydocstyle == 6.3.0",
60
61
  ]
61
62
  dev-formatting = ["black == 25.1.0", "isort == 6.0.1"]
62
63
  dev-mkdocs = [
63
64
  "black == 25.1.0",
64
- "Markdown==3.7",
65
+ "Markdown==3.8",
65
66
  "mike == 2.1.3",
66
67
  "mkdocs-gen-files == 0.5.0",
67
- "mkdocs-literate-nav == 0.6.1",
68
+ "mkdocs-literate-nav == 0.6.2",
68
69
  "mkdocs-macros-plugin == 1.3.7",
69
- "mkdocs-material == 9.6.7",
70
- "mkdocstrings[python] == 0.28.2",
71
- "mkdocstrings-python == 1.16.2",
72
- "frequenz-repo-config[lib] == 0.12.3",
70
+ "mkdocs-material == 9.6.14",
71
+ "mkdocstrings[python] == 0.29.1",
72
+ "mkdocstrings-python == 1.16.11",
73
+ "frequenz-repo-config[lib] == 0.13.4",
73
74
  ]
74
75
  dev-mypy = [
75
- "mypy == 1.15.0",
76
- "grpc-stubs == 1.53.0.5",
77
- "types-Markdown == 3.7.0.20241204",
78
- "types-protobuf == 5.29.1.20250208",
76
+ "mypy == 1.16.0",
77
+ "grpc-stubs == 1.53.0.6",
78
+ "types-Markdown == 3.8.0.20250415",
79
+ "types-protobuf == 6.30.2.20250516",
79
80
  # For checking the noxfile, docs/ script, and tests
80
81
  "frequenz-client-microgrid[dev-mkdocs,dev-noxfile,dev-pytest]",
81
82
  ]
82
- dev-noxfile = ["nox == 2025.2.9", "frequenz-repo-config[lib] == 0.12.3"]
83
+ dev-noxfile = ["nox == 2025.5.1", "frequenz-repo-config[lib] == 0.13.4"]
83
84
  dev-pylint = [
84
- "pylint == 3.3.4",
85
+ "pylint == 3.3.7",
85
86
  # For checking the noxfile, docs/ script, and tests
86
87
  "frequenz-client-microgrid[dev-mkdocs,dev-noxfile,dev-pytest]",
87
88
  ]
88
89
  dev-pytest = [
89
90
  "pytest == 8.3.5",
90
- "frequenz-repo-config[extra-lint-examples] == 0.12.3",
91
- "pytest-mock == 3.14.0",
92
- "pytest-asyncio == 0.25.3",
91
+ "frequenz-repo-config[extra-lint-examples] == 0.13.4",
92
+ "pytest-mock == 3.14.1",
93
+ "pytest-asyncio == 0.26.0",
93
94
  "async-solipsism == 0.7",
94
95
  ]
95
96
  dev = [
@@ -161,7 +162,15 @@ disable = [
161
162
  ]
162
163
 
163
164
  [tool.pytest.ini_options]
164
- addopts = "-W=all -Werror -Wdefault::DeprecationWarning -Wdefault::PendingDeprecationWarning -vv"
165
+ addopts = "-vv"
166
+ filterwarnings = [
167
+ "error",
168
+ "once::DeprecationWarning",
169
+ "once::PendingDeprecationWarning",
170
+ # We use a raw string (single quote) to avoid the need to escape special
171
+ # chars as this is a regex
172
+ 'ignore:Protobuf gencode version .*exactly one major version older.*:UserWarning',
173
+ ]
165
174
  testpaths = ["tests", "src"]
166
175
  asyncio_mode = "auto"
167
176
  asyncio_default_fixture_loop_scope = "function"
@@ -62,7 +62,7 @@ from ._exception import (
62
62
  UnknownError,
63
63
  UnrecognizedGrpcStatus,
64
64
  )
65
- from ._id import ComponentId, MicrogridId
65
+ from ._lifetime import Lifetime
66
66
  from ._metadata import Location, Metadata
67
67
 
68
68
  __all__ = [
@@ -76,7 +76,6 @@ __all__ = [
76
76
  "Component",
77
77
  "ComponentCategory",
78
78
  "ComponentData",
79
- "ComponentId",
80
79
  "ComponentMetadata",
81
80
  "ComponentMetricId",
82
81
  "ComponentType",
@@ -98,11 +97,11 @@ __all__ = [
98
97
  "InverterError",
99
98
  "InverterErrorCode",
100
99
  "InverterType",
100
+ "Lifetime",
101
101
  "Location",
102
102
  "Metadata",
103
103
  "MeterData",
104
104
  "MicrogridApiClient",
105
- "MicrogridId",
106
105
  "OperationAborted",
107
106
  "OperationCancelled",
108
107
  "OperationNotImplemented",
@@ -6,16 +6,22 @@
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
20
+ from frequenz.client.common.microgrid import MicrogridId
21
+ from frequenz.client.common.microgrid.components import ComponentId
22
+ from frequenz.client.common.microgrid.sensors import SensorId
18
23
  from google.protobuf.empty_pb2 import Empty
24
+ from typing_extensions import override
19
25
 
20
26
  from ._component import (
21
27
  Component,
@@ -34,8 +40,9 @@ from ._component_data import (
34
40
  from ._connection import Connection
35
41
  from ._constants import RECEIVER_MAX_SIZE
36
42
  from ._exception import ApiClientError, ClientNotConnected
37
- from ._id import ComponentId, MicrogridId
38
43
  from ._metadata import Location, Metadata
44
+ from ._sensor_proto import sensor_data_samples_from_proto, sensor_from_proto
45
+ from .sensor import Sensor, SensorDataSamples, SensorMetric
39
46
 
40
47
  DEFAULT_GRPC_CALL_TIMEOUT = 60.0
41
48
  """The default timeout for gRPC calls made by this client (in seconds)."""
@@ -95,6 +102,12 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
95
102
  self._broadcasters: dict[
96
103
  ComponentId, streaming.GrpcStreamBroadcaster[Any, Any]
97
104
  ] = {}
105
+ self._sensor_data_broadcasters: dict[
106
+ str,
107
+ streaming.GrpcStreamBroadcaster[
108
+ microgrid_pb2.ComponentData, SensorDataSamples
109
+ ],
110
+ ] = {}
98
111
  self._retry_strategy = retry_strategy
99
112
 
100
113
  @property
@@ -108,6 +121,42 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
108
121
  # type-checker, so it can only be used for type hints.
109
122
  return self._stub # type: ignore
110
123
 
124
+ @override
125
+ async def __aexit__(
126
+ self,
127
+ exc_type: type[BaseException] | None,
128
+ exc_val: BaseException | None,
129
+ exc_tb: Any | None,
130
+ ) -> bool | None:
131
+ """Close the gRPC channel and stop all broadcasters."""
132
+ exceptions = list(
133
+ exc
134
+ for exc in await asyncio.gather(
135
+ *(
136
+ broadcaster.stop()
137
+ for broadcaster in itertools.chain(
138
+ self._broadcasters.values(),
139
+ self._sensor_data_broadcasters.values(),
140
+ )
141
+ ),
142
+ return_exceptions=True,
143
+ )
144
+ if isinstance(exc, BaseException)
145
+ )
146
+ self._broadcasters.clear()
147
+ self._sensor_data_broadcasters.clear()
148
+
149
+ result = None
150
+ try:
151
+ result = await super().__aexit__(exc_type, exc_val, exc_tb)
152
+ except Exception as exc: # pylint: disable=broad-except
153
+ exceptions.append(exc)
154
+ if exceptions:
155
+ raise BaseExceptionGroup(
156
+ "Error while disconnecting from the microgrid API", exceptions
157
+ )
158
+ return result
159
+
111
160
  async def components( # noqa: DOC502 (raises ApiClientError indirectly)
112
161
  self,
113
162
  ) -> Iterable[Component]:
@@ -147,6 +196,33 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
147
196
 
148
197
  return result
149
198
 
199
+ async def list_sensors( # noqa: DOC502 (raises ApiClientError indirectly)
200
+ self,
201
+ ) -> Iterable[Sensor]:
202
+ """Fetch all the sensors present in the microgrid.
203
+
204
+ Returns:
205
+ Iterator whose elements are all the sensors in the microgrid.
206
+
207
+ Raises:
208
+ ApiClientError: If the are any errors communicating with the Microgrid API,
209
+ most likely a subclass of
210
+ [GrpcError][frequenz.client.microgrid.GrpcError].
211
+ """
212
+ component_list = await client.call_stub_method(
213
+ self,
214
+ lambda: self.stub.ListComponents(
215
+ microgrid_pb2.ComponentFilter(
216
+ categories=[
217
+ components_pb2.ComponentCategory.COMPONENT_CATEGORY_SENSOR
218
+ ]
219
+ ),
220
+ timeout=int(DEFAULT_GRPC_CALL_TIMEOUT),
221
+ ),
222
+ method_name="ListComponents",
223
+ )
224
+ return map(sensor_from_proto, component_list.components)
225
+
150
226
  async def metadata(self) -> Metadata:
151
227
  """Fetch the microgrid metadata.
152
228
 
@@ -173,7 +249,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
173
249
  return Metadata()
174
250
 
175
251
  location: Location | None = None
176
- if microgrid_metadata.location:
252
+ if microgrid_metadata.HasField("location"):
177
253
  location = Location(
178
254
  latitude=microgrid_metadata.location.latitude,
179
255
  longitude=microgrid_metadata.location.longitude,
@@ -509,3 +585,91 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
509
585
  ),
510
586
  method_name="AddInclusionBounds",
511
587
  )
588
+
589
+ # noqa: DOC502 (Raises ApiClientError indirectly)
590
+ def stream_sensor_data(
591
+ self,
592
+ sensor: SensorId | Sensor,
593
+ metrics: Iterable[SensorMetric | int] | None = None,
594
+ *,
595
+ buffer_size: int = 50,
596
+ ) -> Receiver[SensorDataSamples]:
597
+ """Stream data samples from a sensor.
598
+
599
+ Warning:
600
+ Sensors may not support all metrics. If a sensor does not support
601
+ a given metric, then the returned data stream will not contain that metric.
602
+
603
+ There is no way to tell if a metric is not being received because the
604
+ sensor does not support it or because there is a transient issue when
605
+ retrieving the metric from the sensor.
606
+
607
+ The supported metrics by a sensor can even change with time, for example,
608
+ if a sensor is updated with new firmware.
609
+
610
+ Args:
611
+ sensor: The sensor to stream data from.
612
+ metrics: If not `None`, only the specified metrics will be retrieved.
613
+ Otherwise all available metrics will be retrieved.
614
+ buffer_size: The maximum number of messages to buffer in the returned
615
+ receiver. After this limit is reached, the oldest messages will be
616
+ dropped.
617
+
618
+ Returns:
619
+ A receiver to retrieve data from the sensor.
620
+ """
621
+ sensor_id = _get_sensor_id(sensor)
622
+ key = str(sensor_id)
623
+
624
+ class _ExtraArgs(TypedDict):
625
+ metrics: NotRequired[frozenset[sensor_pb2.SensorMetric.ValueType]]
626
+
627
+ extra_args: _ExtraArgs = {}
628
+ if metrics is not None:
629
+ extra_args["metrics"] = frozenset(
630
+ [_get_sensor_metric_value(m) for m in metrics]
631
+ )
632
+ # We use the frozenset because iterables are not hashable
633
+ key += f"{hash(extra_args['metrics'])}"
634
+
635
+ broadcaster = self._sensor_data_broadcasters.get(key)
636
+ if broadcaster is None:
637
+ client_id = hex(id(self))[2:]
638
+ stream_name = f"microgrid-client-{client_id}-sensor-data-{key}"
639
+ broadcaster = streaming.GrpcStreamBroadcaster(
640
+ stream_name,
641
+ lambda: aiter(
642
+ self.stub.StreamComponentData(
643
+ microgrid_pb2.ComponentIdParam(id=sensor_id),
644
+ timeout=DEFAULT_GRPC_CALL_TIMEOUT,
645
+ )
646
+ ),
647
+ partial(sensor_data_samples_from_proto, **extra_args),
648
+ retry_strategy=self._retry_strategy,
649
+ )
650
+ self._sensor_data_broadcasters[key] = broadcaster
651
+ return broadcaster.new_receiver(maxsize=buffer_size)
652
+
653
+
654
+ def _get_sensor_id(sensor: SensorId | Sensor) -> int:
655
+ """Get the sensor ID from a sensor or sensor ID."""
656
+ match sensor:
657
+ case SensorId():
658
+ return int(sensor)
659
+ case Sensor():
660
+ return int(sensor.id)
661
+ case unexpected:
662
+ assert_never(unexpected)
663
+
664
+
665
+ def _get_sensor_metric_value(
666
+ metric: SensorMetric | int,
667
+ ) -> sensor_pb2.SensorMetric.ValueType:
668
+ """Get the sensor metric ID from a sensor metric or sensor metric ID."""
669
+ match metric:
670
+ case SensorMetric():
671
+ return sensor_pb2.SensorMetric.ValueType(metric.value)
672
+ case int():
673
+ return sensor_pb2.SensorMetric.ValueType(metric)
674
+ case unexpected:
675
+ assert_never(unexpected)
@@ -8,8 +8,7 @@ from enum import Enum
8
8
 
9
9
  from frequenz.api.common import components_pb2
10
10
  from frequenz.api.microgrid import grid_pb2, inverter_pb2
11
-
12
- from ._id import ComponentId
11
+ from frequenz.client.common.microgrid.components import ComponentId
13
12
 
14
13
 
15
14
  class ComponentType(Enum):
@@ -9,6 +9,7 @@ from datetime import datetime, timezone
9
9
  from typing import Self
10
10
 
11
11
  from frequenz.api.microgrid import microgrid_pb2
12
+ from frequenz.client.common.microgrid.components import ComponentId
12
13
 
13
14
  from ._component_error import BatteryError, InverterError
14
15
  from ._component_states import (
@@ -18,7 +19,6 @@ from ._component_states import (
18
19
  EVChargerComponentState,
19
20
  InverterComponentState,
20
21
  )
21
- from ._id import ComponentId
22
22
 
23
23
 
24
24
  @dataclass(frozen=True)
@@ -6,7 +6,7 @@
6
6
 
7
7
  from dataclasses import dataclass
8
8
 
9
- from ._id import ComponentId
9
+ from frequenz.client.common.microgrid.components import ComponentId
10
10
 
11
11
 
12
12
  @dataclass(frozen=True)
@@ -0,0 +1,52 @@
1
+ # License: MIT
2
+ # Copyright © 2025 Frequenz Energy-as-a-Service GmbH
3
+
4
+ """Lifetime of a microgrid asset."""
5
+
6
+
7
+ from dataclasses import dataclass
8
+ from datetime import datetime, timezone
9
+
10
+
11
+ @dataclass(frozen=True, kw_only=True)
12
+ class Lifetime:
13
+ """An active operational period of a microgrid asset.
14
+
15
+ Warning:
16
+ The [`end`][frequenz.client.microgrid.Lifetime.end] timestamp indicates that the
17
+ asset has been permanently removed from the system.
18
+ """
19
+
20
+ start: datetime | None = None
21
+ """The moment when the asset became operationally active.
22
+
23
+ If `None`, the asset is considered to be active in any past moment previous to the
24
+ [`end`][frequenz.client.microgrid.Lifetime.end].
25
+ """
26
+
27
+ end: datetime | None = None
28
+ """The moment when the asset's operational activity ceased.
29
+
30
+ If `None`, the asset is considered to be active with no plans to be deactivated.
31
+ """
32
+
33
+ def __post_init__(self) -> None:
34
+ """Validate this lifetime."""
35
+ if self.start is not None and self.end is not None and self.start > self.end:
36
+ raise ValueError("Start must be before or equal to end.")
37
+
38
+ def is_operational_at(self, timestamp: datetime) -> bool:
39
+ """Check whether this lifetime is active at a specific timestamp."""
40
+ # Handle start time - it's not active if start is in the future
41
+ if self.start is not None and self.start > timestamp:
42
+ return False
43
+ # Handle end time - active up to and including end time
44
+ if self.end is not None:
45
+ return self.end >= timestamp
46
+ # self.end is None, and either self.start is None or self.start <= timestamp,
47
+ # so it is active at this timestamp
48
+ return True
49
+
50
+ def is_operational_now(self) -> bool:
51
+ """Whether this lifetime is currently active."""
52
+ return self.is_operational_at(datetime.now(timezone.utc))
@@ -6,10 +6,9 @@
6
6
  from dataclasses import dataclass
7
7
  from zoneinfo import ZoneInfo
8
8
 
9
+ from frequenz.client.common.microgrid import MicrogridId
9
10
  from timezonefinder import TimezoneFinder
10
11
 
11
- from ._id import MicrogridId
12
-
13
12
  _timezone_finder = TimezoneFinder()
14
13
 
15
14