frequenz-client-microgrid 0.18.1__tar.gz → 0.18.2__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 (66) hide show
  1. {frequenz_client_microgrid-0.18.1/src/frequenz_client_microgrid.egg-info → frequenz_client_microgrid-0.18.2}/PKG-INFO +1 -1
  2. frequenz_client_microgrid-0.18.2/RELEASE_NOTES.md +177 -0
  3. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/__init__.py +0 -1
  4. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/_client.py +130 -11
  5. frequenz_client_microgrid-0.18.2/src/frequenz/client/microgrid/sensor/__init__.py +48 -0
  6. frequenz_client_microgrid-0.18.2/src/frequenz/client/microgrid/sensor/_sensor.py +57 -0
  7. frequenz_client_microgrid-0.18.2/src/frequenz/client/microgrid/sensor/_sensor_proto.py +93 -0
  8. frequenz_client_microgrid-0.18.2/src/frequenz/client/microgrid/sensor/_state.py +84 -0
  9. frequenz_client_microgrid-0.18.2/src/frequenz/client/microgrid/sensor/_state_proto.py +75 -0
  10. frequenz_client_microgrid-0.18.2/src/frequenz/client/microgrid/sensor/_telemetry.py +33 -0
  11. frequenz_client_microgrid-0.18.2/src/frequenz/client/microgrid/sensor/_telemetry_proto.py +49 -0
  12. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2/src/frequenz_client_microgrid.egg-info}/PKG-INFO +1 -1
  13. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz_client_microgrid.egg-info/SOURCES.txt +7 -0
  14. frequenz_client_microgrid-0.18.1/RELEASE_NOTES.md +0 -13
  15. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/LICENSE +0 -0
  16. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/MANIFEST.in +0 -0
  17. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/README.md +0 -0
  18. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/pyproject.toml +0 -0
  19. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/setup.cfg +0 -0
  20. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/_delivery_area.py +0 -0
  21. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/_delivery_area_proto.py +0 -0
  22. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/_exception.py +0 -0
  23. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/_lifetime.py +0 -0
  24. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/_lifetime_proto.py +0 -0
  25. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/_location.py +0 -0
  26. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/_location_proto.py +0 -0
  27. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/_microgrid_info.py +0 -0
  28. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/_microgrid_info_proto.py +0 -0
  29. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/_util.py +0 -0
  30. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/__init__.py +0 -0
  31. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_battery.py +0 -0
  32. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_category.py +0 -0
  33. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_chp.py +0 -0
  34. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_component.py +0 -0
  35. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_component_proto.py +0 -0
  36. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_connection.py +0 -0
  37. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_connection_proto.py +0 -0
  38. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_converter.py +0 -0
  39. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_crypto_miner.py +0 -0
  40. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_data_samples.py +0 -0
  41. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_data_samples_proto.py +0 -0
  42. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_electrolyzer.py +0 -0
  43. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_ev_charger.py +0 -0
  44. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_grid_connection_point.py +0 -0
  45. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_hvac.py +0 -0
  46. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_inverter.py +0 -0
  47. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_meter.py +0 -0
  48. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_precharger.py +0 -0
  49. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_problematic.py +0 -0
  50. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_relay.py +0 -0
  51. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_state_sample.py +0 -0
  52. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_state_sample_proto.py +0 -0
  53. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_types.py +0 -0
  54. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_voltage_transformer.py +0 -0
  55. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/component/_wind_turbine.py +0 -0
  56. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/conftest.py +0 -0
  57. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/metrics/__init__.py +0 -0
  58. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/metrics/_bounds.py +0 -0
  59. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/metrics/_bounds_proto.py +0 -0
  60. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/metrics/_metric.py +0 -0
  61. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/metrics/_sample.py +0 -0
  62. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/metrics/_sample_proto.py +0 -0
  63. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz/client/microgrid/py.typed +0 -0
  64. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz_client_microgrid.egg-info/dependency_links.txt +0 -0
  65. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz_client_microgrid.egg-info/requires.txt +0 -0
  66. {frequenz_client_microgrid-0.18.1 → frequenz_client_microgrid-0.18.2}/src/frequenz_client_microgrid.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: frequenz-client-microgrid
3
- Version: 0.18.1
3
+ Version: 0.18.2
4
4
  Summary: Microgrid API client for Python
5
5
  Author-email: Frequenz Energy-as-a-Service GmbH <floss@frequenz.com>
6
6
  License: MIT
