flexpool-telemetry 0.4.0

flexpool live telemetry: quality, plausibility, a bounded store with quarter-hour aggregation, pool summaries and the sandbox simulator. No I/O; time is an input.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! The bounded live store (SR-003): per asset the latest value per quantity, up to 15 minutes of
//! recent values and two days of quarter-hour aggregates. Memory is fixed per declared asset; values
//! for undeclared assets are refused, and no input rate makes a series grow past its cap.

use std::collections::{BTreeMap, HashMap, VecDeque};

use flexpool_core::AssetId;
use serde::Serialize;

use crate::quality::{Flags, Quality, Quantity, Reading, classify};
use crate::{QUARTER_SECS, quarter_start};

/// Recent values are kept for this long.
pub const RECENT_SECS: i64 = 900;
/// At most this many recent values per asset and quantity.
pub const RECENT_MAX: usize = 900;
/// At most this many quarter aggregates per asset (two days).
pub const QUARTERS_MAX: usize = 192;
/// A sample this much older than the latest means the receiving clock stepped back: the series
/// starts again instead of freezing on a value from the "future".
pub const CLOCK_STEP_SECS: i64 = 60;

/// What happened to a pushed value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pushed {
    /// Stored.
    Stored,
    /// Slightly older than the latest (reordered): dropped.
    Dropped,
    /// Much older than the latest: the clock stepped back; the series was restarted with it.
    Reset,
    /// No such asset.
    Undeclared,
}

/// One quarter hour of an asset.
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct QuarterAggregate {
    /// Quarter start, Unix seconds.
    pub start: i64,
    /// Time-weighted mean of good power values, kW; `None` without good values.
    pub mean_power_kw: Option<f64>,
    /// The last good state of charge in the quarter, %.
    pub last_soc: Option<f64>,
    /// Share of the quarter covered by good power values, 0–1.
    pub good_share: f64,
}

/// One recent instant: power and state of charge taken at the same source time.
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct Recent {
    /// Source time, Unix seconds.
    pub at: i64,
    /// Power, kW.
    pub power_kw: Option<f64>,
    /// State of charge, %.
    pub soc: Option<f64>,
}

/// An asset now: its readings and its overall quality (that of its power).
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct AssetNow {
    /// Power now.
    pub power: Option<Reading>,
    /// State of charge now (batteries).
    pub soc: Option<Reading>,
    /// Since when the asset has had no connection, Unix seconds.
    pub offline_since: Option<i64>,
    /// The asset's quality: offline without a connection or a power value, else the power's.
    pub quality: Quality,
}

impl AssetNow {
    /// An asset without data.
    #[must_use]
    pub const fn offline(since: Option<i64>) -> Self {
        Self {
            power: None,
            soc: None,
            offline_since: since,
            quality: Quality::Offline,
        }
    }

    /// Builds the asset's state from its readings.
    #[must_use]
    pub fn from_readings(power: Option<Reading>, soc: Option<Reading>) -> Self {
        Self {
            power,
            soc,
            offline_since: None,
            quality: power.map_or(Quality::Offline, |p| p.quality),
        }
    }
}

/// A closed quarter as stored: 16 bytes instead of the 48 of [`QuarterAggregate`] (SC-003).
#[derive(Debug, Clone, Copy)]
struct Packed {
    /// Quarter start / 900.
    index: u32,
    /// Mean good power, kW; NaN without good values.
    mean: f32,
    /// Last good state of charge, %; NaN without one.
    soc: f32,
    /// Good seconds, 0–900.
    good: u16,
}

/// Bytes one stored quarter takes.
pub const QUARTER_BYTES: usize = size_of::<Packed>();

impl Packed {
    fn pack(q: QuarterAggregate) -> Self {
        #[expect(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            reason = "quarters since 1970 fit u32; good seconds ≤ 900"
        )]
        Self {
            index: (q.start / QUARTER_SECS) as u32,
            mean: q.mean_power_kw.map_or(f32::NAN, |v| v as f32),
            soc: q.last_soc.map_or(f32::NAN, |v| v as f32),
            good: (q.good_share * 900.0).round() as u16,
        }
    }

    fn unpack(self) -> QuarterAggregate {
        let some = |v: f32| (!v.is_nan()).then_some(f64::from(v));
        QuarterAggregate {
            start: i64::from(self.index) * QUARTER_SECS,
            mean_power_kw: some(self.mean),
            last_soc: some(self.soc),
            good_share: f64::from(self.good) / 900.0,
        }
    }
}

#[derive(Debug, Clone, Copy)]
struct Sample {
    at: i64,
    value: f32,
    flags: Flags,
}

#[derive(Debug, Clone, Copy)]
struct Accumulator {
    start: i64,
    energy_kws: f64,
    good_secs: i64,
    last_soc: Option<f32>,
}

