flexibility 0.4.0

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, CSIP-AUS, IEC 104, CLS.EEDI converters.
Documentation
//! A site energy manager receives an OpenADR export cap from the grid operator, combines it
//! with the PV array's own range, and instructs the inverter over S2. Run with
//! `cargo run --features openadr,s2 --example curtail_pv`.

use flexibility::jiff::tz::TimeZone;
use flexibility::openadr::{self, wire as adr};
use flexibility::s2::{self, wire as s2w};
use flexibility::{Envelope, Grid, IspDuration, Limit, Provenance, Window, kw, w};
use s2w::types::{CommodityQuantity, Id};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let berlin = TimeZone::get("Europe/Berlin")?;
    let noon: flexibility::jiff::Timestamp = "2026-06-01T10:00:00Z".parse()?;
    let grid = Grid::new(noon, IspDuration::FIFTEEN_MINUTES, 8, berlin)?;
    let window = Window::new(grid.start(), grid.end())?;

    // The VTN: feed in at most 4 kW from 12:30 for an hour (OpenADR 3, as sent).
    let event: adr::model::Event = serde_json::from_str(
        r#"{"id": "noon-cap", "programID": "solar-peak",
            "createdDateTime": "2026-06-01T06:00:00Z", "modificationDateTime": "2026-06-01T06:00:00Z",
            "payloadDescriptors": [{"payloadType": "EXPORT_CAPACITY_LIMIT", "units": "KW"}],
            "intervalPeriod": {"start": "2026-06-01T10:30:00Z", "duration": "PT1H"},
            "intervals": [{"id": 0, "payloads": [{"type": "EXPORT_CAPACITY_LIMIT", "values": [4]}]}]}"#,
    )?;
    let vtn = Provenance::new("vtn.example", "noon-cap", noon);
    let caps = openadr::limits(&event.content, None, window, noon, &vtn)?;

    // The array: 0 to 10 kW of feed-in, never consumption.
    let array = Provenance::new("site.example", "pv-10kWp", noon);
    let range = Limit::band(window, kw!(-10), w!(0), array)?;
    let envelope = std::iter::once(&range)
        .chain(&caps)
        .try_fold(Envelope::unbounded(grid.clone()), |e, l| e.apply(l))?;
    for isp in grid.numbers() {
        let why = envelope.explain(isp).ok_or("ISP on the grid")?.to_string();
        println!("{}", why.lines().next().unwrap_or_default());
    }

    // To the inverter: one S2 element per run of equal bounds, from the grid's start.
    let pe = s2::power_envelope(
        &envelope,
        Id::new_const("pe-noon"),
        CommodityQuantity::ElectricPower3PhaseSymmetric,
    )?;
    for e in &pe.power_envelope_elements {
        println!(
            "S2: {} min between {} W and {} W",
            e.duration.as_millis() / 60_000,
            e.lower_limit,
            e.upper_limit
        );
    }
    assert_eq!(pe.power_envelope_elements.len(), 3);
    Ok(())
}