@@ -0,0 +1,177 @@
1
+ # Frequenz Microgrid API Client Release Notes
2
+
3
+ ## Summary
4
+
5
+ This release reintroduces sensor support that was temporarily removed in the v0.18.0 release. The new sensor API has been redesigned to fit the updated component and metrics model introduced in v0.18.0.
6
+
7
+ ## New Features
8
+
9
+ - New `sensor` module (`frequenz.client.microgrid.sensor`) with sensor related types.
10
+ - New `MicrogridApiClient` methods
11
+
12
+ * `list_sensors()`: fetch sensor metadata.
13
+ * `receive_sensor_telemetry_stream()`: stream sensor telemetry data.
14
+
15
+ Example:
16
+
17
+ ```python
18
+ import asyncio
19
+ from frequenz.client.microgrid import MicrogridApiClient
20
+ from frequenz.client.microgrid.metrics import Metric
21
+
22
+ URL = "grpc://[::1]:62060"
23
+
24
+ async def main() -> None:
25
+ print(f"Connecting to {URL}...")
26
+ async with MicrogridApiClient(URL) as client:
27
+ print("Listing available sensors...")
28
+ sensors = list(await client.list_sensors())
29
+
30
+ if not sensors:
31
+ print("No sensors found.")
32
+ return
33
+
34
+ print(f"Found {len(sensors)}: {sensors}.")
35
+ print()
36
+
37
+ sensor = sensors[0]
38
+ print(f"Streaming telemetry from sensor {sensor.id} ({sensor.name})...")
39
+ telemetry_stream = client.receive_sensor_telemetry_stream(
40
+ sensors[0].id, list(Metric)
41
+ )
42
+ async for telemetry in telemetry_stream:
43
+ print(f"\tReceived: {telemetry}")
44
+
45
+ asyncio.run(main())
46
+ ```
47
+
48
+ ## Upgrading (from v0.9)
49
+
50
+ ### Sensor support restored with new API
51
+
52
+ Sensor support that was removed in v0.18.0 is now back, but with a redesigned API that aligns with the v0.18.0 component and metrics model.
53
+
54
+ #### `list_sensors()`
55
+
56
+ The method name remains the same, but the signature and return type have changed:
57
+
58
+ ```python
59
+ # Old v0.9.1 API
60
+ sensors: Iterable[Sensor] = await client.list_sensors()
61
+
62
+ # New v0.18.2 API (same method name, different types)
63
+ from frequenz.client.common.microgrid.sensors import SensorId
64
+ from frequenz.client.microgrid.sensor import Sensor
65
+
66
+ sensors: Iterable[Sensor] = await client.list_sensors()
67
+
68
+ # You can also filter by sensor IDs
69
+ sensors = await client.list_sensors(sensors=[SensorId(1), SensorId(2)])
70
+ ```
71
+ The `Sensor` class now provides a new attribute `microgrid_id: MicrogridId` and the `identity` property now returns a tuple `(SensorId, MicrogridId)` instead of just `SensorId`.
72
+
73
+ #### `stream_sensor_data()` → `receive_sensor_telemetry_stream()`
74
+
75
+ The streaming method has been renamed and its return type changed:
76
+
77
+ ```python
78
+ # Old v0.9.1 API
79
+ from frequenz.client.microgrid.sensor import SensorDataSamples, SensorMetric
80
+
81
+ receiver: Receiver[SensorDataSamples] = client.stream_sensor_data(
82
+ sensor=SensorId(1),
83
+ metrics=[SensorMetric.TEMPERATURE, SensorMetric.HUMIDITY], # optional
84
+ )
85
+
86
+ async for samples in receiver:
87
+ # samples.metric_samples, samples.state_sample, etc.
88
+ ...
89
+
90
+ # New v0.18.2 API
91
+ from frequenz.client.microgrid.sensor import SensorTelemetry
92
+ from frequenz.client.microgrid.metrics import Metric
93
+
94
+ receiver: Receiver[SensorTelemetry] = client.receive_sensor_telemetry_stream(
95
+ sensor=SensorId(1),
96
+ metrics=[Metric.TEMPERATURE, Metric.AC_VOLTAGE], # required
97
+ )
98
+
99
+ async for telemetry in receiver:
100
+ # telemetry.sensor_id: SensorId
101
+ # telemetry.metric_samples: Sequence[MetricSample]
102
+ # telemetry.state_snapshots: Sequence[SensorStateSnapshot]
103
+ for sample in telemetry.metric_samples:
104
+ print(f"{sample.metric}: {sample.value} at {sample.sampled_at}")
105
+ ...
106
+ ```
107
+
108
+ Key differences:
109
+
110
+ - **Method renamed**: `stream_sensor_data()` → `receive_sensor_telemetry_stream()`
111
+ - **Metrics parameter is now required**: You must specify which metrics to stream. The old API allowed `None` to stream all metrics.
112
+ - **Uses unified `Metric` enum**: The old `SensorMetric` enum is removed. Use `frequenz.client.microgrid.metrics.Metric` instead.
113
+ - **Return type changed**: `SensorDataSamples` → `SensorTelemetry`
114
+ - **State samples changed**: `SensorStateSample` → `SensorStateSnapshot` with different structure (see below)
115
+
116
+ #### Sensor state types
117
+
118
+ The sensor state types have been redesigned:
119
+
120
+ | Old v0.9.1 type | New v0.18.2 type |
121
+ |---------------------------|-------------------------------------------|
122
+ | `SensorMetric` | *Removed* — use `Metric` |
123
+ | `SensorStateCode` | `SensorStateCode` (different values) |
124
+ | `SensorErrorCode` | `SensorDiagnosticCode` |
125
+ | `SensorStateSample` | `SensorStateSnapshot` |
126
+ | `SensorMetricSample` | `MetricSample` |
127
+ | `SensorDataSamples` | `SensorTelemetry` |
128
+
129
+ The new `SensorStateSnapshot` structure:
130
+
131
+ ```python
132
+ @dataclass(frozen=True, kw_only=True)
133
+ class SensorStateSnapshot:
134
+ origin_time: datetime # was `sampled_at`
135
+ states: Set[SensorStateCode | int] # was `frozenset`
136
+ warnings: Sequence[SensorDiagnostic] # new
137
+ errors: Sequence[SensorDiagnostic] # replaces error codes
138
+ ```
139
+
140
+ The new `SensorDiagnostic` provides richer error/warning information:
141
+
142
+ ```python
143
+ @dataclass(frozen=True, kw_only=True)
144
+ class SensorDiagnostic:
145
+ diagnostic_code: SensorDiagnosticCode | int
146
+ message: str | None
147
+ vendor_diagnostic_code: str | None
148
+ ```
149
+
150
+ #### Import changes
151
+
152
+ Update your imports for sensor types:
153
+
154
+ ```python
155
+ # Old v0.9.1
156
+ from frequenz.client.microgrid.sensor import (
157
+ Sensor,
158
+ SensorDataSamples,
159
+ SensorErrorCode,
160
+ SensorMetric,
161
+ SensorMetricSample,
162
+ SensorStateCode,
163
+ SensorStateSample,
164
+ )
165
+
166
+ # New v0.18.2
167
+ from frequenz.client.microgrid.sensor import (
168
+ Sensor,
169
+ SensorDiagnostic,
170
+ SensorDiagnosticCode,
171
+ SensorStateCode,
172
+ SensorStateSnapshot,
173
+ SensorTelemetry,
174
+ )
175
+ from frequenz.client.microgrid.metrics import Metric, MetricSample
176
+ from frequenz.client.common.microgrid.sensors import SensorId
177
+ ```
@@ -6,7 +6,6 @@
6
6
  This package provides a low-level interface for interacting with the microgrid API.
