frequenz_microgrid/logical_meter/config.rs
1// License: MIT
2// Copyright © 2025 Frequenz Energy-as-a-Service GmbH
3
4//! This module defines the configuration for the logical meter.
5
6use crate::Sample;
7use crate::client::proto::common::metrics::Metric;
8use chrono::TimeDelta;
9use frequenz_resampling::ResamplingFunction;
10use std::collections::HashMap;
11
12pub struct LogicalMeterConfig {
13 /// The resampling interval for the logical meter.
14 pub(crate) resampling_interval: TimeDelta,
15 /// Resampler function.
16 pub(crate) resampling_function: Option<ResamplingFunction<f32, Sample<f32>>>,
17 /// Resampler overrides.
18 pub(crate) resampling_overrides: HashMap<Metric, ResamplingFunction<f32, Sample<f32>>>,
19 /// The maximum age of samples to be considered for resampling, in number of
20 /// intervals.
21 pub(crate) max_age_in_intervals: u32,
22}
23
24impl LogicalMeterConfig {
25 /// Creates a new `LogicalMeterConfig` with the given resampling interval.
26 pub fn new(resampling_interval: TimeDelta) -> Self {
27 Self {
28 resampling_interval,
29 resampling_function: None,
30 resampling_overrides: HashMap::new(),
31 max_age_in_intervals: 3,
32 }
33 }
34
35 /// Sets the default resampling function.
36 ///
37 /// This function will be used for all metrics that do not have a specific
38 /// override set.
39 ///
40 /// If no default resampling function is set, the logical meter will default
41 /// to using the `Average` resampling function.
42 pub fn with_default_resampling_function(
43 mut self,
44 function: ResamplingFunction<f32, Sample<f32>>,
45 ) -> Self {
46 self.resampling_function = Some(function);
47 self
48 }
49
50 /// Sets a resampling function override for a specific metric.
51 ///
52 /// If this function is called multiple times for the same metric, the last
53 /// function provided will be used.
54 pub fn override_resampling_function<M: crate::metric::Metric>(
55 mut self,
56 function: ResamplingFunction<f32, Sample<f32>>,
57 ) -> Self {
58 self.resampling_overrides.insert(M::METRIC, function);
59
60 self
61 }
62
63 /// Sets the maximum age of samples to be considered for resampling, in
64 /// number of intervals.
65 ///
66 /// Must be at least 1. If a smaller value is provided, it will be clamped
67 /// to 1.
68 ///
69 /// If not set, the default value is 3.
70 pub fn with_max_age_in_intervals(mut self, max_age_in_intervals: u32) -> Self {
71 // Ensure that the maximum age is at least 1 interval.
72 self.max_age_in_intervals = max_age_in_intervals.max(1);
73 self
74 }
75}