impl Accumulator {
    const fn new(start: i64) -> Self {
        Self {
            start,
            energy_kws: 0.0,
            good_secs: 0,
            last_soc: None,
        }
    }

    fn finish(self) -> QuarterAggregate {
        QuarterAggregate {
            start: self.start,
            #[expect(clippy::cast_precision_loss, reason = "at most 900 seconds")]
            mean_power_kw: (self.good_secs > 0).then(|| self.energy_kws / self.good_secs as f64),
            last_soc: self.last_soc.map(f64::from),
            #[expect(clippy::cast_precision_loss, reason = "at most 900 seconds")]
            good_share: (self.good_secs as f64 / QUARTER_SECS as f64).min(1.0),
        }
    }
}

#[derive(Debug, Clone)]
struct Series {
    rated_kw: f64,
    limit: i64,
    latest: [Option<Sample>; 2],
    recent: [VecDeque<(i64, f32)>; 2],
    quarters: VecDeque<Packed>,
    open: Option<Accumulator>,
    /// The last good power value: credited from `.0` to the next value or `.2` (its stale limit).
    held: Option<(i64, f32, i64)>,
    offline_since: Option<i64>,
}

impl Series {
    fn new(rated_kw: f64, limit: i64) -> Self {
        Self {
            rated_kw,
            limit,
            latest: [None, None],
            recent: [VecDeque::new(), VecDeque::new()],
            quarters: VecDeque::new(),
            open: None,
            held: None,
            offline_since: None,
        }
    }

    fn good_at_arrival(&self, q: Quantity, s: Sample) -> bool {
        classify(
            q,
            f64::from(s.value),
            s.at,
            s.at,
            self.limit,
            s.flags,
            self.rated_kw,
        ) == Quality::Good
    }

    /// The accumulator for quarter `start`, closing older ones.
    fn accumulator(&mut self, start: i64) -> Option<&mut Accumulator> {
        match self.open {
            Some(acc) if acc.start > start => return None, // out of order: ignore
            Some(acc) if acc.start < start => {
                self.quarters.push_back(Packed::pack(acc.finish()));
                // The open quarter counts against the cap too.
                while self.quarters.len() >= QUARTERS_MAX {
                    self.quarters.pop_front();
                }
                self.open = Some(Accumulator::new(start));
            }
            Some(_) => {}
            None => self.open = Some(Accumulator::new(start)),
        }
        self.open.as_mut()
    }

    /// Adds power `v` held over `[from, to)` to the quarters it spans.
    fn hold(&mut self, mut from: i64, to: i64, v: f32) {
        while from < to {
            let q = quarter_start(from);
            let end = (q + QUARTER_SECS).min(to);
            if let Some(acc) = self.accumulator(q) {
                #[expect(clippy::cast_precision_loss, reason = "at most 900 seconds")]
                let secs = (end - from) as f64;
                acc.energy_kws += f64::from(v) * secs;
                acc.good_secs += end - from;
            }
            from = end;
        }
    }

    /// Credits the held power up to `to` (bounded by its stale limit) and keeps holding from there.
    fn credit(&mut self, to: i64) {
        if let Some((from, v, until)) = self.held {
            let end = to.min(until);
            if end > from {
                self.hold(from, end, v);
                self.held = (end < until).then_some((end, v, until));
            }
        }
    }

    fn push(&mut self, q: Quantity, s: Sample) -> Pushed {
        let i = q.index();
        if let Some(l) = self.latest[i]
            && s.at < l.at
        {
            if l.at - s.at <= CLOCK_STEP_SECS {
                return Pushed::Dropped; // reordered: never rewrite the past
            }
            // The clock stepped back: what we hold is dated in the future. Start again.
            *self = Self::new(self.rated_kw, self.limit);
            self.push(q, s);
            return Pushed::Reset;
        }
        self.latest[i] = Some(s);
        let ring = &mut self.recent[i];
        while ring.front().is_some_and(|(t, _)| *t <= s.at - RECENT_SECS)
            || ring.len() >= RECENT_MAX
        {
            ring.pop_front();
        }
        ring.push_back((s.at, s.value));
        let good = self.good_at_arrival(q, s);
        // Whatever arrives, the held power is credited up to now first, so moving to a new quarter
        // never loses time in the old one.
        self.credit(s.at);
        match q {
            Quantity::Power => {
                self.held = good.then_some((s.at, s.value, s.at + self.limit));
                if good {
                    // Opens the quarter even before any time has passed in it.
                    let _ = self.accumulator(quarter_start(s.at));
                }
            }
            Quantity::Soc => {
                if good && let Some(acc) = self.accumulator(quarter_start(s.at)) {
                    acc.last_soc = Some(s.value);
                }
            }
        }
        Pushed::Stored
    }