7
7
  """
8
8
 
9
-
10
9
  from ._client import (
11
10
  DEFAULT_CHANNEL_OPTIONS,
12
11
  DEFAULT_GRPC_CALL_TIMEOUT,
@@ -12,7 +12,7 @@ import math
12
12
  from collections.abc import Iterable
13
13
  from dataclasses import replace
14
14
  from datetime import datetime, timedelta
15
- from typing import Any, assert_never
15
+ from typing import Any, assert_never, cast
16
16
 
17
17
  from frequenz.api.common.v1alpha8.metrics import bounds_pb2, metrics_pb2
18
18
  from frequenz.api.common.v1alpha8.microgrid.electrical_components import (
@@ -23,6 +23,7 @@ from frequenz.channels import Receiver
23
23
  from frequenz.client.base import channel, client, conversion, retry, streaming
24
24
  from frequenz.client.base.exception import ApiClientError
25
25
  from frequenz.client.common.microgrid.components import ComponentId
26
+ from frequenz.client.common.microgrid.sensors import SensorId
26
27
  from google.protobuf.empty_pb2 import Empty
27
28
  from grpc.aio import AioRpcError
28
29
  from typing_extensions import override
@@ -40,6 +41,10 @@ from .component._data_samples_proto import component_data_samples_from_proto
40
41
  from .component._types import ComponentTypes
41
42
  from .metrics._bounds import Bounds
42
43
  from .metrics._metric import Metric
44
+ from .sensor._sensor import Sensor
45
+ from .sensor._sensor_proto import sensor_from_proto
46
+ from .sensor._telemetry import SensorTelemetry
47
+ from .sensor._telemetry_proto import sensor_telemetry_from_proto
43
48
 
44
49
  DEFAULT_GRPC_CALL_TIMEOUT = 60.0
45
50
  """The default timeout for gRPC calls made by this client (in seconds)."""
@@ -100,7 +105,10 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
100
105
  ] = {}
101
106
  self._sensor_data_broadcasters: dict[
102
107
  str,
103
- streaming.GrpcStreamBroadcaster[Any, Any],
108
+ streaming.GrpcStreamBroadcaster[
109
+ microgrid_pb2.ReceiveSensorTelemetryStreamResponse,
110
+ SensorTelemetry,
111
+ ],
104
112
  ] = {}
105
113
  self._retry_strategy = retry_strategy
106
114
 
@@ -123,16 +131,19 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
123
131
  exc_tb: Any | None,
124
132
  ) -> bool | None:
125
133
  """Close the gRPC channel and stop all broadcasters."""
134
+ all_broadcasters = cast(
135
+ list[streaming.GrpcStreamBroadcaster[Any, Any]],
136
+ list(
137
+ itertools.chain(
138
+ self._component_data_broadcasters.values(),
139
+ self._sensor_data_broadcasters.values(),
140
+ )
141
+ ),
142
+ )
126
143
  exceptions = list(
127
144
  exc
128
145
  for exc in await asyncio.gather(
129
- *(
130
- broadcaster.stop()
131
- for broadcaster in itertools.chain(
132
- self._component_data_broadcasters.values(),
133
- self._sensor_data_broadcasters.values(),
134
- )
135
- ),
146
+ *(broadcaster.stop() for broadcaster in all_broadcasters),
136
147
  return_exceptions=True,
137
148
  )
138
149
  if isinstance(exc, BaseException)
@@ -213,7 +224,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
213
224
  Iterator whose elements are all the components in the local microgrid.
214
225
 
215
226
  Raises:
216
- ApiClientError: If the are any errors communicating with the Microgrid API,
227
+ ApiClientError: If there are any errors communicating with the Microgrid API,
217
228
  most likely a subclass of
218
229
  [GrpcError][frequenz.client.microgrid.GrpcError].
219
230
  """
