iec61850-kit 0.8.0

IEC 61850 in Rust: GOOSE and Sampled Values on capture files and live interfaces, an MMS client and server over the full OSI stack, and SCL loading and editing. Panic-free, sans-IO, no_std-capable.
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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
//! The served IED: the model, the namespace it maps to, and the values behind it.
//!
//! Everything a client can name lives here. The SCL file gives the shape ([`super::tree`]),
//! this gives the shape *values*, and [`super::acsi`] answers requests out of both. There is
//! no registry and no build step: [`Ied::from_scl`] is the whole configuration.
//!
//! Values are keyed by their **full MMS reference** — `IED1LD0/LLN0$ST$Mod$stVal` — because
//! that is what a data-set member resolves to, what a report's `DataRef` prints, and what a
//! client writes to. One key shape for all of them is what keeps a report and a read from
//! disagreeing about which attribute changed.

use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;

use super::tree::{self, Domain, VarKind, Variable};
use crate::common::{Edition, EntryTime, Error, Fc, OptFlds, Quality, Result, TrgOps, UtcTime};
use crate::model::{BType, IedModel, LogicalNode, ReportControl};
use crate::proto::data::Value;

/// What a control block is, so that a write to one can be recognised without re-parsing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BlockKind {
    /// An unbuffered report control block (`RP`).
    Unbuffered,
    /// A buffered report control block (`BR`).
    Buffered,
    /// A log control block (`LG`).
    Log,
    /// The setting group control block (`SP$SGCB`).
    SettingGroup,
    /// A GOOSE control block (`GO`).
    Goose,
    /// A sampled-value control block (`MS`).
    SampledValue,
}

/// One control block of the served model, and where it sits.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Block {
    /// The full MMS reference of the block: `IED1LD0/LLN0$RP$urcb01`.
    pub reference: String,
    /// The logical device it is in.
    pub domain: String,
    /// The logical node it is in.
    pub node: String,
    /// Its own name, with the index for an indexed report control block.
    pub name: String,
    /// What kind it is.
    pub kind: BlockKind,
    /// The data set it reports, in MMS form, when it has one.
    pub data_set: Option<String>,
}

/// One member of a data set: the reference the file names, and the leaves it covers.
///
/// A member is an **FCD** (a data object under a functional constraint, `CSWI1$ST$Pos`) or an
/// **FCDA** (one attribute, `CSWI1$ST$Pos$stVal`). The distinction matters for exactly one
/// reason: a member is the unit a report is granular in — one inclusion bit, one value and
/// one `ReasonCode` — so an FCD is reported *whole*, as the structure it is, and never as its
/// attributes one by one (IEC 61850-8-1 §17.2.2, TISSUE 361 🌐).
///
/// The leaves are still needed, because a *trigger* is a property of an attribute: a member is
/// included when any leaf under it changed in a way the block's `TrgOps` asked for.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DataSetMember {
    /// The member as the file names it: `IED1LD0/CSWI1$ST$Pos`.
    pub reference: String,
    /// Every leaf it covers, in namespace order. An FCDA covers itself.
    pub leaves: Vec<String>,
}

/// A data set as the server holds it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ServedDataSet {
    /// `IED1LD0/LLN0$dsTrip`.
    pub reference: String,
    /// The members as the file names them, in order. This is what `GetNamedVariableListAttributes`
    /// answers, what a `Read` of the list returns one value each for, and what a report's
    /// inclusion bit string indexes into — all three, deliberately, from one list.
    pub members: Vec<DataSetMember>,
    /// True when a client created it and may delete it again.
    pub deletable: bool,
}

impl ServedDataSet {
    /// The member references, in order.
    pub fn references(&self) -> Vec<String> {
        self.members.iter().map(|m| m.reference.clone()).collect()
    }

    /// How many members it has — the length of a report's inclusion bit string.
    pub fn len(&self) -> usize {
        self.members.len()
    }

    /// Whether it has no members.
    pub fn is_empty(&self) -> bool {
        self.members.is_empty()
    }
}

/// The IED a server serves.
#[derive(Debug)]
pub struct Ied {
    /// The model it was built from.
    pub model: IedModel,
    /// The MMS domains, one per logical device, in model order.
    pub domains: Vec<Domain>,
    /// Leaf values, keyed by full MMS reference.
    values: BTreeMap<String, Value>,
    /// Data sets, keyed by reference.
    data_sets: BTreeMap<String, ServedDataSet>,
    /// Control blocks, in namespace order.
    blocks: Vec<Block>,
    /// References written since the last commit, and what triggered each.
    dirty: BTreeMap<String, TrgOps>,
    /// The edition this IED serves — taken from the SCL file, because that is where an
    /// IED's edition is declared. It decides the report control block's attribute set:
    /// `ResvTms` and `Owner` arrived with Edition 2, and a server that publishes them to an
    /// Edition 1 client is claiming a service it does not have.
    edition: Edition,
}

impl Ied {
    /// Load an IED from an SCL document.
    ///
    /// `ied` names the IED in an SCD; a single-IED ICD may pass `None`.
    #[cfg(feature = "scl")]
    pub fn from_scl(xml: &str, ied: Option<&str>) -> Result<Ied> {
        Ied::new(IedModel::from_scl(xml, ied)?)
    }

    /// Load an IED from an SCL file on disk — the twenty-line server's first line.
    #[cfg(all(feature = "scl", feature = "std"))]
    pub fn from_scl_file(path: impl AsRef<std::path::Path>, ied: Option<&str>) -> Result<Ied> {
        Ied::new(IedModel::from_scl_file(path, ied)?)
    }

    /// Build the served IED from a model that is already loaded.
    ///
    /// The edition comes from the file's own schema version ([`IedModel::edition`]);
    /// [`Ied::with_edition`] overrides it for a device whose file says one thing and whose
    /// certificate says another.
    pub fn new(model: IedModel) -> Result<Ied> {
        let edition = model.edition();
        Ied::with_edition(model, edition)
    }