    fn reading(&self, q: Quantity, now: i64) -> Option<Reading> {
        self.latest[q.index()].map(|s| Reading {
            value: f64::from(s.value),
            at: s.at,
            quality: classify(
                q,
                f64::from(s.value),
                s.at,
                now,
                self.limit,
                s.flags,
                self.rated_kw,
            ),
        })
    }
}

/// The live store for the declared assets.
#[derive(Debug, Clone, Default)]
pub struct Store {
    series: HashMap<AssetId, Series>,
}

impl Store {
    /// A store for `assets`: `(id, rated kW, stale limit in seconds)`. Assets start offline.
    pub fn new(assets: impl IntoIterator<Item = (AssetId, f64, i64)>) -> Self {
        Self {
            series: assets
                .into_iter()
                .map(|(id, rated, limit)| (id, Series::new(rated, limit)))
                .collect(),
        }
    }

    /// An asset's stale limit in seconds.
    #[must_use]
    pub fn limit(&self, asset: &AssetId) -> Option<i64> {
        self.series.get(asset).map(|s| s.limit)
    }

    /// Sets an asset's stale limit; `false` for an undeclared asset.
    pub fn set_limit(&mut self, asset: &AssetId, limit: i64) -> bool {
        self.series
            .get_mut(asset)
            .map(|s| s.limit = limit)
            .is_some()
    }

    /// Records a value taken at `at`.
    pub fn push(
        &mut self,
        asset: &AssetId,
        quantity: Quantity,
        value: f64,
        at: i64,
        flags: Flags,
    ) -> Pushed {
        let Some(series) = self.series.get_mut(asset) else {
            return Pushed::Undeclared;
        };
        #[expect(
            clippy::cast_possible_truncation,
            reason = "measurements fit f32; plausibility runs on the stored value"
        )]
        let value = value as f32;
        series.offline_since = None;
        series.push(quantity, Sample { at, value, flags })
    }

    /// Marks an asset as without connection since `since` — keeping the first loss when it was
    /// already offline — or connected again with `None`. Held power stops counting as good at the loss.
    pub fn set_offline(&mut self, asset: &AssetId, since: Option<i64>) {
        if let Some(s) = self.series.get_mut(asset) {
            match since {
                Some(t) => {
                    s.credit(t);
                    s.held = None;
                    s.offline_since.get_or_insert(t);
                }
                None => s.offline_since = None,
            }
        }
    }

    /// The asset as of `now`; `None` for an undeclared asset.
    #[must_use]
    pub fn now(&self, asset: &AssetId, now: i64) -> Option<AssetNow> {
        let s = self.series.get(asset)?;
        if s.offline_since.is_some() {
            return Some(AssetNow::offline(s.offline_since));
        }
        Some(AssetNow::from_readings(
            s.reading(Quantity::Power, now),
            s.reading(Quantity::Soc, now),
        ))
    }

    /// Quarter aggregates with a start in `[from, to)`, as of `now` (the open quarter partly).
    #[must_use]
    pub fn quarters(&self, asset: &AssetId, from: i64, to: i64, now: i64) -> Vec<QuarterAggregate> {
        let Some(s) = self.series.get(asset) else {
            return Vec::new();
        };
        let mut view = s.clone();
        view.credit(now);
        view.quarters
            .iter()
            .map(|p| p.unpack())
            .chain(view.open.map(Accumulator::finish))
            .filter(|q| q.start >= from && q.start < to && q.start <= now)
            .collect()
    }

    /// Recent values (≤ 15 minutes before `now`), oldest first.
    #[must_use]
    pub fn recent(&self, asset: &AssetId, now: i64) -> Vec<Recent> {
        let Some(s) = self.series.get(asset) else {
            return Vec::new();
        };
        let mut by_time: BTreeMap<i64, Recent> = BTreeMap::new();
        for q in Quantity::ALL {
            for &(at, v) in &s.recent[q.index()] {
                if at <= now - RECENT_SECS || at > now {
                    continue;
                }
                let r = by_time.entry(at).or_insert(Recent {
                    at,
                    power_kw: None,
                    soc: None,
                });
                match q {
                    Quantity::Power => r.power_kw = Some(f64::from(v)),
                    Quantity::Soc => r.soc = Some(f64::from(v)),
                }
            }
        }
        by_time.into_values().collect()
    }

    /// How many values the asset holds: `(recent power, recent soc, quarters)` — for the caps' tests.
    #[must_use]
    pub fn held(&self, asset: &AssetId) -> Option<(usize, usize, usize)> {
        self.series.get(asset).map(|s| {
            (
                s.recent[0].len(),
                s.recent[1].len(),
                s.quarters.len() + usize::from(s.open.is_some()),
            )
        })
    }
}