energy-api 0.3.0

Rust client and server implementation for German energy market API-Webdienste (MaKo)
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
//! Wire-format types for the EDI-Energy electricity market APIs.
//!
//! Covers three API families:
//! - **Control Measures** (`controlMeasuresV1.yaml`) — Steuerungshandlungen
//!   between NB/LF and MSB.
//! - **MaLo Identification** (`maloIdentV1.yaml`) — MaLo-ID retrieval for the
//!   24 h supplier-switch process (GPKE part 2).
//! - **WiM Order** (`wimOrderV1.yaml`) — iMS Universalbestellprozess for smart
//!   meter commissioning (PIDs 11021–11023).

use serde::{Deserialize, Serialize};
use uuid::Uuid;

// ── Shared identifiers ────────────────────────────────────────────────────────

/// External transaction ID (UUID RFC 4122), chosen by the sender.
pub type TransactionId = Uuid;
/// Idempotency key for retries (UUID RFC 4122).
pub type InitialTransactionId = Uuid;
/// External reference correlating a response to a prior request (UUID RFC 4122).
pub type ReferenceId = Uuid;
/// 13-digit market partner identifier.
pub type MarketPartnerId = i64;

/// Network location identifier — pattern `E[A-Z0-9]{9}[0-9]`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct NeloId(pub String);

/// Controllable resource identifier — pattern `C[A-Z0-9]{9}[0-9]`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SrId(pub String);

/// Either a network location ID or a controllable resource ID.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(untagged)]
pub enum LocationId {
    NetworkLocation(NeloId),
    ControllableResource(SrId),
}

impl std::fmt::Display for NeloId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}
impl std::fmt::Display for SrId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}
impl std::fmt::Display for LocationId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LocationId::NetworkLocation(id) => id.fmt(f),
            LocationId::ControllableResource(id) => id.fmt(f),
        }
    }
}

// ── Control Measures ──────────────────────────────────────────────────────────

/// Maximum power value in kW (`"\d{0,6}(\.\d{1,3})?"`).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MaximumPowerValue(pub String);

/// Regulate a location to a specific maximum power value.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CommandControl {
    pub maximum_power_value: MaximumPowerValue,
    /// Start of effect period — ISO 8601 UTC, second precision (e.g. `"2023-08-01T12:30:00Z"`).
    pub execution_time_from: String,
    /// Optional end of effect period.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_time_until: Option<String>,
}

/// Reset a location to its initial / uncontrolled state.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CommandRegular {
    /// Start of effect period — ISO 8601 UTC, second precision.
    pub execution_time_from: String,
}

/// Reason for a negative response from the MSB.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ReasonNegative {
    /// Communication to the control box was disrupted.
    #[serde(rename = "communicationFailure")]
    CommunicationFailure,
    /// MSB back-end is overloaded.
    #[serde(rename = "overload")]
    Overload,
    /// MSB is procedurally unable to fulfil the request.
    #[serde(rename = "unable")]
    Unable,
}

/// Terminal state for negative (failure) responses.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StateNegative {
    #[serde(rename = "failed")]
    Failed,
}

/// Terminal state for positive (success) responses.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StatePositive {
    #[serde(rename = "succeeded")]
    Succeeded,
}

/// Preliminary state — command is executable in principle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PreliminaryStatePositive {
    #[serde(rename = "possible")]
    Possible,
}

/// State indicating the final outcome is not yet known.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StateUnknown {
    #[serde(rename = "unknown")]
    Unknown,
}

// ── MaLo Identification ───────────────────────────────────────────────────────

/// Market location identifier — 11-digit string.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MaloId(pub String);

/// Metering location identifier — pattern `DE\d{11}[A-Z,\d]{20}`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MeloId(pub String);

/// Technical resource identifier — pattern `D[A-Z0-9]{9}[0-9]`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TrId(pub String);

/// Energy flow direction at a market location.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EnergyDirection {
    #[serde(rename = "consumption")]
    Consumption,
    #[serde(rename = "production")]
    Production,
}

/// Metering technology classification of a market location.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MeasurementTechnologyClassification {
    #[serde(rename = "intelligentMeasuringSystem")]
    IntelligentMeasuringSystem,
    #[serde(rename = "conventionalMeasuringSystem")]
    ConventionalMeasuringSystem,
    #[serde(rename = "noMeasurement")]
    NoMeasurement,
}

