metering 0.19.0

German energy metering domain library — DST-correct Europe/Berlin calendar arithmetic on both the Liefertag and the 06:00 Gastag, gas m3→kWh_Hs conversion, SigLinDe gas SLP, billing-period aggregation, Ersatzwertbildung, a robust validation engine, check-digit-validated MaLo-IDs, Bundesland holiday calendar and SLP/RLM/iMSys classification. Zero I/O, no async, no clock, exact decimal quantities.
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
//! Measurement point — what is being metered, and on whose account.
//!
//! A [`MeasurementPoint`] binds one **OBIS register** on one meter to the
//! market location it is billed against, for a stated validity period. It is
//! the structural context that turns a bare [`crate::MeterInterval`] into a
//! reading somebody can invoice.
//!
//! ## One type, one direction enum
//!
//! [`EnergyFlow`] is the only direction enum here, and the register unit is
//! **derived** from the OBIS code
//! ([`ObisCode::register_unit`](crate::ObisCode::register_unit)) rather than
//! stored — a stored unit can contradict the code that determines it.
//!
//! ## Relationship to MSCONS
//!
//! In MSCONS, each time series is identified by:
//! - `NAD+MS/MR` — sender/receiver market participant
//! - `LOC+172` — Marktlokations-ID (MaLo)
//! - `LOC+237` — Messlokations-ID (MeLo, optional)
//! - `PIA` — OBIS code
//!
//! `MeasurementPoint` binds all four together for a specific validity period.
//!
//! ## Multiple registers per MeLo
//!
//! A MeLo can have multiple registers at the same timestamp — e.g. HT (register 1)
//! and NT (register 2). Each register is a distinct `MeasurementPoint` with a
//! different OBIS code but the same MaLo and MeLo.
//!
//! ## Regulatory basis
//!
//! - **§ 2 MsbG**: MeLo is the physical measurement reference.
//! - **BDEW MaKo**: MaLo is the billing reference.
//! - **BSI TR-03109**: Zählpunkt-ID ties MeLo to the SMGW.

use rust_decimal::Decimal;
use time::Date;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

use crate::ids::{MaloId, MeloId};
use crate::interval::Sparte;
use crate::obis::{ObisCode, RegisterUnit};

// ── MarktRolle ────────────────────────────────────────────────────────────────

/// Market role responsible for this measurement point.
///
/// Governs which entity owns the metering obligation and which processes
/// are triggered by changes (Messstellen­betreiberwechsel, Lieferbeginn, etc.).
///
/// Source: BDEW Rollenmodell V2.2 §2.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "SCREAMING_SNAKE_CASE"))]
pub enum MarktRolle {
    /// Netzbetreiber — owns grid metering for supply accounting.
    Nb,
    /// Lieferant — owns load forecasting and billing.
    Lf,
    /// Messstellenbetreiber — physically operates the meter.
    Msb,
    /// Bilanzkreisverantwortlicher — balance group management.
    Bkv,
    /// Übertragungsnetzbetreiber (Strom) / FNB (Gas).
    #[cfg_attr(feature = "serde", serde(rename = "UENB"))]
    Uenb,
    /// Einspeiseverantwortlicher — responsible for feed-in control.
    Eiv,
    /// Direktvermarkter — direct marketing of renewable energy.
    #[cfg_attr(feature = "serde", serde(rename = "DV"))]
    Direktvermarkter,
    /// Marktgebietsverantwortlicher (Gas).
    Mgv,
    /// Energieserviceanbieter des Anschlussnutzers (iMSys context).
    Esa,
}

impl MarktRolle {
    /// Every role, in declaration order.
    pub const ALL: [Self; 9] = [
        Self::Nb,
        Self::Lf,
        Self::Msb,
        Self::Bkv,
        Self::Uenb,
        Self::Eiv,
        Self::Direktvermarkter,
        Self::Mgv,
        Self::Esa,
    ];

