Skip to main content

smgw_cls/fnn/
fsch.rs

1//! Import a fixed-start daily FSCH price schedule into the local tariff lookup.
2//!
3//! Both readers verify the closing header, apply the caller's policy to the original
4//! start timestamp, then classify prices in the contracted unit. The provider must
5//! keep individual prices stable throughout the read. Replace the active schedule
6//! only after the import succeeds.
7use std::io::{Read, Write};
8use std::ops::{ControlFlow, Range};
9
10use iec61850_kit::client::{Client, TariffSchedule};
11use iec61850_kit::proto::data::Value;
12use iec61850_kit::{Error, Fc, Result, UtcTime};
13
14pub use iec61850_kit::client::{TariffProfile, TariffRead};
15
16use super::tariff::{TariffLevel, TariffWindow};
17
18/// Read the provider's UTC delivery window on an associated blocking MMS client.
19///
20/// For a synchronized, working clock, use
21/// `|t| !t.quality.clock_not_synchronized && !t.quality.clock_failure`.
22/// Returning `None` from `classify` rejects the entire import.
23pub fn read_tariff_windows<S: Read + Write>(
24    client: &mut Client<S>,
25    node: &str,
26    profile: TariffProfile<'_>,
27    delivery_day: Range<u32>,
28    accept_start: impl FnOnce(UtcTime) -> bool,
29    classify: impl FnMut(f64) -> Option<TariffLevel>,
30) -> Result<Vec<TariffWindow>> {
31    let schedule = client.read_tariff_schedule(node, profile, delivery_day)?;
32    tariff_windows(schedule, accept_start, classify)
33}
34
35/// Drive a configured [`TariffRead`] using an existing asynchronous MMS association.
36///
37/// For each batch, `read_fields` issues one MMS Read and returns decoded values in
38/// request order or the original MMS error. The association driver owns invoke-ID
39/// matching, deadlines and in-flight request cleanup on cancellation. Dropping
40/// this future discards the unfinished schedule.
41///
42/// ```
43/// use smgw_cls::fnn::fsch::{TariffProfile, TariffRead, read_tariff_windows_async};
44/// use smgw_cls::fnn::tariff::TariffLevel;
45/// # use iec61850_kit::{Fc, Result, proto::data::Value};
46/// # async fn import(read_fields: impl AsyncFnMut(&[(String, Fc)]) -> Result<Vec<Value>>)
47/// # -> Result<()> {
48/// let profile = TariffProfile { first_price: "ValING1", ..TariffProfile::new("ct/kWh") };
49/// let read = TariffRead::new("CLSLD0/FSCH1", profile, 86_400..172_800)?;
50/// let windows = read_tariff_windows_async(
51///     read, read_fields,
52///     |t| !t.quality.clock_failure && !t.quality.clock_not_synchronized,
53///     |price| match price {
54///         6.0 => Some(TariffLevel::Low),
55///         12.0 => Some(TariffLevel::Standard),
56///         18.0 => Some(TariffLevel::High),
57///         _ => None,
58///     },
59/// ).await?;
60/// # Ok(()) }
61/// ```
62pub async fn read_tariff_windows_async(
63    mut read: TariffRead<'_>,
64    mut read_fields: impl AsyncFnMut(&[(String, Fc)]) -> Result<Vec<Value>>,
65    accept_start: impl FnOnce(UtcTime) -> bool,
66    classify: impl FnMut(f64) -> Option<TariffLevel>,
67) -> Result<Vec<TariffWindow>> {
68    loop {
69        let response = read_fields(&read.fields()).await;
70        match read.accept(response)? {
71            ControlFlow::Continue(next) => read = next,
72            ControlFlow::Break(schedule) => {
73                return tariff_windows(schedule, accept_start, classify);
74            }
75        }
76    }
77}
78
79fn tariff_windows(
80    schedule: TariffSchedule,
81    accept_start: impl FnOnce(UtcTime) -> bool,
82    mut classify: impl FnMut(f64) -> Option<TariffLevel>,
83) -> Result<Vec<TariffWindow>> {
84    if !accept_start(schedule.start) {
85        return Err(Error::InvalidValue("rejected FSCH start timestamp"));
86    }
87    schedule
88        .slots
89        .into_iter()
90        .map(|slot| {
91            let level =
92                classify(slot.price).ok_or(Error::InvalidValue("unmapped FSCH tariff price"))?;
93            Ok(TariffWindow {
94                start_utc: i64::from(slot.utc.start),
95                end_utc: i64::from(slot.utc.end),
96                level,
97            })
98        })
99        .collect()
100}