    /// Build the served IED at an explicit edition.
    pub fn with_edition(model: IedModel, edition: Edition) -> Result<Ied> {
        let mut blocks = Vec::new();
        let mut domains = Vec::with_capacity(model.logical_devices.len());
        for ld in &model.logical_devices {
            let ld_name = ld.name.clone();
            let mut found: Vec<Block> = Vec::new();
            let domain = tree::domain_of(ld, &mut |ln| control_blocks(&ld_name, ln, edition, &mut found));
            blocks.extend(found);
            domains.push(domain);
        }

        let mut ied = Ied { model, domains, values: BTreeMap::new(), data_sets: BTreeMap::new(), blocks, dirty: BTreeMap::new(), edition };
        ied.seed_values();
        ied.seed_data_sets();
        ied.seed_blocks();
        Ok(ied)
    }

    /// The edition this IED serves.
    pub const fn edition(&self) -> Edition {
        self.edition
    }

    /// The MMS domain names, which are the logical device names.
    pub fn domain_names(&self) -> Vec<String> {
        self.domains.iter().map(|d| d.name.clone()).collect()
    }

    /// The domain named `name`.
    pub fn domain(&self, name: &str) -> Option<&Domain> {
        self.domains.iter().find(|d| d.name == name)
    }

    /// The control blocks the model defines.
    pub fn blocks(&self) -> &[Block] {
        &self.blocks
    }

    /// The control block at `reference`.
    pub fn block(&self, reference: &str) -> Option<&Block> {
        self.blocks.iter().find(|b| b.reference == reference)
    }

    /// Data-set references in a logical device, sorted.
    pub fn data_set_names(&self, domain: &str) -> Vec<String> {
        let prefix = alloc::format!("{domain}/");
        let mut out: Vec<String> = self.data_sets.keys().filter_map(|k| k.strip_prefix(&prefix).map(String::from)).collect();
        out.sort();
        out
    }

    /// The log names of a logical device, sorted — the MMS journals of that domain.
    ///
    /// A `Log` with no name is the logical device's default log, which IEC 61850-8-1 names
    /// `LLN0$General`; a named one is `LLN0$<name>`.
    pub fn log_names(&self, domain: &str) -> Vec<String> {
        let mut out = Vec::new();
        if let Some(ld) = self.model.logical_devices.iter().find(|ld| ld.name == domain) {
            for ln in &ld.logical_nodes {
                for log in &ln.logs {
                    let name = if log.name.is_empty() { "General" } else { log.name.as_str() };
                    out.push(alloc::format!("{}${name}", ln.name));
                }
            }
        }
        out.sort();
        out
    }

    /// How many data sets a client has created.
    pub fn created_data_sets(&self) -> usize {
        self.data_sets.values().filter(|d| d.deletable).count()
    }

    /// The data set at `reference` (`IED1LD0/LLN0$dsTrip`).
    pub fn data_set(&self, reference: &str) -> Option<&ServedDataSet> {
        self.data_sets.get(reference)
    }

    /// Create a data set. Fails if one of that name already exists.
    pub fn create_data_set(&mut self, reference: &str, members: Vec<String>) -> Result<()> {
        if self.data_sets.contains_key(reference) {
            return Err(Error::InvalidValue("a data set of that name already exists"));
        }
        let members = members.into_iter().map(|m| DataSetMember { leaves: self.leaves_of(&m), reference: m }).collect();
        self.data_sets.insert(String::from(reference), ServedDataSet { reference: String::from(reference), members, deletable: true });
        Ok(())
    }

    /// Delete a data set. Returns whether it existed and whether it was deletable.
    pub fn delete_data_set(&mut self, reference: &str) -> (bool, bool) {
        match self.data_sets.get(reference) {
            None => (false, false),
            Some(ds) if !ds.deletable => (true, false),
            Some(_) => {
                self.data_sets.remove(reference);
                (true, true)
            }
        }
    }

    /// The value at a full MMS reference, if it is a leaf that has one.
    pub fn value(&self, reference: &str) -> Option<&Value> {
        self.values.get(reference)
    }

    /// Read a full MMS reference (`IED1LD0/CSWI1$ST$Pos`) as a value.
    ///
    /// The same walk as [`Ied::read`], for the callers that hold one string rather than two —
    /// a data-set member, a report's included member, a log entry.
    pub fn read_reference(&self, reference: &str) -> Option<Value> {
        let (domain, item) = reference.split_once('/')?;
        self.read(domain, item)
    }

    /// Read a reference as a value: a leaf directly, a structure assembled from its
    /// components in **model order**, which is the order every positional client reads them.
    pub fn read(&self, domain: &str, item: &str) -> Option<Value> {
        let node = self.domain(domain)?.resolve(item)?;
        self.read_node(domain, item, node)
    }

    fn read_node(&self, domain: &str, item: &str, node: &Variable) -> Option<Value> {
        match &node.kind {
            VarKind::Leaf(_) => self.values.get(&reference(domain, item)).cloned(),
            VarKind::Structure => {
                let mut members = Vec::with_capacity(node.children.len());
                for child in &node.children {
                    let path = alloc::format!("{item}{}{}", tree::SEP, child.name);
                    members.push(self.read_node(domain, &path, child)?);
                }
                Some(Value::Structure(members))
            }
            VarKind::Array(n) => {
                let element = node.element()?;
                let mut members = Vec::with_capacity(*n as usize);
                for i in 0..*n {
                    members.push(self.read_node(domain, &alloc::format!("{item}({i})"), element)?);
                }
                Some(Value::Array(members))
            }
        }
    }

    /// Write a value at a full MMS reference without any ACSI behaviour.
    ///
    /// The value must match the leaf's basic type: a server that accepts an integer where a
    /// boolean was engineered has silently changed its own model, and every client that reads
    /// it back gets a type it did not ask for. Returns the `DataAccessError` code on refusal.
    pub fn write_leaf(&mut self, reference: &str, value: Value) -> core::result::Result<(), i64> {
        let Some(node) = self.node_at(reference) else { return Err(DATA_ACCESS_NON_EXISTENT) };
        let VarKind::Leaf(btype) = node.kind.clone() else { return Err(DATA_ACCESS_TYPE_INCONSISTENT) };
        if !accepts(&btype, &value) {
            return Err(DATA_ACCESS_TYPE_INCONSISTENT);
        }
        let changed = self.values.get(reference) != Some(&value);
        let quality = matches!(btype, BType::Quality);
        self.values.insert(String::from(reference), value);
        if changed {
            // A quality that changed is a *quality* change, not a data change: `TrgOps` has
            // separate bits and a client that asked for one and not the other must get what
            // it asked for.
            let trigger = if quality { TrgOps::NONE.with_quality_change(true) } else { TrgOps::NONE.with_data_change(true) };
            let entry = self.dirty.entry(String::from(reference)).or_insert(TrgOps::NONE);
            *entry = TrgOps::from_bit_string(&or_bits(*entry, trigger));
        } else {
            // Written without changing: `dupd`, which is the trigger a client asks for when
            // it wants every update rather than every change.
            let entry = self.dirty.entry(String::from(reference)).or_insert(TrgOps::NONE);
            *entry = TrgOps::from_bit_string(&or_bits(*entry, TrgOps::NONE.with_data_update(true)));
        }
        Ok(())
    }

