# flexibility
[](https://github.com/hupe1980/flexibility/actions/workflows/ci.yml)
[](https://hupe1980.github.io/flexibility/)
[](https://github.com/hupe1980/flexibility/blob/main/Cargo.toml)
[](#licence)
**Grid flexibility as exact, replayable arithmetic, in Rust.** The limits a grid operator sets,
the plan an aggregator makes, the baseline both agree on, and the settlement of what was
delivered: in whole watts, one sign convention, with a digest both sides recompute.
- **Limits and envelopes.** Caps, floors and bands per quarter hour, combined strictly; every
bound names who set it, and a § 14a minimum refuses any cap below it.
- **Baselines.** Named, versioned methods (`mbma@1`, `xofy@1`, …) with required parameters, whose
meaning never changes.
- **Settlement.** Delivered flexibility and power deficiency exactly as UFTP 3.1 § 2.6 computes
them, with a canonical receipt and a `sha256:` digest anyone can reproduce.
- **Protocols.** UFTP, EEBUS, S2, OpenADR 3, CSIP-AUS, IEC 104 and CLS.EEDI in and out, each
behind a feature, lossless or refusing.
**[Documentation](https://hupe1980.github.io/flexibility/)** ·
[Getting started](https://hupe1980.github.io/flexibility/docs/getting-started/) ·
[API reference](https://docs.rs/flexibility) · [Changelog](CHANGELOG.md)
> **Status:** 0.1, early. The API may change before 1.0; what a method id or a canonical text
> computes does not.
## Install
```sh
cargo add flexibility
# with converters, for example:
cargo add flexibility --features uftp,eebus,s2,openadr,csip,iec104,cls,metering
```
Rust 1.88 or later, for every feature. The default build depends on [`jiff`](https://docs.rs/jiff)
(time, with the zone database bundled) and `sha2`.
## A cap, a plan, and who set the limit
```rust
use flexibility::jiff::{civil::{date, time}, tz::TimeZone};
use flexibility::*;
let berlin = TimeZone::get("Europe/Berlin")?;
let grid = Grid::day(date(2026, 12, 1), &berlin, IspDuration::FIFTEEN_MINUTES)?;
let noon = grid.local(time(12, 0, 0, 0))?;
// The grid operator caps consumption at 4.2 kW from 17:00 to 19:00, local time.
let evening = grid.window(time(17, 0, 0, 0), time(19, 0, 0, 0))?;
let dso = Provenance::new("dso.example", "order-42", noon);
let envelope = Envelope::unbounded(grid.clone()).apply(&Limit::consumption_cap(evening, kw!(4.2), dso))?;
// A car planned at 7.4 kW all evening breaks it in ISPs 69 to 76, and says who set the cap.
let plan = Schedule::new(Series::filled(grid, kw!(7.4)), Provenance::new("agr.example", "plan-7", noon));
let violations = plan.check(&envelope)?;
assert_eq!(violations.len(), 8);
assert_eq!(
violations[0].to_string(),
"ISP 69 (17:00–17:15 +01:00): planned 7.4 kW above max 4.2 kW set by dso.example order-42"
);
# Ok::<(), Box<dyn std::error::Error>>(())
```
## Settle an order, and prove it
```rust
use flexibility::baseline::{self, Mbma};
use flexibility::jiff::{civil::{date, time}, tz::TimeZone};
use flexibility::*;
let berlin = TimeZone::get("Europe/Berlin")?;
let grid = Grid::day(date(2026, 12, 1), &berlin, IspDuration::FIFTEEN_MINUTES)?;
let evening = grid.window(time(17, 0, 0, 0), time(19, 0, 0, 0))?;
// The DSO ordered 3 kW less; the contract names mbma@1 with n = 4, gap = 1. No defaults.
let base = baseline::mbma(&measured, evening, Mbma { n: 4, gap: 1 })?;
let actual = measured.over(evening)?;
let ordered = Series::filled(actual.grid().clone(), Deviation::from_watts(-3_000));
let settlement = settle(&base, &actual, &ordered, MeasurementPoint::ConnectionPoint)?;
assert_eq!(
settlement.lines()[0].to_string(),
"ISP 69 (17:00–17:15 +01:00): baseline 7 kW, actual 4.5 kW, ordered -3 kW, delivered -2.5 kW, deficiency 500 W"
);
// One hash the aggregator compares; `scripts/digest.sh` reproduces it from the canonical text.
println!("{}", settlement.digest());
# Ok::<(), Box<dyn std::error::Error>>(())
```
## Read what the other side sent, and find where you disagree
```rust
# use flexibility::baseline::{self, Mbma};
# use flexibility::jiff::{civil::{date, time}, tz::TimeZone};
# use flexibility::*;
# let berlin = TimeZone::get("Europe/Berlin")?;
# let grid = Grid::day(date(2026, 12, 1), &berlin, IspDuration::FIFTEEN_MINUTES)?;
# let evening = grid.window(time(17, 0, 0, 0), time(19, 0, 0, 0))?;
# let settle_with = |isp71| -> Result<Settlement, Error> {
# let m = Series::new(grid.clone(), grid.numbers().map(|i| match i { 71 => isp71, 69..=76 => kw!(4.5), _ => kw!(7) }).collect())?;
# let actual = m.over(evening)?;
# let ordered = Series::filled(actual.grid().clone(), Deviation::from_watts(-3_000));
# settle(&baseline::mbma(&m, evening, Mbma { n: 4, gap: 1 })?, &actual, &ordered, MeasurementPoint::ConnectionPoint)
# };
# let text = settle_with(kw!(4.4))?.canonical();
# let ours = settle_with(kw!(4.5))?;
// The DSO sent `text`, its settlement's canonical JSON. Edited or re-encoded bytes are refused.
let theirs = Settlement::from_canonical(&text, berlin)?;
assert_eq!(theirs.digest(), Digest::of(text.as_bytes()));
assert_eq!(
ours.diff(&theirs).map(|d| d.to_string()).as_deref(),
Some("ISP 71 (17:30–17:45 +01:00): actual ours 4.5 kW, theirs 4.4 kW")
);
# Ok::<(), Box<dyn std::error::Error>>(())
```
## Protocols
| Feature | Protocol | What it maps |
|---|---|---|
| `uftp` | UFTP 3.1 (Shapeshifter) | FlexRequest → deviation envelope; offers and orders; the `FlexOrderSettlement` item; checking a received settlement |
| `eebus` | EEBUS LPC, LPP | active and failsafe power limits, both ways |
| `s2` | S2 (EN 50491-12-2) | PEBC power envelopes both ways; PPBC power sequences as schedules |
| `openadr` | OpenADR 3 | import and export capacity limits, both ways; usage reports as power |
| `csip` | CSIP-AUS (IEEE 2030.5) | dynamic operating envelopes at the connection point |
| `iec104` | IEC 60870-5-104 | active-power set points (types 48–50), both ways |
| `cls` | CLS.EEDI | control-box limits and failsafes, both ways |
| `metering` | German metering rules | the § 14a minimum as a guarantee; Lastgang energy as power |
## Why you can trust the numbers
- **Exact.** Integers throughout; no floating-point arithmetic. A float on the wire is read
once, as the decimal written. A remainder is refused unless you name a rounding.
- **Pure.** No clock, file, network, environment or randomness: the same inputs give the same
bytes on every machine, so a settlement replays years later.
- **One sign.** Consumption is positive, feed-in negative, everywhere; converters change sign at
the boundary and nowhere else.
- **Refusal over invention.** A missing quarter hour, an unknown unit or an ambiguous control is
an error that names the values and offers a `hint()`, never a guess.
- **Checked.** Unit and property tests, a snapshot per method id, the UFTP specification's own
settlement table and each protocol's published examples, with every feature on the MSRV in CI.
## Examples
Each asserts its own results.
| Command | Shows |
|---|---|
| `cargo run --example evening_cap` | a DSO cap, a connection limit and a § 14a guarantee; `explain` and `headroom` |
| `cargo run --example settle_an_order` | an `mbma@1` baseline, a settlement, one digest, the rebound |
| `cargo run --example verify_a_receipt` | read the other side's settlement and diff it |
| `cargo run --example charge_by_seven` | an EV's departure energy, a pool and a split |
| `cargo run --features uftp --example check_a_settlement` | a FlexOrder to a settlement item `uftp` accepts |
| `cargo run --features eebus,metering --example control_box` | a § 14a control box: minimum, LPC limit, failsafe, Lastgang |
| `cargo run --features openadr,s2 --example curtail_pv` | a VTN's export cap sent to a PV inverter over S2 |
## Licence
Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or
[MIT licence](LICENSE-MIT) at your option. Unless you explicitly state otherwise, any
contribution intentionally submitted for inclusion in this work, as defined in the Apache-2.0
licence, shall be dual licensed as above, without any additional terms or conditions.