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 behind a § 14a control box: the heat pump's minimum comes from
//! `metering`, the grid operator's limit arrives as an EEBUS LPC write, and the evening's
//! Lastgang becomes actual power. Run with
//! `cargo run --features eebus,metering --example control_box`.

use std::time::Duration;

use flexibility::eebus::{self, Direction, LimitWrite};
use flexibility::jiff::civil::{date, time};
use flexibility::jiff::tz::TimeZone;
use flexibility::metering::{self, wire};
use flexibility::{Envelope, Grid, IspDuration, Provenance, Rounding, Schedule, Series, kw};
use wire::grid::para14a::{
    Anlage, Para14aConfig, SteuVeFallgruppe, mindestleistung_direktansteuerung,
    steuerbare_verbrauchseinrichtungen,
};
use wire::{DayBoundary, MeterInterval, ObisCode, QualityFlag, Resolution, dec};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let berlin = TimeZone::get("Europe/Berlin")?;
    let day = Grid::day(date(2026, 12, 1), &berlin, IspDuration::FIFTEEN_MINUTES)?;
    let whole_day = day.window(time(0, 0, 0, 0), time(0, 0, 0, 0))?;
    let received = day.local(time(17, 0, 0, 0))?;

    // The § 14a minimum of a 20.001 kW heat pump: 0,4 × 20,001 kW, kept to the watt above.
    let pump = steuerbare_verbrauchseinrichtungen(&[Anlage::new(
        SteuVeFallgruppe::Waermepumpe,
        dec!(20.001),
    )])
    .ok_or("no controllable device")?;
    let minimum = mindestleistung_direktansteuerung(&pump[0], &Para14aConfig::VERMUTUNG);
    let rule = Provenance::new("bnetza.de", "BK6-22-300 Anlage 1 Ziff. 4.5", received);
    let guarantee = metering::guarantee(minimum, whole_day, rule)?;
    println!("guarantee: {} ({minimum})", guarantee.power());

    // The control box writes LPC: 8.5 kW for two hours.
    let dso = Provenance::new("dso.example", "lpc-2026-12-01-17", received);
    let write = LimitWrite::active_for(8_500, Duration::from_secs(7_200));
    let cap = eebus::limit(
        Direction::Consumption,
        &write,
        received,
        day.end(),
        Rounding::Exact,
        dso.clone(),
    )?
    .ok_or("deactivated")?;
    let site = Envelope::unbounded(day.clone())
        .guarantee(&guarantee)?
        .apply(&cap)?;

    // The plan: the heat pump at 11 kW all evening. Where does it break the cap, and why?
    let plan = Schedule::new(
        Series::filled(day.clone(), kw!(11)),
        Provenance::new("ems.local", "plan-1", received),
    );
    let violations = plan.check(&site)?;
    println!(
        "{} ISPs over the cap, first: {}",
        violations.len(),
        violations[0]
    );
    println!(
        "{}",
        site.explain(violations[0].label.isp()).ok_or("no ISP")?
    );

    // The failsafe the box would fall back to must keep the minimum too.
    let fallback = day.window(time(17, 0, 0, 0), time(19, 0, 0, 0))?;
    let failsafe = eebus::failsafe(
        Direction::Consumption,
        4_200,
        fallback,
        Rounding::Exact,
        dso,
    )?;
    if let Err(e) = site.apply(&failsafe) {
        println!("failsafe refused: {e}");
    }

    // After the event: the Lastgang of 17:00–18:00 as average power, for settlement.
    let hour = day.slice(69..=72)?;
    let intervals = hour
        .numbers()
        .map(|isp| {
            let iv = hour.interval(isp).ok_or("no ISP")?;
            Ok(
                MeterInterval::new(iv.from(), iv.until(), dec!(2.125), QualityFlag::Measured)?
                    .with_obis(ObisCode::STROM_BEZUG_LASTGANG),
            )
        })
        .collect::<Result<Vec<_>, Box<dyn std::error::Error>>>()?;
    let lastgang = wire::Series::new(Resolution::QUARTER_HOUR, DayBoundary::Strom, intervals)?;
    let actual = metering::power(&[&lastgang], &hour, Rounding::Exact)?;
    println!("actual: {} per ISP of {hour}", actual.values()[0]);
    Ok(())
}