    /// Write a value without marking it dirty — a write the *server itself* makes.
    ///
    /// A report control block's `SqNum`, `EntryID` and `TimeOfEntry`, a log control block's
    /// `OldEnt`/`NewEnt`, an `SGCB`'s `LActTm` and the `GI`/`PurgeBuf` flags a request
    /// consumes are all bookkeeping the server writes *while publishing*. They are not
    /// application data and no data set contains them, so they must not enter the dirty set.
    /// Publishing through the ordinary write and clearing the set with [`Ied::take_dirty`]
    /// afterwards would also discard any application write that had landed in the meantime —
    /// losing it from the report *and* the log whenever another association's thread committed
    /// at the wrong moment.
    pub fn set_internal(&mut self, reference: &str, value: Value) -> core::result::Result<(), i64> {
        let Some(node) = self.node_at(reference) else { return Err(DATA_ACCESS_NON_EXISTENT) };
        let VarKind::Leaf(btype) = node.kind.clone() else { return Err(DATA_ACCESS_TYPE_INCONSISTENT) };
        if !accepts(&btype, &value) {
            return Err(DATA_ACCESS_TYPE_INCONSISTENT);
        }
        self.values.insert(String::from(reference), value);
        Ok(())
    }

    /// An SCL `Val` text as the value of the attribute at `reference`.
    ///
    /// The type comes from the model and, for an enumeration, so does the symbol table — the
    /// same path a type template's own `Val` takes, so a per-group setting and an ungrouped
    /// one cannot be decoded differently.
    pub fn parse_text(&self, reference: &str, text: &str) -> Option<Value> {
        let node = self.node_at(reference)?;
        let VarKind::Leaf(btype) = &node.kind else { return None };
        // The enumeration table is looked up by the attribute's `type`, which the tree does
        // not carry; the model does, and this is the one place that needs it.
        let type_id = self.attribute_type_id(reference);
        parse_engineered_typed(&self.model, btype, type_id.as_deref(), text)
    }

    /// The `type` attribute of the data attribute at `reference`, for an enumeration.
    ///
    /// The tree carries the basic type but not the `type` id, because only an enumeration
    /// needs it; the model has both, and resolving through it is one lookup rather than a
    /// second walk that could disagree with the first.
    fn attribute_type_id(&self, reference: &str) -> Option<String> {
        let parsed = crate::common::ObjectReference::parse(reference).ok()?;
        self.model.attribute(&parsed)?.type_id.clone()
    }

    /// The ordinal an enumeration name has at `reference`, according to **the file**.
    ///
    /// An `Enum` attribute names an SCL `EnumType`, and that type says which number each name
    /// is. Service tracking needs exactly this: IEC 61850-7-2 gives the `serviceType` and
    /// `errorCode` names ✅ and IEC 61850-8-1 gives the numbers, behind the paywall, so
    /// asking the file is the only way to answer without inventing one — and a file that has
    /// answered must win, or the server and its own engineering document disagree.
    pub fn enum_ordinal(&self, reference: &str, name: &str) -> Option<i64> {
        let type_id = self.attribute_type_id(reference)?;
        self.model.enum_type(&type_id)?.ord(name)
    }

    /// Whether a **client** may write `reference`, and the `DataAccessError` when it may not.
    ///
    /// Two rules, because there are two kinds of name. Inside a control block the answer is a
    /// per-attribute table — `RptEna` is a client's to set and `SqNum` is the server's to
    /// count — and everywhere else it is the functional constraint
    /// ([`Fc::is_client_writable`]). Neither applies to the **application** behind the
    /// server: it writes process data through [`Ied::write_leaf`], which is what a
    /// [`Txn`](crate::server::Txn) does, and is the only path that may touch `ST` and `MX`.
    pub fn client_write_allowed(&self, reference: &str) -> core::result::Result<(), i64> {
        if let Some((block, attribute)) = reference.rsplit_once(tree::SEP)
            && let Some(b) = self.block(block)
        {
            return if writable_block_attribute(b.kind, attribute) { Ok(()) } else { Err(DATA_ACCESS_DENIED) };
        }
        match self.node_at(reference) {
            Some(node) => match node.fc {
                Some(fc) if fc.is_client_writable() => Ok(()),
                // A node with no functional constraint is a logical node, which is not a
                // value at all.
                _ => Err(DATA_ACCESS_DENIED),
            },
            None => Err(DATA_ACCESS_NON_EXISTENT),
        }
    }

    /// The tree node a full MMS reference denotes.
    pub fn node_at(&self, reference: &str) -> Option<&Variable> {
        let (domain, item) = reference.split_once('/')?;
        self.domain(domain)?.resolve(item)
    }

    /// What has been written since the last [`Ied::take_dirty`], and what each write triggers.
    pub fn take_dirty(&mut self) -> BTreeMap<String, TrgOps> {
        core::mem::take(&mut self.dirty)
    }

    /// Whether anything is waiting to be committed.
    pub fn is_dirty(&self) -> bool {
        !self.dirty.is_empty()
    }

    /// Every leaf reference a data-set member covers, in namespace order.
    ///
    /// A member that names a data object (`IED1LD0/PTRC1$ST$Tr`) covers every attribute under
    /// it, which is ordinary engineering. The leaves are what a *trigger* is evaluated
    /// against; the member is what is reported ([`DataSetMember`]).
    pub fn leaves_of(&self, reference: &str) -> Vec<String> {
        let Some((domain, item)) = reference.split_once('/') else { return Vec::new() };
        let Some(node) = self.domain(domain).and_then(|d| d.resolve(item)) else { return Vec::new() };
        let mut out = Vec::new();
        collect_leaves(domain, item, node, &mut out);
        out
    }