@@ -269,7 +280,7 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
269
280
  Iterator whose elements are all the connections in the local microgrid.
270
281
 
271
282
  Raises:
272
- ApiClientError: If the are any errors communicating with the Microgrid API,
283
+ ApiClientError: If there are any errors communicating with the Microgrid API,
273
284
  most likely a subclass of
274
285
  [GrpcError][frequenz.client.microgrid.GrpcError].
275
286
  """
@@ -296,6 +307,41 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
296
307
  if conn is not None
297
308
  )
298
309
 
310
+ async def list_sensors( # noqa: DOC502 (raises ApiClientError indirectly)
311
+ self,
312
+ *,
313
+ sensors: Iterable[SensorId | Sensor] = (),
314
+ ) -> Iterable[Sensor]:
315
+ """Fetch all the sensors present in the local microgrid.
316
+
317
+ Sensors are devices that measure physical properties in the microgrid's
318
+ surroundings, such as temperature, humidity, and solar irradiance. Unlike
319
+ electrical components, sensors are not part of the electrical infrastructure.
320
+
321
+ Args:
322
+ sensors: The sensors to fetch. If empty, all sensors are fetched.
323
+
324
+ Returns:
325
+ Iterator whose elements are all the sensors in the local microgrid.
326
+
327
+ Raises:
328
+ ApiClientError: If there are any errors communicating with the Microgrid API,
329
+ most likely a subclass of
330
+ [GrpcError][frequenz.client.microgrid.GrpcError].
331
+ """
332
+ response = await client.call_stub_method(
333
+ self,
334
+ lambda: self.stub.ListSensors(
335
+ microgrid_pb2.ListSensorRequest(
336
+ sensor_ids=map(_get_sensor_id, sensors),
337
+ ),
338
+ timeout=DEFAULT_GRPC_CALL_TIMEOUT,
339
+ ),
340
+ method_name="ListSensors",
341
+ )
342
+
343
+ return map(sensor_from_proto, response.sensors)
344
+
299
345
  # pylint: disable-next=fixme
300
346
  # TODO: Unifi set_component_power_active and set_component_power_reactive, or at
301
347
  # least use a common implementation.
@@ -632,6 +678,68 @@ class MicrogridApiClient(client.BaseApiClient[microgrid_pb2_grpc.MicrogridStub])
632
678
  self._component_data_broadcasters[key] = broadcaster
633
679
  return broadcaster.new_receiver(maxsize=buffer_size)
634
680
 
681
+ def receive_sensor_telemetry_stream(
682
+ self,
683
+ sensor: SensorId | Sensor,
684
+ metrics: Iterable[Metric | int],
685
+ *,
686
+ buffer_size: int = 50,
687
+ ) -> Receiver[SensorTelemetry]:
688
+ """Stream telemetry data from a sensor.
689
+
690
+ At least one metric must be specified. If no metric is specified, then the
691
+ stream will raise an error.
692
+
693
+ Warning:
694
+ Sensors may not support all metrics. If a sensor does not support
695
+ a given metric, then the returned data stream will not contain that metric.
696
+
697
+ There is no way to tell if a metric is not being received because the
698
+ sensor does not support it or because there is a transient issue when
699
+ retrieving the metric from the sensor.
700
+
701
+ The supported metrics by a sensor can even change with time, for example,
702
+ if a sensor is updated with new firmware.
703
+
704
+ Args:
705
+ sensor: The sensor to stream data from.
706
+ metrics: List of metrics to return. Only the specified metrics will be
707
+ returned.
708
+ buffer_size: The maximum number of messages to buffer in the returned
709
+ receiver. After this limit is reached, the oldest messages will be
710
+ dropped.
711
+
712
+ Returns:
713
+ The telemetry stream from the sensor.
714
+ """
715
+ sensor_id = _get_sensor_id(sensor)
716
+ metrics_set = frozenset([_get_metric_value(m) for m in metrics])
717
+ key = f"{sensor_id}-{hash(metrics_set)}"
718
+ broadcaster = self._sensor_data_broadcasters.get(key)
719
+ if broadcaster is None:
720
+ client_id = hex(id(self))[2:]
721
+ stream_name = f"microgrid-client-{client_id}-sensor-data-{key}"
722
+ # Alias to avoid too long lines linter errors
723
+ # pylint: disable-next=invalid-name
724
+ Request = microgrid_pb2.ReceiveSensorTelemetryStreamRequest
725
+ broadcaster = streaming.GrpcStreamBroadcaster(
726
+ stream_name,
727
+ lambda: aiter(
728
+ self.stub.ReceiveSensorTelemetryStream(
729
+ Request(
730
+ sensor_id=sensor_id,
731
+ filter=Request.SensorTelemetryStreamFilter(
732
+ metrics=metrics_set
733
+ ),
734
+ ),
735
+ )
736
+ ),
737
+ lambda msg: sensor_telemetry_from_proto(msg.telemetry),
738
+ retry_strategy=self._retry_strategy,
739
+ )
740
+ self._sensor_data_broadcasters[key] = broadcaster
741
+ return broadcaster.new_receiver(maxsize=buffer_size)
742
+
635
743
 
636
744
  # pylint: disable-next=fixme
637
745
  # TODO: Remove this enum, now AugmentElectricalComponentBounds takes a simple timeout as
@@ -663,6 +771,17 @@ def _get_component_id(component: ComponentId | Component) -> int:
663
771
  assert_never(unexpected)
664
772
 
665
773
 
774
+ def _get_sensor_id(sensor: SensorId | Sensor) -> int:
775
+ """Get the sensor ID from a sensor or sensor ID."""
776
+ match sensor:
777
+ case SensorId():
778
+ return int(sensor)
779
+ case Sensor():
780
+ return int(sensor.id)
781
+ case unexpected:
782
+ assert_never(unexpected)
783
+
784
+
666
785
  def _get_metric_value(metric: Metric | int) -> metrics_pb2.Metric.ValueType:
667
786
  """Get the metric ID from a metric or metric ID."""
668
787
  match metric:
@@ -0,0 +1,48 @@
1
+ # License: MIT
2
+ # Copyright © 2025 Frequenz Energy-as-a-Service GmbH
3
+
4
+ """Microgrid sensors.
5
+
6
+ This package provides classes and utilities for working with different types of
7
+ sensors in a microgrid environment. [`Sensor`][frequenz.client.microgrid.sensor.Sensor]s
8
+ measure various physical metrics in the surrounding environment, such as temperature,
9
+ humidity, and solar irradiance.
10
+
11
+ # Sensor Telemetry
12
+
13
+ This package also provides several data structures for handling sensor readings
14
+ and states:
15
+
16
+ * [`SensorTelemetry`][frequenz.client.microgrid.sensor.SensorTelemetry]:
17
+ Represents a collection of measurements and states from a sensor at a specific
18
+ point in time, including [metric
19
+ samples][frequenz.client.microgrid.metrics.MetricSample] and [state
20
+ snapshots][frequenz.client.microgrid.sensor.SensorStateSnapshot].
21
+ * [`SensorStateSnapshot`][frequenz.client.microgrid.sensor.SensorStateSnapshot]:
22
+ Contains the sensor's state codes and any associated diagnostic information.
23
+ * [`SensorDiagnostic`][frequenz.client.microgrid.sensor.SensorDiagnostic]:
24
+ Represents a diagnostic message from a sensor, including an error code and
25
+ optional additional information.
26
+ * [`SensorDiagnosticCode`][frequenz.client.microgrid.sensor.SensorDiagnosticCode]:
27
+ Defines error codes that a sensor can report.
28
+ * [`SensorStateCode`][frequenz.client.microgrid.sensor.SensorStateCode]:
29
+ Defines codes representing the operational state of a sensor.
30
+ """
31
+
32
+ from ._sensor import Sensor
33
+ from ._state import (
34
+ SensorDiagnostic,
35
+ SensorDiagnosticCode,
36
+ SensorStateCode,
37
+ SensorStateSnapshot,
38
+ )
39
+ from ._telemetry import SensorTelemetry
40
+
41
+ __all__ = [
42
+ "Sensor",
43
+ "SensorDiagnostic",
44
+ "SensorDiagnosticCode",
45
+ "SensorStateCode",
46
+ "SensorStateSnapshot",
47
+ "SensorTelemetry",
48
+ ]
@@ -0,0 +1,57 @@
1
+ # License: MIT
2
+ # Copyright © 2025 Frequenz Energy-as-a-Service GmbH
3
+
4
+ """Sensor definition."""
5
+
6
+ from dataclasses import dataclass, field
7
+
8
+ from frequenz.client.common.microgrid import MicrogridId
9
+ from frequenz.client.common.microgrid.sensors import SensorId
10
+
11
+ from .._lifetime import Lifetime
12
+
13
+
14
+ @dataclass(frozen=True, kw_only=True)
15
+ class Sensor:
16
+ """A sensor that measures physical metrics in the microgrid's surroundings.
17
+
18
+ Sensors are not part of the electrical infrastructure but provide
19
+ environmental data such as temperature, humidity, and solar irradiance.
20
+ """
21
+
22
+ id: SensorId
23
+ """A unique identifier for the sensor."""
24
+
25
+ microgrid_id: MicrogridId
26
+ """Unique identifier of the parent microgrid."""
27
+
28
+ name: str | None = None
29
+ """An optional name for the sensor."""
30
+
31
+ manufacturer: str | None = None
32
+ """The sensor manufacturer."""
33
+
34
+ model_name: str | None = None
35
+ """The model name of the sensor."""
36
+
37
+ operational_lifetime: Lifetime = field(default_factory=Lifetime)
38
+ """The operational lifetime of the sensor."""
39
+
40
+ @property
41
+ def identity(self) -> tuple[SensorId, MicrogridId]:
42
+ """The identity of this sensor.
43
+
44
+ This uses the sensor ID and microgrid ID to identify a sensor
45
+ without considering the other attributes, so even if a sensor state
46
+ changed, the identity remains the same.
47
+ """
48
+ return (self.id, self.microgrid_id)
49
+
50
+ def __str__(self) -> str:
51
+ """Return a human-readable string representation of this instance.
52
+
53
+ Returns:
54
+ A string representation of this sensor.
55
+ """
56
+ name = f":{self.name}" if self.name else ""
57
+ return f"<{type(self).__name__}:{self.id}{name}>"
@@ -0,0 +1,93 @@
1
+ # License: MIT
2
+ # Copyright © 2025 Frequenz Energy-as-a-Service GmbH
3
+
4
+ """Loading of Sensor objects from protobuf messages."""
5
+
6
+ import logging
7
+
8
+ from frequenz.api.common.v1alpha8.microgrid.sensors import sensors_pb2
9
+ from frequenz.client.common.microgrid import MicrogridId
10
+ from frequenz.client.common.microgrid.sensors import SensorId
11
+
12
+ from .._lifetime import Lifetime
13
+ from .._lifetime_proto import lifetime_from_proto
14
+ from ._sensor import Sensor
15
+
16
+ _logger = logging.getLogger(__name__)
17
+
18
+
19
+ def sensor_from_proto(message: sensors_pb2.Sensor) -> Sensor:
20
+ """Convert a protobuf message to a `Sensor` instance.
21
+
22
+ Args:
23
+ message: The protobuf message.
24
+
25
+ Returns:
26
+ The resulting sensor instance.
27
+ """
28
+ major_issues: list[str] = []
29
+ minor_issues: list[str] = []
30
+
31
+ sensor = sensor_from_proto_with_issues(
32
+ message, major_issues=major_issues, minor_issues=minor_issues
33
+ )
34
+
35
+ if major_issues:
36
+ _logger.warning(
37
+ "Found issues in sensor: %s | Protobuf message:\n%s",
38
+ ", ".join(major_issues),
39
+ message,
40
+ )
41
+ if minor_issues:
42
+ _logger.debug(
43
+ "Found minor issues in sensor: %s | Protobuf message:\n%s",
44
+ ", ".join(minor_issues),
45
+ message,
46
+ )
47
+
48
+ return sensor
49
+
50
+
51
+ def sensor_from_proto_with_issues(
52
+ message: sensors_pb2.Sensor,
53
+ *,
54
+ major_issues: list[str], # pylint: disable=unused-argument
55
+ minor_issues: list[str],
56
+ ) -> Sensor:
57
+ """Convert a protobuf message to a sensor instance and collect issues.
58
+
59
+ Args:
60
+ message: The protobuf message.
61
+ major_issues: A list to append major issues to.
62
+ minor_issues: A list to append minor issues to.
63
+
64
+ Returns:
65
+ The resulting sensor instance.
66
+ """
67
+ sensor_id = SensorId(message.id)
68
+ microgrid_id = MicrogridId(message.microgrid_id)
69
+
70
+ name = message.name or None
71
+ if name is None:
72
+ minor_issues.append("name is empty")
73
+
74
+ manufacturer = message.manufacturer or None
75
+ if manufacturer is None:
76
+ minor_issues.append("manufacturer is empty")
77
+
78
+ model_name = message.model_name or None
79
+ if model_name is None:
80
+ minor_issues.append("model_name is empty")
81
+
82
+ operational_lifetime = Lifetime()
83
+ if message.HasField("operational_lifetime"):
84
+ operational_lifetime = lifetime_from_proto(message.operational_lifetime)
85
+
86
+ return Sensor(
87
+ id=sensor_id,
88
+ microgrid_id=microgrid_id,
89
+ name=name,
90
+ manufacturer=manufacturer,
91
+ model_name=model_name,
92
+ operational_lifetime=operational_lifetime,
93
+ )
@@ -0,0 +1,84 @@
1
+ # License: MIT
2
+ # Copyright © 2025 Frequenz Energy-as-a-Service GmbH
3
+
4
+ """Sensor state-related types."""
5
+
6
+ import enum
7
+ from collections.abc import Sequence, Set
8
+ from dataclasses import dataclass
9
+ from datetime import datetime
10
+
11
+
12
+ @enum.unique
13
+ class SensorStateCode(enum.Enum):
14
+ """Sensor state code.
15
+
16
+ Represents the operational state of a sensor.
17
+ """
18
+
19
+ UNSPECIFIED = 0
20
+ """Unspecified state."""
21
+
22
+ OK = 1
23
+ """Sensor is operating normally."""
24
+
25
+ ERROR = 2
26
+ """Sensor is in an error state."""
27
+
28
+
29
+ @enum.unique
30
+ class SensorDiagnosticCode(enum.Enum):
31
+ """Sensor diagnostic code.
32
+
33
+ Provides additional diagnostic information about warnings or errors.
34
+ """
35
+
36
+ UNSPECIFIED = 0
37
+ """Unspecified diagnostic code."""
38
+
39
+ UNKNOWN = 1
40
+ """Unknown diagnostic issue."""
41
+
42
+ INTERNAL = 2
43
+ """Internal sensor error."""
44
+
45
+
46
+ @dataclass(frozen=True, kw_only=True)
47
+ class SensorDiagnostic:
48
+ """Diagnostic information for a sensor warning or error.
49
+
50
+ Provides detailed information about issues affecting a sensor.
51
+ """
52
+
53
+ diagnostic_code: SensorDiagnosticCode | int
54
+ """The diagnostic code identifying the type of issue."""
55
+
56
+ message: str | None = None
57
+ """Optional human-readable message describing the issue."""
58
+
59
+ vendor_diagnostic_code: str | None = None
60
+ """Optional vendor-specific diagnostic code."""
61
+
62
+
63
+ @dataclass(frozen=True, kw_only=True)
64
+ class SensorStateSnapshot:
65
+ """A snapshot of a sensor's operational state at a specific time.
66
+
67
+ Contains the sensor's state codes and any associated diagnostic information.
68
+ """
69
+
70
+ origin_time: datetime
71
+ """The timestamp when this state snapshot was recorded."""
72
+
73
+ states: Set[SensorStateCode | int]
74
+ """Set of state codes active at the snapshot time."""
75
+
76
+ warnings: Sequence[SensorDiagnostic]
77
+ """Sequence of active warnings with diagnostic information."""
78
+
79
+ errors: Sequence[SensorDiagnostic]
80
+ """Sequence of active errors with diagnostic information."""
81
+
82
+ # Disable hashing for this class (mypy doesn't seem to understand assigining to
83
+ # None, but it is documented in __hash__ docs).
84
+ __hash__ = None # type: ignore[assignment]
@@ -0,0 +1,75 @@
1
+ # License: MIT
2
+ # Copyright © 2025 Frequenz Energy-as-a-Service GmbH
3
+
4
+ """Proto conversion for sensor state types."""
5
+
6
+ from datetime import timezone
7
+
8
+ from frequenz.api.common.v1alpha8.microgrid.sensors import sensors_pb2
9
+ from frequenz.client.base.conversion import to_datetime
10
+
11
+ from ._state import (
12
+ SensorDiagnostic,
13
+ SensorDiagnosticCode,
14
+ SensorStateCode,
15
+ SensorStateSnapshot,
16
+ )
17
+
18
+
19
+ def sensor_diagnostic_from_proto(
20
+ proto: sensors_pb2.SensorDiagnostic,
21
+ ) -> SensorDiagnostic:
22
+ """Convert a proto SensorDiagnostic to a SensorDiagnostic.
23
+
24
+ Args:
25
+ proto: The proto SensorDiagnostic to convert.
26
+
27
+ Returns:
28
+ The converted SensorDiagnostic.
29
+ """
30
+ diagnostic_code: SensorDiagnosticCode | int = proto.diagnostic_code
31
+ try:
32
+ diagnostic_code = SensorDiagnosticCode(diagnostic_code)
33
+ except ValueError:
34
+ pass # Keep as int if unrecognized
35
+
36
+ return SensorDiagnostic(
37
+ diagnostic_code=diagnostic_code,
38
+ message=proto.message if proto.message else None,
39
+ vendor_diagnostic_code=(
40
+ proto.vendor_diagnostic_code if proto.vendor_diagnostic_code else None
41
+ ),
42
+ )
43
+
44
+
45
+ def sensor_state_snapshot_from_proto(
46
+ proto: sensors_pb2.SensorStateSnapshot,
47
+ ) -> SensorStateSnapshot:
48
+ """Convert a proto SensorStateSnapshot to a SensorStateSnapshot.
49
+
50
+ Args:
51
+ proto: The proto SensorStateSnapshot to convert.
52
+
53
+ Returns:
54
+ The converted SensorStateSnapshot.
55
+ """
56
+ # Convert states
57
+ states = frozenset(
58
+ (
59
+ SensorStateCode(int(state))
60
+ if int(state) in [s.value for s in SensorStateCode]
61
+ else int(state)
62
+ )
63
+ for state in proto.states
64
+ )
65
+
66
+ # Convert warnings and errors
67
+ warnings = [sensor_diagnostic_from_proto(w) for w in proto.warnings]
68
+ errors = [sensor_diagnostic_from_proto(e) for e in proto.errors]
69
+
70
+ return SensorStateSnapshot(
71
+ origin_time=to_datetime(proto.origin_time).replace(tzinfo=timezone.utc),
72
+ states=states,
73
+ warnings=warnings,
74
+ errors=errors,
75
+ )
@@ -0,0 +1,33 @@
1
+ # License: MIT
2
+ # Copyright © 2025 Frequenz Energy-as-a-Service GmbH
3
+
4
+ """Sensor telemetry types."""
5
+
6
+ from collections.abc import Sequence
7
+ from dataclasses import dataclass
8
+
9
+ from frequenz.client.common.microgrid.sensors import SensorId
10
+
11
+ from ..metrics._sample import MetricSample
12
+ from ._state import SensorStateSnapshot
13
+
14
+
15
+ @dataclass(frozen=True, kw_only=True)
16
+ class SensorTelemetry:
17
+ """Telemetry data from a sensor.
18
+
19
+ Contains metric measurements and state snapshots for a specific sensor.
20
+ """
21
+
22
+ sensor_id: SensorId
23
+ """The unique identifier of the sensor that produced this telemetry."""
24
+
25
+ metric_samples: Sequence[MetricSample]
26
+ """List of metric measurements from the sensor."""
27
+
28
+ state_snapshots: Sequence[SensorStateSnapshot]
29
+ """List of state snapshots indicating the sensor's operational status."""
30
+
31
+ # Disable hashing for this class (mypy doesn't seem to understand assigining to
32
+ # None, but it is documented in __hash__ docs).
33
+ __hash__ = None # type: ignore[assignment]
@@ -0,0 +1,49 @@
1
+ # License: MIT
2
+ # Copyright © 2025 Frequenz Energy-as-a-Service GmbH
3
+
4
+ """Proto conversion for sensor telemetry."""
5
+
6
+ from frequenz.api.common.v1alpha8.microgrid.sensors import sensors_pb2
7
+ from frequenz.client.common.microgrid.sensors import SensorId
8
+
9
+ from ..metrics._sample_proto import metric_sample_from_proto_with_issues
10
+ from ._state_proto import sensor_state_snapshot_from_proto
11
+ from ._telemetry import SensorTelemetry
12
+
13
+
14
+ def sensor_telemetry_from_proto(
15
+ proto: sensors_pb2.SensorTelemetry,
16
+ ) -> SensorTelemetry:
17
+ """Convert a proto SensorTelemetry to a SensorTelemetry.
18
+
19
+ Args:
20
+ proto: The proto SensorTelemetry to convert.
21
+
22
+ Returns:
23
+ The converted SensorTelemetry.
24
+ """
25
+ # Convert metric samples
26
+ # Using empty issue lists as we're not handling issues at this level
27
+ # In a future improvement, we could expose issues to the caller
28
+ major_issues: list[str] = []
29
+ minor_issues: list[str] = []
30
+
31
+ metric_samples = [
32
+ metric_sample_from_proto_with_issues(
33
+ sample,
34
+ major_issues=major_issues,
35
+ minor_issues=minor_issues,
36
+ )
37
+ for sample in proto.metric_samples
38
+ ]
39
+
40
+ # Convert state snapshots
41
+ state_snapshots = [
42
+ sensor_state_snapshot_from_proto(snapshot) for snapshot in proto.state_snapshots
43
+ ]
44
+
45
+ return SensorTelemetry(
46
+ sensor_id=SensorId(proto.sensor_id),
47
+ metric_samples=metric_samples,
48
+ state_snapshots=state_snapshots,
49
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: frequenz-client-microgrid
3
- Version: 0.18.1
3
+ Version: 0.18.2
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
@@ -49,6 +49,13 @@ src/frequenz/client/microgrid/metrics/_bounds_proto.py
49
49
  src/frequenz/client/microgrid/metrics/_metric.py
50
50
  src/frequenz/client/microgrid/metrics/_sample.py
51
51
  src/frequenz/client/microgrid/metrics/_sample_proto.py
52
+ src/frequenz/client/microgrid/sensor/__init__.py
53
+ src/frequenz/client/microgrid/sensor/_sensor.py
54
+ src/frequenz/client/microgrid/sensor/_sensor_proto.py
55
+ src/frequenz/client/microgrid/sensor/_state.py
56
+ src/frequenz/client/microgrid/sensor/_state_proto.py
57
+ src/frequenz/client/microgrid/sensor/_telemetry.py
58
+ src/frequenz/client/microgrid/sensor/_telemetry_proto.py
52
59
  src/frequenz_client_microgrid.egg-info/PKG-INFO
53
60
  src/frequenz_client_microgrid.egg-info/SOURCES.txt
54
61
  src/frequenz_client_microgrid.egg-info/dependency_links.txt
@@ -1,13 +0,0 @@
1
- # Frequenz Microgrid API Client Release Notes
2
-
3
- ## Summary
4
-
5
- This release adds a new `WindTurbine` component type.
6
-
7
- ## Upgrading
8
-
9
- - If you are using `match` and doing exhaustive matching on the `Component` types, you will get `mypy` errors and will need to handle the new `WindTurbine` type.
10
-
11
- ## New Features
12
-
13
- - Add `WindTurbine` component type.