    /// Stable DB/wire label. Matches the `serde` tag and
    /// [`FromStr`](std::str::FromStr) input.
    ///
    /// ASCII, unlike [`abbreviation`](Self::abbreviation), which writes the
    /// BDEW spelling `ÜNB`. A code that a database column, a CLI argument and
    /// a URL path segment all have to survive is not the place for an umlaut;
    /// `FromStr` accepts `ÜNB` as a lenient input alias.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Nb => "NB",
            Self::Lf => "LF",
            Self::Msb => "MSB",
            Self::Bkv => "BKV",
            Self::Uenb => "UENB",
            Self::Eiv => "EIV",
            Self::Direktvermarkter => "DV",
            Self::Mgv => "MGV",
            Self::Esa => "ESA",
        }
    }

    /// BDEW abbreviation, as printed in the Rollenmodell — `ÜNB` with the
    /// umlaut. For a stored code use [`as_str`](Self::as_str).
    #[must_use]
    pub const fn abbreviation(self) -> &'static str {
        match self {
            Self::Nb => "NB",
            Self::Lf => "LF",
            Self::Msb => "MSB",
            Self::Bkv => "BKV",
            Self::Uenb => "ÜNB",
            Self::Eiv => "EIV",
            Self::Direktvermarkter => "DV",
            Self::Mgv => "MGV",
            Self::Esa => "ESA",
        }
    }

    /// `true` for roles that receive meter data via MSCONS.
    ///
    /// The ÜNB is one of them: under MaBiS the Netzbetreiber transmits the
    /// Bilanzierungs-Summenzeitreihen to the ÜNB as Bilanzkoordinator via
    /// MSCONS, and the ÜNB acknowledges them — it is a receiver in exactly the
    /// sense this predicate answers.
    #[must_use]
    pub fn is_mscons_receiver(self) -> bool {
        matches!(
            self,
            Self::Lf | Self::Bkv | Self::Mgv | Self::Direktvermarkter | Self::Uenb
        )
    }
}

// ── EnergyFlow ────────────────────────────────────────────────────────────────

/// Which way energy flows at this measurement point.
///
/// The **one** direction enum in this crate. It is master data — a statement of
/// what the point is for — and the OBIS code is the metered fact. Where the two
/// disagree, [`MeasurementPoint::is_bezug`] and
/// [`is_einspeisung`](MeasurementPoint::is_einspeisung) believe the code.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "SCREAMING_SNAKE_CASE"))]
pub enum EnergyFlow {
    /// Consumption — energy drawn from the grid.
    Consumption,
    /// Generation — energy fed into the grid (Einspeisung).
    Generation,
    /// Storage charging. Consumption from the grid's point of view, kept
    /// distinct because EEG and Redispatch treat a battery differently from a
    /// load.
    StorageCharge,
    /// Storage discharging. Generation from the grid's point of view.
    StorageDischarge,
    /// Bidirectional — a four-quadrant meter at one connection point, where
    /// neither direction is the point's purpose.
    Bidirectional,
}

impl EnergyFlow {
    /// Stable DB/wire label. Matches the `serde` tag and
    /// [`FromStr`](std::str::FromStr) input.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Consumption => "CONSUMPTION",
            Self::Generation => "GENERATION",
            Self::StorageCharge => "STORAGE_CHARGE",
            Self::StorageDischarge => "STORAGE_DISCHARGE",
            Self::Bidirectional => "BIDIRECTIONAL",
        }
    }

    /// Every variant, in declaration order.
    pub const ALL: [Self; 5] = [
        Self::Consumption,
        Self::Generation,
        Self::StorageCharge,
        Self::StorageDischarge,
        Self::Bidirectional,
    ];

    /// `true` when energy flows out of the grid at this point — consumption,
    /// or a storage unit charging.
    #[must_use]
    pub const fn draws_from_grid(self) -> bool {
        matches!(self, Self::Consumption | Self::StorageCharge)
    }

    /// `true` when energy flows into the grid at this point — generation, or a
    /// storage unit discharging.
    #[must_use]
    pub const fn feeds_grid(self) -> bool {
        matches!(self, Self::Generation | Self::StorageDischarge)
    }

    /// `true` for a storage point in either direction.
    #[must_use]
    pub const fn is_storage(self) -> bool {
        matches!(self, Self::StorageCharge | Self::StorageDischarge)
    }
}