    // ---- construction --------------------------------------------------------------

    /// Every leaf of every domain gets a value, from the file's `Val` when it has one and
    /// from the type otherwise. A model attribute with no value is still a variable a client
    /// may read, and answering `object-non-existent` for it would be a lie about the model.
    fn seed_values(&mut self) {
        let mut seeded: Vec<(String, Value)> = Vec::new();
        for domain in &self.domains {
            for node in &domain.nodes {
                seed_node(&domain.name, &node.name, node, &mut seeded);
            }
        }
        for (reference, value) in seeded {
            self.values.insert(reference, value);
        }
        // The engineered values from the SCL type templates and instances override the
        // type defaults, which is what makes a `ctlModel` of `sbo-with-enhanced-security`
        // in the file the server's actual behaviour.
        let overrides = self.engineered_values();
        for (reference, value) in overrides {
            self.values.insert(reference, value);
        }
    }

    fn engineered_values(&self) -> Vec<(String, Value)> {
        let mut out = Vec::new();
        for ld in &self.model.logical_devices {
            for ln in &ld.logical_nodes {
                for object in &ln.data_objects {
                    engineered_of(&self.model, &ld.name, &ln.name, &object.name, object, &mut out);
                }
            }
        }
        out
    }

    fn seed_data_sets(&mut self) {
        let mut sets = Vec::new();
        for ld in &self.model.logical_devices {
            for ln in &ld.logical_nodes {
                for ds in &ln.data_sets {
                    sets.push((alloc::format!("{}/{}${}", ld.name, ln.name, ds.name), ld.name.clone(), ds.clone()));
                }
            }
        }
        for (reference, ld_name, ds) in sets {
            let members: Vec<DataSetMember> = ds
                .members
                .iter()
                .map(|m| {
                    let reference = self.model.fcda_reference(&ld_name, m);
                    DataSetMember { leaves: self.leaves_of(&reference), reference }
                })
                .collect();
            self.data_sets.insert(reference.clone(), ServedDataSet { reference, members, deletable: false });
        }
    }

    /// Put the engineered defaults into every control block's attributes.
    fn seed_blocks(&mut self) {
        let edition = self.edition;
        let mut writes: Vec<(String, Value)> = Vec::new();
        for ld in &self.model.logical_devices {
            for ln in &ld.logical_nodes {
                for rcb in &ln.report_controls {
                    let data_set = rcb.dat_set.as_ref().map(|d| alloc::format!("{}/{}${d}", ld.name, ln.name));
                    for name in rcb.instance_names() {
                        let base = alloc::format!("{}/{}${}${name}", ld.name, ln.name, rcb.fc().as_str());
                        for (attribute, value) in rcb_defaults(rcb, &base, data_set.as_deref(), edition) {
                            writes.push((alloc::format!("{base}${attribute}"), value));
                        }
                    }
                }
                for lcb in &ln.log_controls {
                    let base = alloc::format!("{}/{}$LG${}", ld.name, ln.name, lcb.name);
                    let log = alloc::format!("{}/{}${}", lcb.log_ld_inst.as_deref().unwrap_or(&ld.name), ln.name, lcb.log_name);
                    for (attribute, value) in lcb_defaults(lcb, &log, ld, ln) {
                        writes.push((alloc::format!("{base}${attribute}"), value));
                    }
                }
                if let Some(sg) = ln.setting_control {
                    let base = alloc::format!("{}/{}$SP$SGCB", ld.name, ln.name);
                    for (attribute, value) in sgcb_defaults(sg) {
                        writes.push((alloc::format!("{base}${attribute}"), value));
                    }
                }
                // The publisher control blocks are engineered in the file too, and a client
                // that reads one should see what the file says rather than a block of zeros.
                for gcb in &ln.gse_controls {
                    let base = alloc::format!("{}/{}$GO${}", ld.name, ln.name, gcb.name);
                    for (attribute, value) in gocb_defaults(gcb, &base, &ld.name, &ln.name) {
                        writes.push((alloc::format!("{base}${attribute}"), value));
                    }
                }
                for scb in &ln.smv_controls {
                    let base = alloc::format!("{}/{}${}${}", ld.name, ln.name, svcb_fc(scb.multicast).as_str(), scb.name);
                    for (attribute, value) in svcb_defaults(scb, &ld.name, &ln.name) {
                        writes.push((alloc::format!("{base}${attribute}"), value));
                    }
                }
            }
        }
        for (reference, value) in writes {
            self.values.insert(reference, value);
        }
        self.dirty.clear();
    }
}

/// Whether a client may write `attribute` of a control block of this kind.
///
/// The tables are IEC 61850-7-2's: what a client *configures* against what the server
/// *counts*. `SqNum`, `ConfRev`, `TimeOfEntry`, `BufOvfl` and `Owner` are the server's own
/// bookkeeping, and a client that could write them could make a report claim a sequence
/// number it never sent. `EntryID` is the exception that proves the rule — it is writable,
/// because writing it is how a client says where to resume (§17.2).
pub fn writable_block_attribute(kind: BlockKind, attribute: &str) -> bool {
    match kind {
        // IEC 61850-7-2 Tables 25 (URCB) and 27 (BRCB).
        BlockKind::Unbuffered | BlockKind::Buffered => {
            matches!(attribute, "RptID" | "RptEna" | "Resv" | "ResvTms" | "DatSet" | "OptFlds" | "BufTm" | "TrgOps" | "IntgPd" | "GI" | "PurgeBuf" | "EntryID")
        }
        // Table 29 (LCB): the four `Old*`/`New*` attributes and `LogRef` are the log's state.
        BlockKind::Log => matches!(attribute, "LogEna" | "DatSet" | "TrgOps" | "IntgPd"),
        // §11: `NumOfSG` is the device's and `LActTm` records the last activation.
        BlockKind::SettingGroup => matches!(attribute, "ActSG" | "EditSG" | "CnfEdit" | "ResvTms"),
        // §18/§19: only the enable flag. Everything else describes a stream that is
        // engineered in the SCL file, and changing it at runtime would make the file a lie.
        BlockKind::Goose => attribute == "GoEna",
        BlockKind::SampledValue => attribute == "SvEna",
    }
}

