frequenz-client-microgrid 0.7.0__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 (32) hide show
  1. {frequenz_client_microgrid-0.7.0/src/frequenz_client_microgrid.egg-info → frequenz_client_microgrid-0.8.0}/PKG-INFO +22 -21
  2. frequenz_client_microgrid-0.8.0/RELEASE_NOTES.md +18 -0
  3. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/pyproject.toml +21 -21
  4. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/__init__.py +2 -3
  5. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_client.py +166 -4
  6. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_component.py +1 -1
  7. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_component_data.py +1 -1
  8. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_connection.py +1 -1
  9. frequenz_client_microgrid-0.8.0/src/frequenz/client/microgrid/_lifetime.py +52 -0
  10. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_metadata.py +1 -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.7.0 → frequenz_client_microgrid-0.8.0/src/frequenz_client_microgrid.egg-info}/PKG-INFO +22 -21
  17. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/src/frequenz_client_microgrid.egg-info/SOURCES.txt +6 -1
  18. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/src/frequenz_client_microgrid.egg-info/requires.txt +19 -19
  19. frequenz_client_microgrid-0.7.0/RELEASE_NOTES.md +0 -14
  20. frequenz_client_microgrid-0.7.0/src/frequenz/client/microgrid/_id.py +0 -107
  21. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/LICENSE +0 -0
  22. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/MANIFEST.in +0 -0
  23. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/README.md +0 -0
  24. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/setup.cfg +0 -0
  25. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_component_error.py +0 -0
  26. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_component_states.py +0 -0
  27. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_constants.py +0 -0
  28. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/_exception.py +0 -0
  29. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/conftest.py +0 -0
  30. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/src/frequenz/client/microgrid/py.typed +0 -0
  31. {frequenz_client_microgrid-0.7.0 → frequenz_client_microgrid-0.8.0}/src/frequenz_client_microgrid.egg-info/dependency_links.txt +0 -0
  32. {frequenz_client_microgrid-0.7.0 → 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.7.0
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.2; 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.2; 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
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.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"
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
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: 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==2025.2.9; extra == "dev-noxfile"
59
- Requires-Dist: frequenz-repo-config[lib]==0.12.3; 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
64
  Requires-Dist: pytest==8.3.5; extra == "dev-pytest"
65
- Requires-Dist: frequenz-repo-config[extra-lint-examples]==0.12.3; 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.2",
7
- "setuptools_scm[toml] == 8.2.0",
8
- "frequenz-repo-config[lib] == 0.12.3",
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.2",
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.2",
58
+ "pydoclint == 0.6.6",
59
59
  "pydocstyle == 6.3.0",
60
60
  ]
61
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.7",
70
- "mkdocstrings[python] == 0.28.2",
71
- "mkdocstrings-python == 1.16.2",
72
- "frequenz-repo-config[lib] == 0.12.3",
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
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
+ "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 == 2025.2.9", "frequenz-repo-config[lib] == 0.12.3"]
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
89
  "pytest == 8.3.5",
90
- "frequenz-repo-config[extra-lint-examples] == 0.12.3",
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,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,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,
@@ -34,8 +37,10 @@ from ._component_data import (
34
37
  from ._connection import Connection
35
38
  from ._constants import RECEIVER_MAX_SIZE
36
39
  from ._exception import ApiClientError, ClientNotConnected
37
- from ._id import ComponentId, MicrogridId
38
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
39
44
 
40
45
  DEFAULT_GRPC_CALL_TIMEOUT = 60.0
41
46
  """The default timeout for gRPC calls made by this client (in seconds)."""
@@ -95,6 +100,12 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
95
100
  self._broadcasters: dict[
96
101
  ComponentId, streaming.GrpcStreamBroadcaster[Any, Any]
97
102
  ] = {}
103
+ self._sensor_data_broadcasters: dict[
104
+ str,
105
+ streaming.GrpcStreamBroadcaster[
106
+ microgrid_pb2.ComponentData, SensorDataSamples
107
+ ],
108
+ ] = {}
98
109
  self._retry_strategy = retry_strategy
99
110
 
100
111
  @property
@@ -108,6 +119,42 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
108
119
  # type-checker, so it can only be used for type hints.
109
120
  return self._stub # type: ignore
110
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
+
111
158
  async def components( # noqa: DOC502 (raises ApiClientError indirectly)
112
159
  self,
113
160
  ) -> Iterable[Component]:
@@ -147,6 +194,33 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
147
194
 
148
195
  return result
149
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
+
150
224
  async def metadata(self) -> Metadata:
151
225
  """Fetch the microgrid metadata.
152
226
 
@@ -173,7 +247,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
173
247
  return Metadata()
174
248
 
175
249
  location: Location | None = None
176
- if microgrid_metadata.location:
250
+ if microgrid_metadata.HasField("location"):
177
251
  location = Location(
178
252
  latitude=microgrid_metadata.location.latitude,
179
253
  longitude=microgrid_metadata.location.longitude,
@@ -509,3 +583,91 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
509
583
  ),
510
584
  method_name="AddInclusionBounds",
511
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,7 +9,7 @@ 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
12
+ from .id import ComponentId
13
13
 
14
14
 
15
15
  class ComponentType(Enum):
@@ -18,7 +18,7 @@ from ._component_states import (
18
18
  EVChargerComponentState,
19
19
  InverterComponentState,
20
20
  )
21
- from ._id import ComponentId
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 .id 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))
@@ -8,7 +8,7 @@ from zoneinfo import ZoneInfo
8
8
 
9
9
  from timezonefinder import TimezoneFinder
10
10
 
11
- from ._id import MicrogridId
11
+ from .id import MicrogridId
12
12
 
13
13
  _timezone_finder = TimezoneFinder()
14
14