crate::codes::string_codes! {
    MarktRolle, aliases = [("ÜNB", Self::Uenb)];
    EnergyFlow;
}

// ── MeasurementPoint ─────────────────────────────────────────────────────────

/// The complete regulatory and physical context for a meter register.
///
/// Binds together: Marktlokation (MaLo), Messlokation (MeLo), OBIS register,
/// accountable market role, and energy flow direction.
///
/// ## Bitemporal validity
///
/// `valid_from` / `valid_to` track when this configuration was active.
/// This is essential for:
/// - Meter exchange events (MeLo changes, MSB change per WiM process)
/// - Supplier switch (Lieferbeginn/-ende)
/// - Register reconfiguration (HT↔NT tariff changes per §14a)
///
/// ## Virtual meters
///
/// Virtual meters (GGV community solar, Residuallast) also have `MeasurementPoint`
/// entries with `is_virtual = true`. Their `obis_code` is a conventional code
/// like `1-0:1.8.0` (total import) since virtual meters are logical.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MeasurementPoint {
    /// Marktlokations-ID (billing reference).
    ///
    /// A [`MaloId`], not a `String`: the check digit is verified at the parse,
    /// so a transposed digit is rejected at the boundary instead of becoming a
    /// plausible-looking key for the wrong delivery point.
    pub malo_id: MaloId,

    /// Messlokations-ID (physical metering reference).
    ///
    /// `None` for SLP customers without an explicit MeLo.
    pub melo_id: Option<MeloId>,

    /// Physical meter serial number.
    ///
    /// `None` for virtual meters or when meter identity is not yet known.
    pub meter_serial: Option<String>,

    /// OBIS code identifying this register on the meter.
    pub obis_code: ObisCode,

    /// Energy commodity.
    pub sparte: Sparte,

    /// Energy flow direction for this register.
    pub energy_flow: EnergyFlow,

    /// Market role accountable for this measurement point.
    pub accountable_role: MarktRolle,

    /// 13-digit BDEW or DVGW Codenummer of the accountable market participant.
    pub accountable_mp_id: String,

    /// `true` when this is a virtual/derived measurement point (GGV, Residuallast).
    pub is_virtual: bool,

    /// Multiplier from the raw counter display to the real quantity
    /// (Wandlerfaktor).
    ///
    /// `1` for direct metering; 100–1000 for a Wandlermessung. **Every
    /// [`MeterInterval`](crate::MeterInterval) in this crate is post-Wandler**:
    /// the factor is applied when the counter is read, so this field is
    /// traceability, and applying it a second time inflates consumption by the
    /// factor.
    pub wandler_factor: Decimal,

    /// Validity start (German local date, inclusive).
    pub valid_from: Date,

    /// Validity end (German local date, inclusive).
    ///
    /// `None` = still active.
    pub valid_to: Option<Date>,
}

impl MeasurementPoint {
    /// `true` when this point is active on the given date.
    #[must_use]
    pub fn is_active(&self, on_date: Date) -> bool {
        on_date >= self.valid_from && self.valid_to.is_none_or(|end| on_date <= end)
    }

    /// `true` when this point measures Bezug — energy drawn from the grid.
    ///
    /// Decided by the **OBIS code**, which is the metered fact (direction is
    /// value group C — see [`ObisCode::is_import`]), falling back to
    /// [`energy_flow`](Self::energy_flow) only when the code carries no
    /// direction, as a gas or heat code does not.
    ///
    /// Mutually exclusive with [`is_einspeisung`](Self::is_einspeisung) by
    /// construction: a pair of predicates that can both be true is worse than
    /// either being wrong, because nothing downstream can detect the
    /// contradiction.
    #[must_use]
    pub fn is_bezug(&self) -> bool {
        if self.obis_code.is_import() {
            return true;
        }
        if self.obis_code.is_export() {
            return false;
        }
        matches!(self.energy_flow, EnergyFlow::Consumption)
    }