/// `object-non-existent`.
pub const DATA_ACCESS_NON_EXISTENT: i64 = 10;
/// `type-inconsistent`.
pub const DATA_ACCESS_TYPE_INCONSISTENT: i64 = 7;
/// `object-access-denied`.
pub const DATA_ACCESS_DENIED: i64 = 3;
/// `object-value-invalid`.
pub const DATA_ACCESS_VALUE_INVALID: i64 = 11;
/// `object-access-unsupported` — the object exists and the *way* it was asked for does not.
///
/// What a selection this server cannot serve gets: an `alternateAccess` naming a range of
/// array elements or all of them names several values where one `AccessResult` holds one.
/// Answering with the whole array instead would be a different answer to a different
/// question, with nothing on the wire to say the question had changed.
pub const DATA_ACCESS_UNSUPPORTED: i64 = 9;

fn or_bits(a: TrgOps, b: TrgOps) -> Vec<u8> {
    let (_, mut left) = a.to_bit_string();
    let (_, right) = b.to_bit_string();
    for (l, r) in left.iter_mut().zip(&right) {
        *l |= *r;
    }
    left
}

/// The full MMS reference of an item in a domain.
fn reference(domain: &str, item: &str) -> String {
    alloc::format!("{domain}/{item}")
}

fn collect_leaves(domain: &str, item: &str, node: &Variable, out: &mut Vec<String>) {
    match node.kind {
        VarKind::Leaf(_) => out.push(reference(domain, item)),
        VarKind::Structure => {
            for child in &node.children {
                collect_leaves(domain, &alloc::format!("{item}{}{}", tree::SEP, child.name), child, out);
            }
        }
        // Every element of an array is its own set of leaves, under the index the reference
        // syntax spells: one store, addressed the way a client writes it.
        VarKind::Array(n) => {
            if let Some(element) = node.element() {
                for i in 0..n {
                    collect_leaves(domain, &alloc::format!("{item}({i})"), element, out);
                }
            }
        }
    }
}

fn seed_node(domain: &str, item: &str, node: &Variable, out: &mut Vec<(String, Value)>) {
    match &node.kind {
        VarKind::Leaf(b) => out.push((reference(domain, item), default_value(b))),
        VarKind::Structure => {
            for child in &node.children {
                seed_node(domain, &alloc::format!("{item}{}{}", tree::SEP, child.name), child, out);
            }
        }
        VarKind::Array(n) => {
            if let Some(element) = node.element() {
                for i in 0..*n {
                    seed_node(domain, &alloc::format!("{item}({i})"), element, out);
                }
            }
        }
    }
}

/// The engineered values of one data object, as `(reference, value)` pairs.
///
/// `do_path` is the data object's path below the logical node, `$`-joined: `Pos` for a data
/// object and `Pos$SBO` for a sub data object. Passing only the logical node here is how a
/// nested object's values end up written to the parent's names.
fn engineered_of(model: &IedModel, ld: &str, ln: &str, do_path: &str, object: &crate::model::DataObject, out: &mut Vec<(String, Value)>) {
    fn walk(model: &IedModel, prefix: &str, a: &crate::model::DataAttribute, out: &mut Vec<(String, Value)>) {
        let path = alloc::format!("{prefix}${}", a.name);
        if let Some(text) = &a.value
            && let Some(v) = parse_engineered(model, a, text)
        {
            out.push((path.clone(), v));
        }
        for c in &a.children {
            walk(model, &path, c, out);
        }
    }
    for a in &object.attributes {
        walk(model, &alloc::format!("{ld}/{ln}${}${do_path}", a.fc.as_str()), a, out);
    }
    for s in &object.sub_objects {
        engineered_of(model, ld, ln, &alloc::format!("{do_path}${}", s.name), s, out);
    }
}

/// An SCL `Val` as the value of its basic type.
///
/// An enumeration's `Val` is its **symbol** — `direct-with-normal-security`, `on`,
/// `remote-control` — and the wire carries the ordinal. The document's own `EnumType` tables
/// are what turn one into the other, which is why the model loads them: a server that parses
/// the symbol as a number answers `ctlModel = 0` (status-only) for every controllable object
/// in the file, and every control a client then issues is refused for a reason that is not
/// the real one.
fn parse_engineered(model: &IedModel, a: &crate::model::DataAttribute, text: &str) -> Option<Value> {
    parse_engineered_typed(model, &a.btype, a.type_id.as_deref(), text)
}

/// The same, given the type directly.
pub(super) fn parse_engineered_typed(model: &IedModel, btype: &BType, type_id: Option<&str>, text: &str) -> Option<Value> {
    Some(match btype {
        BType::Enum => Value::Integer(model.enum_ord(type_id, text)?),
        BType::Boolean => Value::Boolean(matches!(text, "true" | "1")),
        BType::Int8 | BType::Int16 | BType::Int24 | BType::Int32 | BType::Int64 => Value::Integer(text.parse().ok()?),
        BType::Int8U | BType::Int16U | BType::Int24U | BType::Int32U => Value::Unsigned(text.parse().ok()?),
        BType::Float32 => Value::Float32(text.parse().ok()?),
        BType::Float64 => Value::Float64(text.parse().ok()?),
        BType::VisString32 | BType::VisString64 | BType::VisString65 | BType::VisString129 | BType::VisString255 | BType::ObjRef | BType::Currency => {
            Value::VisibleString(String::from(text))
        }
        BType::Unicode255 => Value::MmsString(String::from(text)),
        _ => return None,
    })
}