/// Whether the forecast basis may be changed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum OptionalChangeForecastBasis {
    #[serde(rename = "possible")]
    Possible,
    #[serde(rename = "notPossible")]
    NotPossible,
}

/// Lifecycle property / category of a market location.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum MarketLocationProperty {
    #[serde(rename = "customerFacility")]
    CustomerFacility,
    /// Dormant market location (spec spelling: `"nonActice"`).
    #[serde(rename = "nonActice")]
    NonActive,
    #[serde(rename = "standard")]
    Standard,
}

/// Tranche proportion type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ProportionType {
    #[serde(rename = "bilateralAgreement")]
    BilateralAgreement,
    #[serde(rename = "percent")]
    Percent,
}

/// Input parameters for a MaLo identification request.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdentificationParameter {
    /// Effective date for identification — ISO 8601 UTC, day-boundary midnight.
    pub identification_date_time: String,
    pub energy_direction: EnergyDirection,
    /// Optional ID-based search criteria.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub identification_parameter_id: Option<IdentificationParameterId>,
    /// Address-based search criteria.
    pub identification_parameter_address: IdentificationParameterAddress,
}

/// Optional ID-based identification parameters.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdentificationParameterId {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub malo_id: Option<MaloId>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tranchen_ids: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub melo_ids: Option<Vec<MeloId>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub meter_numbers: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub customer_number: Option<String>,
}

/// Address-based identification parameters.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct IdentificationParameterAddress {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<PersonName>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub address: Option<PostalAddress>,
}

/// Person or company name.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PersonName {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub surnames: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub firstnames: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub company: Option<String>,
}

/// German postal address.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PostalAddress {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub country_code: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub zip_code: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub city: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub street: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub house_number: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub house_number_addition: Option<String>,
}

// ── MaLo Identification response types ───────────────────────────────────────

/// Positive identification result — all data the NB holds about the market
/// location from `identificationDateTime` onwards.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MaloIdentResultPositive {
    pub data_market_location: DataMarketLocation,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_tranches: Option<Vec<DataTranche>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_meter_locations: Option<Vec<DataMeterLocation>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_technical_resources: Option<Vec<DataTechnicalResource>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_controllable_resources: Option<Vec<DataControllableResource>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_network_locations: Option<Vec<DataNetworkLocation>>,
}

/// Negative identification result, referencing the applicable decision tree.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MaloIdentResultNegative {
    /// Decision tree code from EDI@energy, e.g. `"E_0594"`.
    pub decision_tree: String,
    /// Response code from that tree, e.g. `"A10"`.
    pub response_code: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// NB that now holds the location (when it left this NB's grid area).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub network_operator: Option<MarketPartnerId>,
}

/// Full data about the identified market location.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DataMarketLocation {
    pub malo_id: MaloId,
    pub energy_direction: EnergyDirection,
    pub measurement_technology_classification: MeasurementTechnologyClassification,
    pub optional_change_forecast_basis: OptionalChangeForecastBasis,
    pub data_market_location_properties: Vec<MarketLocationProperties>,
    pub data_market_location_network_operators: Vec<TimeSlicedMarketPartner>,
    pub data_market_location_transmission_system_operators: Vec<TimeSlicedMarketPartner>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_market_location_measuring_point_operators: Option<Vec<TimeSlicedMarketPartner>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_market_location_suppliers: Option<Vec<TimeSlicedMarketPartner>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_market_location_name: Option<PersonName>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_market_location_address: Option<PostalAddress>,
}

/// A market partner assignment valid for a specific time slice.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TimeSlicedMarketPartner {
    pub market_partner_id: MarketPartnerId,
    pub execution_time_from: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_time_until: Option<String>,
}

/// Property of a market location valid for a specific time slice.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MarketLocationProperties {
    pub market_location_property: MarketLocationProperty,
    pub execution_time_from: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_time_until: Option<String>,
}

/// Data about a metering location (Messlokation) at the market location.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DataMeterLocation {
    pub melo_id: MeloId,
    pub meter_number: String,
    pub data_meter_location_measuring_point_operators: Vec<TimeSlicedMarketPartner>,
}