    /// `true` when this point measures Einspeisung — energy fed into the grid.
    ///
    /// The mirror of [`is_bezug`](Self::is_bezug), and mutually exclusive with
    /// it by construction.
    #[must_use]
    pub fn is_einspeisung(&self) -> bool {
        if self.obis_code.is_export() {
            return true;
        }
        if self.obis_code.is_import() {
            return false;
        }
        matches!(self.energy_flow, EnergyFlow::Generation)
    }

    /// `true` when this point measures Blindarbeit / Blindleistung —
    /// electricity C = 3…8, including the Q I–Q IV quadrant registers.
    #[must_use]
    pub fn is_reactive(&self) -> bool {
        self.obis_code.is_reactive()
    }

    /// `true` when this point measures Gas.
    #[must_use]
    pub fn is_gas(&self) -> bool {
        matches!(self.sparte, Sparte::Gas)
    }

    /// The unit this register counts in, derived from the OBIS code.
    ///
    /// `None` for a code whose unit this crate cannot name — see
    /// [`ObisCode::register_unit`].
    #[must_use]
    pub fn unit(&self) -> Option<RegisterUnit> {
        self.obis_code.register_unit()
    }

    /// Tariff register: `None` for the total, `Some(1)` for HT, `Some(2)` for
    /// NT — see [`ObisCode::tariff_register`].
    #[must_use]
    pub fn tariff_register(&self) -> Option<u8> {
        self.obis_code.tariff_register()
    }

    /// Apply the Wandlerfaktor to a raw counter reading.
    ///
    /// Only ever call this on a value straight off the meter display. Values
    /// that reach [`MeterInterval`](crate::MeterInterval) have already had it
    /// applied.
    #[must_use]
    pub fn apply_wandler(&self, raw_display_value: Decimal) -> Decimal {
        raw_display_value * self.wandler_factor
    }
}

// ── tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use rust_decimal::dec;
    use time::macros::date;

    fn bezug_point() -> MeasurementPoint {
        MeasurementPoint {
            malo_id: "51238696781".parse().unwrap(),
            melo_id: Some("DE00056266802AO6G56M11SN51G21M24S".parse().unwrap()),
            meter_serial: Some("MSN-001".to_owned()),
            obis_code: ObisCode::STROM_BEZUG_TOTAL,
            sparte: Sparte::Strom,
            energy_flow: EnergyFlow::Consumption,
            accountable_role: MarktRolle::Lf,
            accountable_mp_id: "9900987654321".to_owned(),
            is_virtual: false,
            wandler_factor: Decimal::ONE,
            valid_from: date!(2026 - 01 - 01),
            valid_to: None,
        }
    }

    #[test]
    fn active_within_validity() {
        let mp = bezug_point();
        assert!(mp.is_active(date!(2026 - 06 - 15)));
    }

    #[test]
    fn inactive_before_valid_from() {
        let mp = bezug_point();
        assert!(!mp.is_active(date!(2025 - 12 - 31)));
    }

    #[test]
    fn inactive_after_valid_to() {
        let mut mp = bezug_point();
        mp.valid_to = Some(date!(2026 - 06 - 30));
        assert!(!mp.is_active(date!(2026 - 07 - 01)));
        assert!(mp.is_active(date!(2026 - 06 - 30)));
    }

    #[test]
    fn bezug_detection() {
        let mp = bezug_point();
        assert!(mp.is_bezug());
        assert!(!mp.is_einspeisung());
    }

    #[test]
    fn einspeisung_detection() {
        let mut mp = bezug_point();
        mp.obis_code = ObisCode::STROM_EINSPEISUNG_TOTAL;
        mp.energy_flow = EnergyFlow::Generation;
        assert!(mp.is_einspeisung());
        assert!(!mp.is_bezug());
    }

    #[test]
    fn gas_detection() {
        let mut mp = bezug_point();
        mp.sparte = Sparte::Gas;
        mp.obis_code = ObisCode::GAS_VOLUME_M3;
        assert!(mp.is_gas());
    }

    #[test]
    fn virtual_meter_flag() {
        let mut mp = bezug_point();
        mp.is_virtual = true;
        assert!(mp.is_virtual);
    }

    /// The unit is read off the OBIS code, so it cannot contradict it — the
    /// failure a stored `unit` field made possible.
    #[test]
    fn the_unit_is_derived_from_the_obis_code() {
        let mut mp = bezug_point();
        assert_eq!(mp.unit(), Some(RegisterUnit::KiloWattHour));

        mp.obis_code = ObisCode::STROM_BLINDARBEIT_Q1;
        assert_eq!(mp.unit(), Some(RegisterUnit::KiloVarHour));

        mp.obis_code = ObisCode::STROM_BEZUG_MAXIMUM;
        assert_eq!(mp.unit(), Some(RegisterUnit::KiloWatt));
        assert!(!mp.unit().unwrap().is_cumulative(), "a maximum is a power");

        mp.obis_code = ObisCode::GAS_VOLUME_M3;
        assert_eq!(mp.unit(), Some(RegisterUnit::CubicMetre));

        mp.obis_code = ObisCode::WAERME_ENERGY;
        assert_eq!(mp.unit(), Some(RegisterUnit::KiloWattHourThermal));
    }

    /// The Wandlerfaktor, and the direction predicates the merged type
    /// inherited from `MeterRegister`.
    #[test]
    fn the_merged_type_carries_the_register_facts() {
        let mut mp = bezug_point();
        mp.wandler_factor = dec!(100);
        assert_eq!(mp.apply_wandler(dec!(1234)), dec!(123400));

        assert_eq!(mp.tariff_register(), None, "1-0:1.8.0 is the total");
        mp.obis_code = ObisCode::STROM_BEZUG_HT;
        assert_eq!(mp.tariff_register(), Some(1));
        mp.obis_code = ObisCode::STROM_BEZUG_NT;
        assert_eq!(mp.tariff_register(), Some(2));
    }

    /// The direction predicates are mutually exclusive — the invariant that
    /// had to be fixed twice while the concept existed twice.
    #[test]
    fn direction_predicates_are_mutually_exclusive() {
        let mut mp = bezug_point();
        // Master data and the OBIS code disagree on purpose.
        mp.energy_flow = EnergyFlow::Generation;
        mp.obis_code = ObisCode::STROM_BEZUG_TOTAL;
        assert!(mp.is_bezug(), "the metered code wins");
        assert!(!mp.is_einspeisung());

        // ...and where the code carries no direction, the master data decides.
        mp.obis_code = ObisCode::GAS_VOLUME_M3;
        assert!(!mp.is_bezug());
        assert!(mp.is_einspeisung());

        for flow in EnergyFlow::ALL {
            mp.energy_flow = flow;
            assert!(
                !(mp.is_bezug() && mp.is_einspeisung()),
                "{flow:?} must not be both"
            );
        }
    }

    #[test]
    fn energy_flow_groups_storage_with_the_direction_it_acts_in() {
        assert!(EnergyFlow::Consumption.draws_from_grid());
        assert!(EnergyFlow::StorageCharge.draws_from_grid());
        assert!(EnergyFlow::Generation.feeds_grid());
        assert!(EnergyFlow::StorageDischarge.feeds_grid());
        assert!(!EnergyFlow::Bidirectional.draws_from_grid());
        assert!(!EnergyFlow::Bidirectional.feeds_grid());
        assert!(EnergyFlow::StorageCharge.is_storage());
        assert!(!EnergyFlow::Consumption.is_storage());
    }

    #[test]
    fn markt_rolle_mscons_receiver() {
        assert!(MarktRolle::Lf.is_mscons_receiver());
        assert!(MarktRolle::Bkv.is_mscons_receiver());
        // MaBiS: the NB sends the Summenzeitreihen to the ÜNB via MSCONS.
        assert!(MarktRolle::Uenb.is_mscons_receiver());
        assert!(!MarktRolle::Nb.is_mscons_receiver());
        assert!(!MarktRolle::Msb.is_mscons_receiver());
    }
}