/// What a leaf holds before anything has written to it.
pub fn default_value(btype: &BType) -> Value {
    match btype {
        BType::Boolean => Value::Boolean(false),
        BType::Int8 | BType::Int16 | BType::Int24 | BType::Int32 | BType::Int64 | BType::Enum => Value::Integer(0),
        BType::Int8U | BType::Int16U | BType::Int24U | BType::Int32U => Value::Unsigned(0),
        BType::Float32 => Value::Float32(0.0),
        BType::Float64 => Value::Float64(0.0),
        // A quality nobody has set is `Good`, which is the only honest default: a server that
        // starts every attribute `invalid` reports a fault it does not have.
        BType::Quality => Value::quality(Quality::GOOD),
        // Two bits, whether it is a position, a tap command or a check.
        BType::Dbpos | BType::Tcmd | BType::Check => Value::BitString { unused: 6, bytes: alloc::vec![0] },
        BType::TrgOps => TrgOps::NONE.to_value(),
        BType::OptFlds => OptFlds::NONE.to_value(),
        BType::SvOptFlds | BType::LogOptFlds => Value::BitString { unused: 0, bytes: alloc::vec![0] },
        BType::Timestamp => Value::UtcTime(UtcTime::default()),
        BType::EntryTime => Value::BinaryTime(EntryTime::default().to_octets().to_vec()),
        BType::Octet64 | BType::EntryID | BType::PhyComAddr => Value::OctetString(Vec::new()),
        // Exactly six and exactly sixteen octets, so the default is the field's own width
        // rather than an empty string a peer would read as a missing address.
        BType::Octet6 => Value::OctetString(alloc::vec![0; 6]),
        BType::Octet16 => Value::OctetString(alloc::vec![0; 16]),
        BType::Unicode255 => Value::MmsString(String::new()),
        BType::Struct | BType::Other(_) => Value::Structure(Vec::new()),
        _ => Value::VisibleString(String::new()),
    }
}

/// Whether a value may be written to a leaf of this basic type.
///
/// Deliberately by *shape*, not by width: a client that writes `Unsigned(3)` where the model
/// says `INT8U` is right, and one that writes a string there is not. Range checking is the
/// application's business — the type is the server's.
pub fn accepts(btype: &BType, value: &Value) -> bool {
    match btype {
        BType::Boolean => matches!(value, Value::Boolean(_)),
        BType::Int8 | BType::Int16 | BType::Int24 | BType::Int32 | BType::Int64 | BType::Enum => {
            matches!(value, Value::Integer(_) | Value::Unsigned(_))
        }
        BType::Int8U | BType::Int16U | BType::Int24U | BType::Int32U => matches!(value, Value::Integer(_) | Value::Unsigned(_)),
        BType::Float32 | BType::Float64 => matches!(value, Value::Float32(_) | Value::Float64(_)),
        BType::Quality | BType::Dbpos | BType::Tcmd | BType::Check | BType::TrgOps | BType::OptFlds | BType::SvOptFlds | BType::LogOptFlds => {
            matches!(value, Value::BitString { .. })
        }
        BType::Timestamp => matches!(value, Value::UtcTime(_)),
        BType::EntryTime => matches!(value, Value::BinaryTime(_)),
        BType::Octet64 | BType::EntryID | BType::PhyComAddr | BType::Octet6 | BType::Octet16 => matches!(value, Value::OctetString(_)),
        BType::Unicode255 => matches!(value, Value::MmsString(_) | Value::VisibleString(_)),
        BType::Struct | BType::Other(_) => matches!(value, Value::Structure(_)),
        _ => matches!(value, Value::VisibleString(_) | Value::MmsString(_)),
    }
}