/// Data about a technical resource (Technische Ressource) at the market location.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DataTechnicalResource {
    pub tr_id: TrId,
}

/// Data about a controllable resource (Steuerbare Ressource) at the market location.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DataControllableResource {
    pub sr_id: SrId,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data_controllable_resource_measuring_point_operators: Option<Vec<SrMarketPartner>>,
}

/// Market partner assignment at a controllable resource.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SrMarketPartner {
    pub market_partner_id: MarketPartnerId,
    pub execution_time_from: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_time_until: Option<String>,
    pub market_partner_type_sr: String,
}

/// Data about a network location (Netzlokation) linked to the market location.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DataNetworkLocation {
    pub nelo_id: NeloId,
    pub data_network_location_measuring_point_operators: Vec<TimeSlicedMarketPartner>,
}

/// A billing tranche at a market location.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DataTranche {
    pub tranchen_id: String,
    pub proportion: ProportionType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub percent: Option<f64>,
    pub data_tranche_suppliers: Vec<TimeSlicedMarketPartner>,
}

// ── WiM Order (iMS Universalbestellprozess) ───────────────────────────────────

/// Device category for the iMS Universalbestellprozess.
///
/// Specifies which type of smart meter the Netzbetreiber is ordering from the MSB.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WimDeviceCategory {
    /// Intelligentes Messsystem (iMSys) — full smart meter system.
    #[serde(rename = "iMSys")]
    IMSys,
    /// Moderne Messeinrichtung (mME) — basic smart meter display.
    #[serde(rename = "mME")]
    Mme,
    /// Moderne Messeinrichtung mit Kommunikationsadapter (mME+KME).
    #[serde(rename = "mME+KME")]
    MmeKme,
}

/// Rejection reason code for a WiM Ablehnung response.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WimRejectionReason {
    /// MeLo does not exist in the MSB's service territory.
    #[serde(rename = "meloUnknown")]
    MeloUnknown,
    /// MSB is not responsible for this MeLo.
    #[serde(rename = "notResponsible")]
    NotResponsible,
    /// Requested device category is not installable at this MeLo.
    #[serde(rename = "deviceCategoryNotSupported")]
    DeviceCategoryNotSupported,
    /// Regulatory prerequisites for iMSys rollout not yet met.
    #[serde(rename = "rolloutPreconditionNotMet")]
    RolloutPreconditionNotMet,
    /// MSB technical capacity exhausted.
    #[serde(rename = "capacityExhausted")]
    CapacityExhausted,
    /// Other / unspecified reason; see `reason_text` for details.
    #[serde(rename = "other")]
    Other,
}

/// Payload for a WiM Anmeldung (PID 11021) — NB orders iMS installation from MSB.
///
/// Sent by the Netzbetreiber to the Messstellenbetreiber over the REST channel.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WimAnmeldungRequest {
    /// Messlokation EIC code at which the device should be installed.
    pub melo_id: String,
    /// 13-digit GLN of the Netzbetreiber (sender).
    pub netzbetreiber_id: i64,
    /// Requested process date (ISO 8601, date only, e.g. `"2026-06-01"`).
    pub process_date: String,
    /// Requested device category.
    pub device_category: WimDeviceCategory,
    /// Optional free-text notes (e.g. access instructions).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub notes: Option<String>,
}

/// Payload for a WiM Bestätigung (PID 11022) — MSB confirms the order.
///
/// Sent by the MSB to the Netzbetreiber after accepting an Anmeldung.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WimBestaetigung {
    /// UUID of the original Anmeldung transaction this response refers to.
    pub reference_id: Uuid,
    /// Confirmed installation date (ISO 8601, date only).
    pub confirmed_process_date: String,
    /// Assigned device identifier (EIC or MSB-internal reference).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub device_id: Option<String>,
}

/// Payload for a WiM Ablehnung (PID 11023) — MSB rejects the order.
///
/// Sent by the MSB to the Netzbetreiber after refusing an Anmeldung.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct WimAblehnung {
    /// UUID of the original Anmeldung transaction this response refers to.
    pub reference_id: Uuid,
    /// Structured rejection reason code.
    pub reason: WimRejectionReason,
    /// Optional human-readable explanation (supplementary to `reason`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason_text: Option<String>,
}