/// The components of a report control block, in the order IEC 61850-8-1 Tables 37 and 39 put
/// them — which is not the order the prose lists them in, and not the same for both kinds.
///
/// `Resv` is the **third** component of an unbuffered block, not a trailing one, and the
/// buffered block's `SqNum` is sixteen bits where the unbuffered one's is eight 🌐
/// (libiec61850 `reporting.c`). A client that reads the whole block positionally depends on
/// every one of these.
pub fn rcb_components(buffered: bool, edition: Edition) -> Vec<(&'static str, BType)> {
    let mut out: Vec<(&'static str, BType)> = alloc::vec![("RptID", BType::VisString129), ("RptEna", BType::Boolean)];
    if !buffered {
        out.push(("Resv", BType::Boolean));
    }
    out.extend([
        ("DatSet", BType::VisString129),
        ("ConfRev", BType::Int32U),
        ("OptFlds", BType::OptFlds),
        ("BufTm", BType::Int32U),
        ("SqNum", if buffered { BType::Int16U } else { BType::Int8U }),
        ("TrgOps", BType::TrgOps),
        ("IntgPd", BType::Int32U),
        ("GI", BType::Boolean),
    ]);
    if buffered {
        out.extend([("PurgeBuf", BType::Boolean), ("EntryID", BType::EntryID), ("TimeOfEntry", BType::EntryTime)]);
        // `ResvTms` arrived with Edition 2. An Ed1 server that publishes it claims a
        // reservation service it does not have, and a client reading the block positionally
        // then reads everything after it at the wrong offset.
        if edition.has_rcb_reservation() {
            out.push(("ResvTms", BType::Int16));
        }
    }
    if edition.has_rcb_reservation() {
        out.push(("Owner", BType::Octet64));
    }
    out
}

/// The components of a log control block (IEC 61850-7-2 §17).
pub fn lcb_components() -> Vec<(&'static str, BType)> {
    alloc::vec![
        ("LogEna", BType::Boolean),
        ("LogRef", BType::VisString129),
        ("DatSet", BType::VisString129),
        ("OldEntrTm", BType::EntryTime),
        ("NewEntrTm", BType::EntryTime),
        ("OldEnt", BType::EntryID),
        ("NewEnt", BType::EntryID),
        ("TrgOps", BType::TrgOps),
        ("IntgPd", BType::Int32U),
    ]
}

/// The components of the setting group control block (IEC 61850-7-2 §11).
pub fn sgcb_components() -> Vec<(&'static str, BType)> {
    alloc::vec![
        ("NumOfSG", BType::Int8U),
        ("ActSG", BType::Int8U),
        ("EditSG", BType::Int8U),
        ("CnfEdit", BType::Boolean),
        ("LActTm", BType::EntryTime),
        ("ResvTms", BType::Int16U),
    ]
}

/// The components of a GOOSE control block, in order.
///
/// Nine of them, and the last four are the ones a short version leaves out: `DstAddress` is
/// the `PhyComAddr` structure the block publishes to, `MinTime`/`MaxTime` are the
/// retransmission curve, and `FixedOffs` says whether the frames are fixed-length encoded.
/// A client that reads the block **positionally** — and Edition 1 clients do — reads every
/// field after a missing one at the wrong offset, so the set is the whole set 🌐
/// (libiec61850 `mms_goose.c`, `createMmsGooseControlBlock`).
fn gocb_components(fc: Fc) -> Vec<Variable> {
    alloc::vec![
        Variable::leaf("GoEna", Some(fc), BType::Boolean),
        Variable::leaf("GoID", Some(fc), BType::VisString129),
        Variable::leaf("DatSet", Some(fc), BType::VisString129),
        Variable::leaf("ConfRev", Some(fc), BType::Int32U),
        Variable::leaf("NdsCom", Some(fc), BType::Boolean),
        tree::phy_com_addr("DstAddress", Some(fc)),
        Variable::leaf("MinTime", Some(fc), BType::Int32U),
        Variable::leaf("MaxTime", Some(fc), BType::Int32U),
        Variable::leaf("FixedOffs", Some(fc), BType::Boolean),
    ]
}

/// The components of a sampled-value control block, in order 🌐 (libiec61850 `mms_sv.c`,
/// `createSVControlBlock`).
///
/// Two blocks, not one. IEC 61850-7-2 §12 gives a **multicast** stream an `MSVCB` under `MS`
/// and a **unicast** one a `USVCB` under `US`, and the difference is not only the constraint:
/// the identifier is `MsvID` in one and `UsvID` in the other, and `noASDU` — how many ASDUs
/// one frame carries — is a multicast concept the unicast block does not have. SCL says which
/// with `SampledValueControl/@multicast`, and a server that publishes every block as an
/// `MSVCB` answers a client that asked for `UsvID` with `object-non-existent` while offering
/// it a field its block cannot have.
///
/// `noASDU` is spelt with a small `n`, which is what the standard's attribute name is and
/// what a client asks for by name.
fn svcb_components(multicast: bool) -> Vec<Variable> {
    let fc = svcb_fc(multicast);
    let mut out = alloc::vec![
        Variable::leaf("SvEna", Some(fc), BType::Boolean),
        Variable::leaf(if multicast { "MsvID" } else { "UsvID" }, Some(fc), BType::VisString129),
        Variable::leaf("DatSet", Some(fc), BType::VisString129),
        Variable::leaf("ConfRev", Some(fc), BType::Int32U),
        Variable::leaf("SmpRate", Some(fc), BType::Int32U),
        Variable::leaf("OptFlds", Some(fc), BType::SvOptFlds),
        // `smpMod` is an enumeration, which the 8-1 mapping makes an eight-bit INTEGER.
        Variable::leaf("SmpMod", Some(fc), BType::Enum),
        tree::phy_com_addr("DstAddress", Some(fc)),
    ];
    if multicast {
        out.push(Variable::leaf("noASDU", Some(fc), BType::Int32U));
    }
    out
}

/// The functional constraint a sampled-value control block lives under.
const fn svcb_fc(multicast: bool) -> Fc {
    if multicast { Fc::MS } else { Fc::US }
}

fn rcb_defaults(rcb: &ReportControl, base: &str, data_set: Option<&str>, edition: Edition) -> Vec<(&'static str, Value)> {
    let mut out: Vec<(&'static str, Value)> = alloc::vec![
        // A block with no engineered `rptID` reports under its own reference, which is what
        // IEC 61850-7-2 §17.2.2 says the default is.
        ("RptID", Value::VisibleString(rcb.rpt_id.clone().unwrap_or_else(|| String::from(base)))),
        ("RptEna", Value::Boolean(false)),
        ("DatSet", Value::VisibleString(String::from(data_set.unwrap_or("")))),
        ("ConfRev", Value::Unsigned(u64::from(rcb.conf_rev))),
        // The two flags an unbuffered block cannot honour are cleared here rather than at
        // report time as well: a client that *reads* `OptFlds` should see what the block will
        // actually send. SCL's `bufOvfl` defaults to true, so this is the common case, not a
        // corner one.
        ("OptFlds", if rcb.buffered { rcb.opt_flds.to_value() } else { rcb.opt_flds.with_buffer_overflow(false).with_entry_id(false).to_value() }),
        ("BufTm", Value::Unsigned(u64::from(rcb.buf_time_ms))),
        ("SqNum", Value::Unsigned(0)),
        ("TrgOps", rcb.trg_ops.to_value()),
        ("IntgPd", Value::Unsigned(u64::from(rcb.intg_pd_ms))),
        ("GI", Value::Boolean(false)),
    ];
    if edition.has_rcb_reservation() {
        out.push(("Owner", Value::OctetString(Vec::new())));
    }
    if rcb.buffered {
        out.extend([
            ("PurgeBuf", Value::Boolean(false)),
            ("EntryID", Value::OctetString(Vec::new())),
            ("TimeOfEntry", Value::BinaryTime(EntryTime::default().to_octets().to_vec())),
        ]);
        if edition.has_rcb_reservation() {
            out.push(("ResvTms", Value::Integer(0)));
        }
    } else {
        out.push(("Resv", Value::Boolean(false)));
    }
    out
}

/// The engineered values of a GOOSE control block, from the `GSEControl` and the `GSE`
/// address the `Communication` section gives it.
///
/// A block with no address in the file publishes nothing, and its `DstAddress` stays the
/// zeros the tree seeded — which is the honest answer to "where does this go?" for a file
/// that does not say.
fn gocb_defaults(gcb: &crate::model::GseControl, base: &str, ld: &str, ln: &str) -> Vec<(String, Value)> {
    let mut out = alloc::vec![
        (String::from("GoEna"), Value::Boolean(false)),
        // `GoID` defaults to the control block's own reference, exactly as a report control
        // block's `RptID` does (IEC 61850-7-2 §18.2.1).
        (String::from("GoID"), Value::VisibleString(gcb.go_id.clone().unwrap_or_else(|| String::from(base)))),
        (String::from("DatSet"), Value::VisibleString(gcb.dat_set.as_ref().map_or_else(String::new, |d| alloc::format!("{ld}/{ln}${d}")))),
        (String::from("ConfRev"), Value::Unsigned(u64::from(gcb.conf_rev))),
        (String::from("NdsCom"), Value::Boolean(false)),
        (String::from("FixedOffs"), Value::Boolean(gcb.fixed_offs)),
    ];
    if let Some(a) = &gcb.address {
        out.push((String::from("DstAddress$Addr"), Value::OctetString(a.mac.0.to_vec())));
        out.push((String::from("DstAddress$PRIORITY"), Value::Unsigned(u64::from(a.vlan_priority))));
        out.push((String::from("DstAddress$VID"), Value::Unsigned(u64::from(a.vlan_id))));
        out.push((String::from("DstAddress$APPID"), Value::Unsigned(u64::from(a.appid))));
        out.push((String::from("MinTime"), Value::Unsigned(u64::from(a.min_time_ms.unwrap_or(0)))));
        out.push((String::from("MaxTime"), Value::Unsigned(u64::from(a.max_time_ms.unwrap_or(0)))));
    }
    out
}

/// The engineered values of a sampled-value control block, from the `SampledValueControl` and
/// its `SMV` address.
fn svcb_defaults(scb: &crate::model::SmvControl, ld: &str, ln: &str) -> Vec<(String, Value)> {
    let smp_mod = match scb.smp_mod.as_str() {
        "SmpPerSec" => 1,
        "SecPerSmp" => 2,
        _ => 0,
    };
    let mut out = alloc::vec![
        (String::from("SvEna"), Value::Boolean(false)),
        (String::from(if scb.multicast { "MsvID" } else { "UsvID" }), Value::VisibleString(scb.smv_id.clone())),
        (String::from("DatSet"), Value::VisibleString(scb.dat_set.as_ref().map_or_else(String::new, |d| alloc::format!("{ld}/{ln}${d}")))),
        (String::from("ConfRev"), Value::Unsigned(u64::from(scb.conf_rev))),
        (String::from("SmpRate"), Value::Unsigned(u64::from(scb.smp_rate))),
        (String::from("SmpMod"), Value::Integer(smp_mod)),
    ];
    if scb.multicast {
        out.push((String::from("noASDU"), Value::Unsigned(u64::from(scb.nof_asdu))));
    }
    if let Some(a) = &scb.address {
        out.push((String::from("DstAddress$Addr"), Value::OctetString(a.mac.0.to_vec())));
        out.push((String::from("DstAddress$PRIORITY"), Value::Unsigned(u64::from(a.vlan_priority))));
        out.push((String::from("DstAddress$VID"), Value::Unsigned(u64::from(a.vlan_id))));
        out.push((String::from("DstAddress$APPID"), Value::Unsigned(u64::from(a.appid))));
    }
    out
}

fn lcb_defaults(lcb: &crate::model::LogControl, log: &str, ld: &crate::model::LogicalDevice, ln: &LogicalNode) -> Vec<(&'static str, Value)> {
    let data_set = lcb.dat_set.as_ref().map_or_else(String::new, |d| alloc::format!("{}/{}${d}", ld.name, ln.name));
    alloc::vec![
        ("LogEna", Value::Boolean(lcb.log_ena)),
        ("LogRef", Value::VisibleString(String::from(log))),
        ("DatSet", Value::VisibleString(data_set)),
        ("OldEntrTm", Value::BinaryTime(EntryTime::default().to_octets().to_vec())),
        ("NewEntrTm", Value::BinaryTime(EntryTime::default().to_octets().to_vec())),
        ("OldEnt", Value::OctetString(Vec::new())),
        ("NewEnt", Value::OctetString(Vec::new())),
        ("TrgOps", lcb.trg_ops.to_value()),
        ("IntgPd", Value::Unsigned(u64::from(lcb.intg_pd_ms))),
    ]
}

fn sgcb_defaults(sg: crate::model::SettingControl) -> Vec<(&'static str, Value)> {
    alloc::vec![
        ("NumOfSG", Value::Unsigned(u64::from(sg.num_of_sgs))),
        ("ActSG", Value::Unsigned(u64::from(sg.act_sg))),
        ("EditSG", Value::Unsigned(0)),
        ("CnfEdit", Value::Boolean(false)),
        ("LActTm", Value::BinaryTime(EntryTime::default().to_octets().to_vec())),
        ("ResvTms", Value::Unsigned(u64::from(sg.resv_tms.unwrap_or(0)))),
    ]
}

/// A `(name, bType)` component list as the tree's leaves.
fn leaves(fc: Fc, components: &[(&'static str, BType)]) -> Vec<Variable> {
    components.iter().map(|(n, b)| Variable::leaf(*n, Some(fc), b.clone())).collect()
}

/// The control-block variables of one logical node, and the [`Block`] record for each.
fn control_blocks(ld_name: &str, ln: &LogicalNode, edition: Edition, found: &mut Vec<Block>) -> Vec<(Fc, Variable)> {
    let mut out = Vec::new();
    let mut add = |fc: Fc, name: String, kind: BlockKind, children: Vec<Variable>, data_set: Option<String>, out: &mut Vec<(Fc, Variable)>| {
        found.push(Block {
            reference: alloc::format!("{ld_name}/{}${}${name}", ln.name, fc.as_str()),
            domain: String::from(ld_name),
            node: ln.name.clone(),
            name: name.clone(),
            kind,
            data_set,
        });
        out.push((fc, Variable { name, kind: VarKind::Structure, fc: Some(fc), children }));
    };

    for rcb in &ln.report_controls {
        let fc = rcb.fc();
        let kind = if rcb.buffered { BlockKind::Buffered } else { BlockKind::Unbuffered };
        let data_set = rcb.dat_set.as_ref().map(|d| alloc::format!("{ld_name}/{}${d}", ln.name));
        for name in rcb.instance_names() {
            add(fc, name, kind, leaves(fc, &rcb_components(rcb.buffered, edition)), data_set.clone(), &mut out);
        }
    }
    for lcb in &ln.log_controls {
        let data_set = lcb.dat_set.as_ref().map(|d| alloc::format!("{ld_name}/{}${d}", ln.name));
        add(Fc::LG, lcb.name.clone(), BlockKind::Log, leaves(Fc::LG, &lcb_components()), data_set, &mut out);
    }
    for gcb in &ln.gse_controls {
        let data_set = gcb.dat_set.as_ref().map(|d| alloc::format!("{ld_name}/{}${d}", ln.name));
        add(Fc::GO, gcb.name.clone(), BlockKind::Goose, gocb_components(Fc::GO), data_set, &mut out);
    }
    for scb in &ln.smv_controls {
        let data_set = scb.dat_set.as_ref().map(|d| alloc::format!("{ld_name}/{}${d}", ln.name));
        add(svcb_fc(scb.multicast), scb.name.clone(), BlockKind::SampledValue, svcb_components(scb.multicast), data_set, &mut out);
    }
    if ln.setting_control.is_some() {
        add(Fc::SP, String::from("SGCB"), BlockKind::SettingGroup, leaves(Fc::SP, &sgcb_components()), None, &mut out);
    }
    out
}