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
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
//! A blocking IEC 61850 client over MMS — the ten-line path.
//!
//! [`Client::connect`] dials TCP. [`Client::with_transport`] drives the same MMS services
//! over an existing blocking stream, including the plaintext side of a verified TLS connection.
//!
//! ```no_run
//! use iec61850_kit::client::Client;
//! use iec61850_kit::Fc;
//!
//! # fn main() -> iec61850_kit::Result<()> {
//! let mut c = Client::connect("10.0.0.5:102")?;
//! for ld in c.server_directory()? {                      // the logical devices
//!     for name in c.logical_device_directory(&ld)? {      // the logical nodes and data
//!         println!("{ld}/{name}");
//!     }
//! }
//! let w = c.read("IED1LD0/MMXU1.TotW.mag.f", Fc::MX)?;
//! c.release()?;
//! # Ok(()) }
//! ```
//!
//! **Blocking on purpose.** The core is sans-IO, so an async wrapper is an adapter over the
//! same state machine; blocking needs no runtime and no dependency at all.
//!
//! One association per client. Reports and command terminations that arrive while a request is
//! outstanding are kept, not dropped. [`Client::is_alive`] is a `Status` round trip and
//! [`Client::reconnect`] opens a new association on a [`Backoff`] the caller states, restoring
//! nothing the old one held.

use std::collections::VecDeque;
use std::io::{Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::{Duration, Instant as StdInstant};

mod control;
mod files;
mod log;
mod rcb;
mod sg;
mod tariff;

pub use control::{CONTROL_ATTRIBUTES, Control};
pub use files::FileEntry;
pub use log::{Lcb, LogEntry, LogPage};
pub use rcb::{Rcb, RcbSettings};
pub use sg::Sgcb;
pub use tariff::{TariffProfile, TariffRead, TariffSchedule, TariffSlot};

// The report types belong to the codec; re-exported here because a client user reaches for
// them without needing to know which layer they came from.
pub use crate::proto::mms::control::{AddCause, Check, CommandTermination, ControlModel, LastApplError, Origin, OriginCategory};
pub use crate::proto::mms::report::{AssemblerStats, OptFlds, ReasonCode, Report, ReportAssembler, ReportEntry, TrgOps};
pub use crate::proto::mms::typespec::{Component, TypeSpec};

use crate::common::{Error, Fc, Instant, Limits, ObjectReference, Result};
use crate::proto::data::{DataView, Typed, Value};
use crate::proto::mms::association::{Association, AssociationConfig, AssociationEvent, CloseReason, PORT};
use crate::proto::mms::control::ControlRequest;
use crate::proto::mms::{
    AccessResult, AlternateAccess, ConfirmedRequest, ConfirmedResponse, Mms, ObjectName, ObjectScope, ServiceError, Unconfirmed, VariableAccess,
    VariableSpecification, delete_scope, object_class,
};

/// How long to wait between reconnection attempts, and how many to make.
///
/// A substation link drops for reasons that clear on their own — a switch reboot, a
/// redundancy switchover, a maintenance window — and a client that gives up on the first
/// refusal needs a human. One that retries without waiting turns a busy server into a
/// refused-connection storm, which is why the delay grows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Backoff {
    /// Wait before the first retry.
    pub first: Duration,
    /// The longest wait, whatever the factor would make it.
    pub max: Duration,
    /// What the wait is multiplied by after each failure.
    pub factor: u32,
    /// How many attempts to make in total; `0` means keep trying.
    pub attempts: usize,
}

impl Default for Backoff {
    /// 500 ms doubling to 30 s, for ever — the shape a SCADA gateway wants, because a link
    /// that has been down for an hour is still a link worth trying.
    fn default() -> Backoff {
        Backoff { first: Duration::from_millis(500), max: Duration::from_secs(30), factor: 2, attempts: 0 }
    }
}

impl Backoff {
    /// A policy that gives up after `attempts` tries.
    #[must_use]
    pub const fn bounded(mut self, attempts: usize) -> Backoff {
        self.attempts = attempts;
        self
    }

    /// The wait before attempt `n` (zero-based), saturating at [`Backoff::max`].
    pub fn delay(&self, n: u32) -> Duration {
        let scale = u64::from(self.factor.max(1)).checked_pow(n).unwrap_or(u64::MAX);
        Duration::from_nanos(u64::try_from(self.first.as_nanos()).unwrap_or(u64::MAX).saturating_mul(scale)).min(self.max)
    }
}

/// What a server says about its own health (`Status`).
///
/// The two numbers are ISO 9506's, not IEC 61850's — see
/// [`vmd_logical`](crate::proto::mms::vmd_logical) and
/// [`vmd_physical`](crate::proto::mms::vmd_physical) for what each value means.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ServerStatus {
    /// `vmdLogicalStatus` — whether the server will accept requests that change its state.
    pub logical: i64,
    /// `vmdPhysicalStatus` — whether the device behind it is working.
    pub physical: i64,
}

impl ServerStatus {
    /// True when the server is operational and taking state changes.
    pub const fn is_healthy(self) -> bool {
        self.logical == crate::proto::mms::vmd_logical::STATE_CHANGES_ALLOWED && self.physical == crate::proto::mms::vmd_physical::OPERATIONAL
    }
}

/// What a server says it is (`Identify`).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Identity {
    /// Vendor name.
    pub vendor: String,
    /// Model name.
    pub model: String,
    /// Revision.
    pub revision: String,
}

/// Something the server sent without being asked.
///
/// Three things arrive this way on an IEC 61850 association and they are told apart by what
/// the `InformationReport` names, not by a tag: a **report** names a report control block, a
/// **command termination** names a control object's `Oper`, and anything else is handed over
/// as it arrived rather than guessed at.
#[derive(Clone, Debug, PartialEq)]
pub enum Unsolicited {
    /// A report from a report control block, decoded per IEC 61850-8-1 Table 40.
    Report(Box<Report>),
    /// The final answer to an enhanced-security control.
    CommandTermination(Box<CommandTermination>),
    /// An `InformationReport` that is neither — another stack's data set report, or a report
    /// this decoder could not make sense of. The raw PDU comes with it so nothing is lost.
    Other {
        /// What the report named.
        name: String,
        /// The `AccessResult`s, decoded, in the order the server sent them.
        values: Vec<Value>,
        /// The whole encoded MMS PDU.
        raw: Vec<u8>,
    },
}

impl Unsolicited {
    /// Classify an encoded `unconfirmed-PDU`.
    ///
    /// Returns `None` for anything that is not an `InformationReport`, or that does not
    /// decode. Public because the classification is useful without a socket: `ied mms sniff`
    /// runs it over a capture, so what the tool says a report contains is what a client
    /// would have been handed.
    pub fn from_pdu(pdu: &[u8], limits: &Limits) -> Option<Unsolicited> {
        let Ok(Mms::Unconfirmed(Unconfirmed::InformationReport { access, results })) = Mms::parse(pdu, limits) else {
            return None;
        };
        // A failed access inside a report is a hole, not a value, and inventing a placeholder
        // would shift every field after it. So a report with one is not decoded — but it is
        // still handed over, whole, because losing it entirely would be worse.
        let mut values = Vec::with_capacity(results.len());
        let mut complete = true;
        for r in &results {
            match r {
                AccessResult::Success(t) => match DataView::from_tlv(*t).ok().and_then(|d| d.to_owned(limits).ok()) {
                    Some(v) => values.push(v),
                    None => complete = false,
                },
                AccessResult::Failure(_) => complete = false,
            }
        }
        if !complete {
            let name = match &access {
                VariableAccess::VariableListName(n) => object_name(n),
                VariableAccess::ListOfVariable(names) => names.iter().map(specification_name).collect::<Vec<_>>().join(", "),
            };
            return Some(Unsolicited::Other { name, values: Vec::new(), raw: pdu.to_vec() });
        }
        Some(match &access {
            VariableAccess::VariableListName(name) => {
                let name = object_name(name);
                match Report::from_values(&values) {
                    Ok(r) => Unsolicited::Report(Box::new(r)),
                    Err(_) => Unsolicited::Other { name, values, raw: pdu.to_vec() },
                }
            }
            VariableAccess::ListOfVariable(names) => match termination(names, &values) {
                Some(t) => Unsolicited::CommandTermination(Box::new(t)),
                None => Unsolicited::Other { name: names.iter().map(specification_name).collect::<Vec<_>>().join(", "), values, raw: pdu.to_vec() },
            },
        })
    }

    /// The report, when this is one.
    pub fn report(&self) -> Option<&Report> {
        match self {
            Unsolicited::Report(r) => Some(r),
            _ => None,
        }
    }

    /// The command termination, when this is one.
    pub fn termination(&self) -> Option<&CommandTermination> {
        match self {
            Unsolicited::CommandTermination(t) => Some(t),
            _ => None,
        }
    }
}

/// How a client connects.
#[derive(Clone, Debug)]
pub struct ClientConfig {
    /// The association parameters — selectors, sizes, timeouts, the ACSE password.
    pub association: AssociationConfig,
    /// How long to wait for the TCP connection itself.
    pub connect_timeout: Duration,
}

impl Default for ClientConfig {
    fn default() -> ClientConfig {
        ClientConfig { association: AssociationConfig::default(), connect_timeout: Duration::from_secs(10) }
    }
}

#[cfg(feature = "scl")]
impl ClientConfig {
    /// Take the association's addressing from an SCL file.
    ///
    /// `Communication/ConnectedAP` is where a station's OSI addressing is engineered — the
    /// transport, session and presentation selectors, the AP-title and the AE-qualifier —
    /// and every one of them has to match or the server refuses the association at a layer
    /// whose error message says nothing useful. Reading them out of the SCD is the same rule
    /// the process bus already follows: **the engineering file is the configuration**.
    ///
    /// Returns the configuration and the `IP` the file gives the access point, when it has
    /// one — a caller that is connecting through a gateway overrides it.
    pub fn from_scl(scl: &crate::scl::Scl<'_>, ied: &str, access_point: Option<&str>) -> Result<(ClientConfig, Option<String>)> {
        let model = scl.model(Some(ied))?;
        let address = model.osi_address(access_point).ok_or(Error::NotFound("ConnectedAP address for this IED"))?;
        let cfg = ClientConfig {
            association: AssociationConfig { remote: crate::proto::mms::association::Selectors::from_address(address), ..AssociationConfig::default() },
            ..ClientConfig::default()
        };
        Ok((cfg, address.ip.clone()))
    }
}

/// A blocking MMS client: one association on a blocking duplex stream.
#[derive(Debug)]
pub struct Client<S = TcpStream> {
    stream: Option<S>,
    set_read_timeout: fn(&mut S, Duration) -> std::io::Result<()>,
    assoc: Association,
    limits: Limits,
    /// What the server sent while something else was being waited for.
    unsolicited: VecDeque<Unsolicited>,
    /// Joins the segments of a segmented report before it reaches the queue, so a caller
    /// never sees half of one.
    assembler: ReportAssembler,
    /// The `ctlNum` the next control sequence gets.
    ctl_num: u8,
    epoch: StdInstant,
    rx: Vec<u8>,
    /// How long a confirmed request may go unanswered, from the configuration this client
    /// was built with — not from the default, which is what a `&self` helper would have read.
    request_timeout: Duration,
    /// Where this client dialled and with what, so it can dial again. `None` for a client
    /// built from a socket somebody else opened ([`Client::from_stream`]) — there is nothing
    /// to reconnect *to* when the transport was handed in.
    origin: Option<(String, ClientConfig)>,
    /// The one file this client serves to the server while a `set_file` runs.
    pub(crate) serving: Option<files::Serving>,
    /// When this client last served the server during a `set_file`.
    pub(crate) progress: Option<StdInstant>,
}

impl Client {
    /// Connect and associate, with the defaults.
    ///
    /// `addr` may omit the port, in which case 102 is used.
    pub fn connect(addr: &str) -> Result<Client> {
        Client::connect_with(addr, &ClientConfig::default())
    }

    /// Connect and associate with an explicit configuration.
    pub fn connect_with(addr: &str, cfg: &ClientConfig) -> Result<Client> {
        let with_port = with_default_port(addr);
        let target =
            with_port.to_socket_addrs().map_err(|e| Error::Io(format!("{addr}: {e}")))?.next().ok_or_else(|| Error::Io(format!("{addr}: no address")))?;
        let stream = TcpStream::connect_timeout(&target, cfg.connect_timeout).map_err(|e| Error::Io(format!("{addr}: {e}")))?;
        let mut c = Self::from_stream(stream, cfg)?;
        c.origin = Some((String::from(addr), cfg.clone()));
        Ok(c)
    }

    /// Connect, retrying on the given policy.
    ///
    /// The first attempt is immediate; each failure waits [`Backoff::delay`] and tries again.
    /// The error returned is the **last** one, because that is the one that describes the
    /// state the link is in now.
    pub fn connect_retrying(addr: &str, cfg: &ClientConfig, backoff: &Backoff) -> Result<Client> {
        let mut n = 0u32;
        loop {
            match Client::connect_with(addr, cfg) {
                Ok(c) => return Ok(c),
                Err(e) => {
                    if backoff.attempts != 0 && usize::try_from(n).unwrap_or(usize::MAX).saturating_add(1) >= backoff.attempts {
                        return Err(e);
                    }
                    std::thread::sleep(backoff.delay(n));
                    n = n.saturating_add(1);
                }
            }
        }
    }

    /// Open the association again after it dropped, on the same address and configuration.
    ///
    /// What is **not** restored is deliberate: report control blocks, selections and file
    /// handles all belong to the association that ended, and a client that silently
    /// re-enabled them would be claiming a subscription the server does not know it has. A
    /// buffered control block is the exception the standard already provides for — re-enable
    /// it with the `EntryID` of the last report seen and the server replays what was missed
    /// ([`Client::enable_rcb`] with [`RcbSettings::resume_after`]).
    ///
    /// Fails for a client built from a socket somebody else opened: there is nothing to dial.
    pub fn reconnect(&mut self, backoff: &Backoff) -> Result<()> {
        let (addr, cfg) = self.origin.clone().ok_or(Error::InvalidValue("this client was built from a socket, so it has nowhere to reconnect to"))?;
        *self = Self::connect_retrying(&addr, &cfg, backoff)?;
        Ok(())
    }

    /// Associate over an already connected TCP socket at the first TPKT byte.
    pub fn from_stream(stream: TcpStream, cfg: &ClientConfig) -> Result<Client> {
        stream.set_nodelay(true).map_err(|e| Error::Io(e.to_string()))?;
        Self::with_transport(stream, cfg, |tcp, timeout| tcp.set_read_timeout(Some(timeout)))
    }

    /// Connect to an IED the way its SCD says to.
    ///
    /// The address, the selectors and the ACSE names all come out of
    /// `Communication/ConnectedAP`, so an association is engineered once, in the file, and
    /// never typed a second time into code. `host` overrides the file's `IP` when the server
    /// is reached through a gateway or a test bench; pass `None` to use what the file says.
    #[cfg(feature = "scl")]
    pub fn connect_scl(scl: &crate::scl::Scl<'_>, ied: &str, access_point: Option<&str>, host: Option<&str>) -> Result<Client> {
        let (cfg, ip) = ClientConfig::from_scl(scl, ied, access_point)?;
        let host = match (host, ip.as_deref()) {
            (Some(h), _) => String::from(h),
            (None, Some(ip)) => String::from(ip),
            (None, None) => return Err(Error::NotFound("the SCL file gives this access point no IP address")),
        };
        Client::connect_with(&host, &cfg)
    }
}

impl<S: Read + Write> Client<S> {
    /// Associate over an application-supplied stream at the first plaintext TPKT byte.
    ///
    /// For TLS, finish peer verification before calling this method. The callback must
    /// bound the next blocking read by the supplied duration. Set a write timeout on the
    /// underlying transport before handoff. Pass a mutable borrow to retain ownership for
    /// TLS shutdown after [`Self::release`].
    pub fn with_transport(stream: S, cfg: &ClientConfig, set_read_timeout: fn(&mut S, Duration) -> std::io::Result<()>) -> Result<Self> {
        let limits = cfg.association.limits;
        let mut c = Client {
            stream: Some(stream),
            set_read_timeout,
            assoc: Association::client(cfg.association.clone()),
            limits,
            unsolicited: VecDeque::new(),
            assembler: ReportAssembler::new(8),
            ctl_num: 0,
            epoch: StdInstant::now(),
            rx: alloc_buffer(),
            request_timeout: request_timeout(&cfg.association),
            // A socket somebody else opened cannot be opened again by this client.
            origin: None,
            serving: None,
            progress: None,
        };
        let now = c.now();
        c.assoc.start(now)?;
        c.flush()?;
        c.pump_while(|a| !a.is_established(), Duration::from_millis(cfg.association.connect_timeout_ms))?;
        Ok(c)
    }

    /// Whether the association is still answering, by the cheapest question there is.
    ///
    /// A TCP connection that has lost its peer looks open until something is written to it,
    /// so "is the socket up" is not the same question as "is the server there". A `Status`
    /// round trip is: it needs no name, no model and no data set, and it exercises all six
    /// layers. This is what a supervision loop calls between reports.
    pub fn is_alive(&mut self) -> bool {
        self.assoc.is_established() && self.status(false).is_ok()
    }

    /// The `ctlModel` of a controllable object, read from the server.
    ///
    /// A control sequence that assumes the wrong model does nothing and says nothing: an
    /// object engineered for select-before-operate answers an unselected `Oper` with
    /// `AddCause::ObjectNotSelected`. One extra `Read` of `$CF$<DO>$ctlModel` removes the
    /// guess, and the answer can be cached for the life of the association.
    pub fn read_control_model(&mut self, reference: &str) -> Result<ControlModel> {
        let parsed = ObjectReference::parse(reference)?;
        // `to_mms_under`, not `to_mms`: the caller usually holds the object as
        // `LN$CO$DO` — the controllable object — and `ctlModel` lives under `CF`. Keeping
        // the reference's own constraint asks for a `CO$…$ctlModel` no server has, and the
        // read fails silently into "assume direct control".
        let (domain, item) = parsed.to_mms_under(Fc::CF);
        let full = format!("{domain}/{item}$ctlModel");
        let v = self.read(&full, Fc::CF)?;
        let code = v.as_i64().or_else(|| v.as_u64().and_then(|u| i64::try_from(u).ok())).ok_or(Error::InvalidValue("ctlModel is not an integer"))?;
        ControlModel::from_code(code).ok_or(Error::InvalidValue("ctlModel is outside the enumeration"))
    }

    /// What the two ends agreed on.
    pub fn negotiated(&self) -> Option<crate::proto::mms::association::Negotiated> {
        self.assoc.negotiated()
    }

    /// The association's counters.
    pub fn stats(&self) -> crate::proto::mms::association::AssociationStats {
        self.assoc.stats()
    }

    /// `Identify` — vendor, model and revision.
    pub fn identify(&mut self) -> Result<Identity> {
        let pdu = self.call(&ConfirmedRequest::Identify)?;
        match Mms::parse(&pdu, &self.limits)? {
            Mms::ConfirmedResponse { service: ConfirmedResponse::Identify { vendor, model, revision }, .. } => {
                Ok(Identity { vendor: String::from(vendor), model: String::from(model), revision: String::from(revision) })
            }
            _ => Err(Error::InvalidValue("not an Identify response")),
        }
    }

    /// `Status` — is the server healthy, and will it accept state changes?
    ///
    /// This is the cheapest question there is and the one a SCADA client asks first and last:
    /// it needs no name, no model and no data set, so an answer proves the whole six-layer
    /// association is alive. `extended_derivation` asks the server to re-derive its status
    /// rather than report a cached one.
    pub fn status(&mut self, extended_derivation: bool) -> Result<ServerStatus> {
        let pdu = self.call(&ConfirmedRequest::Status { extended_derivation })?;
        match Mms::parse(&pdu, &self.limits)? {
            Mms::ConfirmedResponse { service: ConfirmedResponse::Status { logical, physical, .. }, .. } => Ok(ServerStatus { logical, physical }),
            _ => Err(Error::InvalidValue("not a Status response")),
        }
    }

    /// `GetCapabilityList` — the free-form strings the server says describe what it can do.
    ///
    /// Paged like every other list here: `moreFollows` is followed until the server stops.
    pub fn capabilities(&mut self) -> Result<Vec<String>> {
        let mut out: Vec<String> = Vec::new();
        loop {
            let after = out.last().cloned();
            let pdu = self.call(&ConfirmedRequest::GetCapabilityList { continue_after: after.as_deref() })?;
            let (page, more) = match Mms::parse(&pdu, &self.limits)? {
                Mms::ConfirmedResponse { service: ConfirmedResponse::GetCapabilityList { capabilities, more_follows }, .. } => {
                    (capabilities.iter().map(|c| String::from(*c)).collect::<Vec<_>>(), more_follows)
                }
                _ => return Err(Error::InvalidValue("not a GetCapabilityList response")),
            };
            let empty = page.is_empty();
            out.extend(page);
            // A server that says `moreFollows` and then sends nothing would loop for ever;
            // an empty page ends the walk whatever the flag claims.
            if !more || empty {
                return Ok(out);
            }
            if out.len() > self.limits.max_dataset_members {
                return Err(Error::LimitExceeded { limit: "max_dataset_members", value: out.len() });
            }
        }
    }

    /// `GetServerDirectory(LOGICAL-DEVICE)`: the logical devices this server hosts.
    ///
    /// MMS domains are logical devices, which is the whole of the mapping.
    pub fn server_directory(&mut self) -> Result<Vec<String>> {
        self.name_list(object_class::DOMAIN, ObjectScope::VmdSpecific)
    }

    /// `GetLogicalDeviceDirectory(ld)`: every named variable in one logical device.
    ///
    /// These come back in the MMS form (`LLN0$ST$Mod$stVal`), which is what the server holds
    /// them as; [`ObjectReference`] reads either spelling.
    pub fn logical_device_directory(&mut self, ld: &str) -> Result<Vec<String>> {
        self.name_list(object_class::NAMED_VARIABLE, ObjectScope::DomainSpecific(ld))
    }

    /// The data sets (`named variable lists`) of one logical device.
    pub fn data_set_directory(&mut self, ld: &str) -> Result<Vec<String>> {
        self.name_list(object_class::NAMED_VARIABLE_LIST, ObjectScope::DomainSpecific(ld))
    }

    /// The logs (`journals`) of one logical device.
    pub fn log_directory(&mut self, ld: &str) -> Result<Vec<String>> {
        self.name_list(object_class::JOURNAL, ObjectScope::DomainSpecific(ld))
    }

    /// The members of a data set, as MMS-form references.
    pub fn data_set_members(&mut self, ld: &str, name: &str) -> Result<Vec<String>> {
        let pdu = self.call(&ConfirmedRequest::GetNamedVariableListAttributes(ObjectName::DomainSpecific { domain: ld, item: name }))?;
        match Mms::parse(&pdu, &self.limits)? {
            Mms::ConfirmedResponse { service: ConfirmedResponse::GetNamedVariableListAttributes { variables, .. }, .. } => Ok(variables
                .iter()
                // A member may name **one element** of an array, which SCL writes as
                // `FCDA ix="7"` and ISO 9506 carries as an `alternateAccess`. The reference
                // this returns carries it in IEC 61850's own syntax — `…$phsAHar(7)$cVal` —
                // so a member that selects an element does not read as the whole array.
                .filter_map(|v| {
                    let selected = v.access().map(ToString::to_string).unwrap_or_default();
                    match v.name()? {
                        ObjectName::DomainSpecific { domain, item } => Some(format!("{domain}/{item}{selected}")),
                        ObjectName::VmdSpecific(n) | ObjectName::AaSpecific(n) => Some(format!("{n}{selected}")),
                    }
                })
                .collect()),
            _ => Err(Error::InvalidValue("not a GetNamedVariableListAttributes response")),
        }
    }

    /// Read one data attribute or data object.
    ///
    /// `reference` is either form — `IED1LD0/MMXU1.TotW.mag.f` with `fc`, or
    /// `IED1LD0/MMXU1$MX$TotW$mag$f`, which carries its own.
    pub fn read(&mut self, reference: &str, fc: Fc) -> Result<Value> {
        let addressed = Addressed::of(reference, fc)?;
        let access = VariableAccess::ListOfVariable(vec![addressed.spec()]);
        let mut values = self.read_access(&access)?;
        if values.len() == 1 { Ok(values.remove(0)) } else { Err(Error::InvalidValue("server returned the wrong number of values")) }
    }

    /// Read several references in one `Read` — one round trip instead of *n*.
    pub fn read_many(&mut self, references: &[(&str, Fc)]) -> Result<Vec<Value>> {
        let items = Addressed::all(references)?;
        let access = VariableAccess::ListOfVariable(items.iter().map(Addressed::spec).collect());
        self.read_access(&access)
    }

    /// Read several references in one `Read`, keeping the per-value failures.
    ///
    /// A `Read` of many variables answers with one `AccessResult` each, so one missing
    /// reference does not spoil the rest — which is exactly what reading a control block
    /// needs, since Edition 1 servers have no `ResvTms` and no `Owner`.
    pub fn read_many_results(&mut self, references: &[(&str, Fc)]) -> Result<Vec<Result<Value>>> {
        let items = Addressed::all(references)?;
        let access = VariableAccess::ListOfVariable(items.iter().map(Addressed::spec).collect());
        self.read_access_results(&access)
    }

    /// Read a whole data set in one request — the values, in the data set's own order.
    pub fn read_data_set(&mut self, ld: &str, name: &str) -> Result<Vec<Value>> {
        self.read_access(&VariableAccess::VariableListName(ObjectName::DomainSpecific { domain: ld, item: name }))
    }

    /// Write one data attribute.
    pub fn write(&mut self, reference: &str, fc: Fc, value: &Value) -> Result<()> {
        let addressed = Addressed::of(reference, fc)?;
        let encoded = Value::encode_all(std::slice::from_ref(value))?;
        let element = crate::ber::Cursor::new(&encoded).next_required()?;
        let access = VariableAccess::ListOfVariable(vec![addressed.spec()]);
        let pdu = self.call(&ConfirmedRequest::Write { access, values: vec![element] })?;
        match Mms::parse(&pdu, &self.limits)? {
            Mms::ConfirmedResponse { service: ConfirmedResponse::Write(results), .. } => match results.first() {
                Some(crate::proto::mms::WriteResult::Success) => Ok(()),
                Some(crate::proto::mms::WriteResult::Failure(code)) => Err(Error::DataAccess(*code)),
                None => Err(Error::InvalidValue("empty Write response")),
            },
            _ => Err(Error::InvalidValue("not a Write response")),
        }
    }

    /// `GetVariableAccessAttributes`: what *type* a variable is.
    ///
    /// One round trip turns "the write was refused with type-inconsistent" into something a
    /// tool can explain, and it is how a caller learns the component order of an `Oper`
    /// without having the SCD. The answer is stable for the life of the association.
    pub fn variable_type(&mut self, reference: &str, fc: Fc) -> Result<TypeSpec> {
        let parsed = ObjectReference::parse(reference)?;
        let (domain, item) = parsed.to_mms(fc);
        let pdu = self.call(&ConfirmedRequest::GetVariableAccessAttributes(ObjectName::DomainSpecific { domain, item: &item }))?;
        match Mms::parse(&pdu, &self.limits)? {
            Mms::ConfirmedResponse { service: ConfirmedResponse::GetVariableAccessAttributes { type_spec, .. }, .. } => Ok(type_spec),
            _ => Err(Error::InvalidValue("not a GetVariableAccessAttributes response")),
        }
    }

    /// Create a data set (`DefineNamedVariableList`).
    ///
    /// `name` is `LD/LLN0$dsName`; `members` are references in either spelling, each with the
    /// functional constraint to read it under. A data set created this way is *non-persistent*
    /// unless the server chooses otherwise, and IEC 61850-7-2 lets a server refuse to create
    /// one at all — which comes back as a service error rather than a silent no-op.
    pub fn create_data_set(&mut self, name: &str, members: &[(&str, Fc)]) -> Result<()> {
        let (ld, item) = split_data_set(name)?;
        let mut items = Vec::with_capacity(members.len());
        for (reference, fc) in members {
            let parsed = ObjectReference::parse(reference)?;
            let (domain, member) = parsed.to_mms(*fc);
            items.push((String::from(domain), member));
        }
        let variables = items.iter().map(|(d, i)| VariableSpecification::Name(ObjectName::DomainSpecific { domain: d, item: i })).collect::<Vec<_>>();
        let pdu = self.call(&ConfirmedRequest::DefineNamedVariableList { name: ObjectName::DomainSpecific { domain: &ld, item: &item }, variables })?;
        match Mms::parse(&pdu, &self.limits)? {
            Mms::ConfirmedResponse { service: ConfirmedResponse::DefineNamedVariableList, .. } => Ok(()),
            _ => Err(Error::InvalidValue("not a DefineNamedVariableList response")),
        }
    }

    /// Delete a data set (`DeleteNamedVariableList`).
    ///
    /// A server that finds the list but will not let this client delete it answers
    /// "matched 1, deleted 0", which is reported as an error rather than as success — the
    /// difference between "gone" and "refused" is the whole answer.
    pub fn delete_data_set(&mut self, name: &str) -> Result<()> {
        let (ld, item) = split_data_set(name)?;
        let pdu = self.call(&ConfirmedRequest::DeleteNamedVariableList {
            scope: delete_scope::SPECIFIC,
            names: vec![ObjectName::DomainSpecific { domain: &ld, item: &item }],
            domain: None,
        })?;
        match Mms::parse(&pdu, &self.limits)? {
            Mms::ConfirmedResponse { service: ConfirmedResponse::DeleteNamedVariableList { deleted: 1, .. }, .. } => Ok(()),
            Mms::ConfirmedResponse { service: ConfirmedResponse::DeleteNamedVariableList { matched: 0, .. }, .. } => Err(Error::NotFound("data set")),
            Mms::ConfirmedResponse { service: ConfirmedResponse::DeleteNamedVariableList { .. }, .. } => {
                // 3 is object-access-denied.
                Err(Error::DataAccess(3))
            }
            _ => Err(Error::InvalidValue("not a DeleteNamedVariableList response")),
        }
    }

    /// The next unsolicited PDU, waiting up to `timeout` for one to arrive.
    ///
    /// Anything that arrived while another request was in flight is handed back first, in
    /// order, without touching the socket.
    pub fn next_unsolicited(&mut self, timeout: Duration) -> Result<Option<Unsolicited>> {
        self.take_unsolicited(timeout, |_| true)
    }

    /// The next **report**, waiting up to `timeout`.
    ///
    /// Command terminations and anything else stay queued for [`Client::next_unsolicited`]:
    /// a client waiting for a report must not silently drop the answer to a control it
    /// issued a moment ago.
    pub fn next_report(&mut self, timeout: Duration) -> Result<Option<Report>> {
        Ok(self.take_unsolicited(timeout, |u| matches!(u, Unsolicited::Report(_)))?.and_then(|u| match u {
            Unsolicited::Report(r) => Some(*r),
            _ => None,
        }))
    }

    /// The next **command termination**, waiting up to `timeout`. Reports stay queued.
    pub fn next_termination(&mut self, timeout: Duration) -> Result<Option<CommandTermination>> {
        self.take_termination(timeout, None)
    }

    /// The command termination for one `ctlNum`, waiting up to `timeout`.
    ///
    /// A client with two commands in flight gets two terminations, and the only thing tying
    /// each to its command is the sequence number both carry — so taking "the next one" would
    /// hand the second command's answer to the first. Terminations for other commands, and
    /// every report, stay queued.
    pub fn next_termination_for(&mut self, ctl_num: u8, timeout: Duration) -> Result<Option<CommandTermination>> {
        self.take_termination(timeout, Some(ctl_num))
    }

    fn take_termination(&mut self, timeout: Duration, ctl_num: Option<u8>) -> Result<Option<CommandTermination>> {
        let wanted = move |u: &Unsolicited| match u {
            Unsolicited::CommandTermination(t) => ctl_num.is_none_or(|n| t.ctl_num() == n),
            _ => false,
        };
        Ok(self.take_unsolicited(timeout, wanted)?.and_then(|u| match u {
            Unsolicited::CommandTermination(t) => Some(*t),
            _ => None,
        }))
    }

    /// Unsolicited PDUs collected so far and not yet taken.
    pub fn buffered_unsolicited(&self) -> usize {
        self.unsolicited.len()
    }

    /// Take the first queued item `wanted` accepts, reading from the socket until `timeout`
    /// if none is there. Everything it rejects stays in the queue, in order.
    fn take_unsolicited(&mut self, timeout: Duration, wanted: impl Fn(&Unsolicited) -> bool) -> Result<Option<Unsolicited>> {
        let deadline = StdInstant::now() + timeout;
        loop {
            if let Some(i) = self.unsolicited.iter().position(&wanted) {
                return Ok(self.unsolicited.remove(i));
            }
            if StdInstant::now() >= deadline || !self.assoc.is_established() {
                return Ok(None);
            }
            self.read_once(deadline.saturating_duration_since(StdInstant::now()))?;
            self.drain_events()?;
        }
    }

    /// Release the MMS association and drop its stream or borrow.
    pub fn release(&mut self) -> Result<()> {
        let result = self.release_association();
        self.stream.take();
        result
    }

    fn release_association(&mut self) -> Result<()> {
        if self.assoc.is_established() {
            let now = self.now();
            self.assoc.release(now)?;
            self.flush()?;
            // The peer's confirmation is worth a short wait and nothing more: the association
            // is over either way, and a server that never answers must not hang a tool.
            let _ = self.pump_while(|a| !matches!(a.state(), crate::proto::mms::association::State::Closed), Duration::from_secs(2));
        }
        Ok(())
    }

    // ---- plumbing ------------------------------------------------------------------

    fn name_list(&mut self, class: i64, scope: ObjectScope<'_>) -> Result<Vec<String>> {
        let mut out: Vec<String> = Vec::new();
        loop {
            let after = out.last().cloned();
            let pdu = self.call(&ConfirmedRequest::GetNameList { object_class: class, scope, continue_after: after.as_deref() })?;
            let Mms::ConfirmedResponse { service: ConfirmedResponse::GetNameList { identifiers, more_follows }, .. } = Mms::parse(&pdu, &self.limits)? else {
                return Err(Error::InvalidValue("not a GetNameList response"));
            };
            let empty = identifiers.is_empty();
            out.extend(identifiers.iter().map(|s| String::from(*s)));
            // A server that says `moreFollows` and then sends nothing would loop forever;
            // an empty continuation is the end whatever the flag claims.
            if !more_follows || empty {
                return Ok(out);
            }
            if out.len() > self.limits.max_dataset_members * 64 {
                return Err(Error::LimitExceeded { limit: "GetNameList continuations", value: out.len() });
            }
        }
    }

    fn read_access(&mut self, access: &VariableAccess<'_>) -> Result<Vec<Value>> {
        self.read_access_results(access)?.into_iter().collect()
    }

    fn read_access_results(&mut self, access: &VariableAccess<'_>) -> Result<Vec<Result<Value>>> {
        let pdu = self.call(&ConfirmedRequest::Read { specification_with_result: false, access: access.clone() })?;
        let Mms::ConfirmedResponse { service: ConfirmedResponse::Read { results, .. }, .. } = Mms::parse(&pdu, &self.limits)? else {
            return Err(Error::InvalidValue("not a Read response"));
        };
        if let VariableAccess::ListOfVariable(items) = access
            && items.len() != results.len()
        {
            return Err(Error::InvalidValue("server returned the wrong number of Read results"));
        }
        Ok(results
            .iter()
            .map(|r| match r {
                AccessResult::Failure(code) => Err(Error::DataAccess(*code)),
                AccessResult::Success(t) => DataView::from_tlv(*t)?.to_owned(&self.limits),
            })
            .collect())
    }

    /// Write several references in one `Write`, keeping the per-value failures.
    ///
    /// Every reference must be in **MMS form** and carry its own functional constraint. The
    /// callers are the control-block and setting-group helpers, which build the names
    /// themselves, so there is no caller-supplied `fc` to fall back on — and a default would
    /// be silently wrong now that the constraint decides whether a write is allowed at all:
    /// a dotted reference defaulted to `ST` is a write a conforming server refuses.
    pub(crate) fn write_many(&mut self, writes: &[(String, Value)]) -> Result<Vec<Result<()>>> {
        let mut encoded = Vec::with_capacity(writes.len());
        let mut items = Vec::with_capacity(writes.len());
        for (reference, value) in writes {
            let fc = ObjectReference::parse(reference)?.fc.ok_or(Error::InvalidReference("a write needs a functional constraint"))?;
            items.push(Addressed::of(reference, fc)?);
            encoded.push(Value::encode_all(core::slice::from_ref(value))?);
        }
        let access = VariableAccess::ListOfVariable(items.iter().map(Addressed::spec).collect());
        let mut elements = Vec::with_capacity(encoded.len());
        for bytes in &encoded {
            elements.push(crate::ber::Cursor::new(bytes).next_required()?);
        }
        let pdu = self.call(&ConfirmedRequest::Write { access, values: elements })?;
        let Mms::ConfirmedResponse { service: ConfirmedResponse::Write(results), .. } = Mms::parse(&pdu, &self.limits)? else {
            return Err(Error::InvalidValue("not a Write response"));
        };
        Ok(results
            .iter()
            .map(|r| match r {
                crate::proto::mms::WriteResult::Success => Ok(()),
                crate::proto::mms::WriteResult::Failure(code) => Err(Error::DataAccess(*code)),
            })
            .collect())
    }

    /// The next `ctlNum` for a control sequence: 0–255, wrapping.
    pub(crate) fn next_ctl_num(&mut self) -> u8 {
        self.ctl_num = self.ctl_num.wrapping_add(1);
        self.ctl_num
    }

    /// The request timeout this client was configured with.
    pub(crate) const fn timeout(&self) -> Duration {
        self.request_timeout
    }

    /// Issue a confirmed request and block until its answer arrives.
    fn call(&mut self, service: &ConfirmedRequest<'_>) -> Result<Vec<u8>> {
        if !self.assoc.is_established() {
            return Err(Error::Io(String::from("association is not established")));
        }
        let now = self.now();
        let invoke_id = self.assoc.call(now, service)?;
        self.flush()?;
        let mut deadline = StdInstant::now() + self.request_timeout;
        loop {
            if let Some(pdu) = self.take_answer(invoke_id)? {
                return Ok(pdu);
            }
            // The server served from this end since the last look: it is working on the
            // request, so the wait starts again rather than running out mid-transfer.
            if let Some(at) = self.progress.take() {
                deadline = at + self.request_timeout;
            }
            if StdInstant::now() >= deadline {
                return Err(Error::Io(String::from("request timed out")));
            }
            self.read_once(deadline.saturating_duration_since(StdInstant::now()))?;
        }
    }

    /// Drain events, keeping reports and returning the answer to `invoke_id` if it came.
    fn take_answer(&mut self, invoke_id: i64) -> Result<Option<Vec<u8>>> {
        let mut answer = None;
        while let Some(event) = self.assoc.poll_event() {
            match event {
                AssociationEvent::Response { invoke_id: id, pdu } if id == invoke_id => {
                    // A confirmed error is an answer too, and a more useful one than silence.
                    if let Mms::ConfirmedError { error, .. } = Mms::parse(&pdu, &self.limits)? {
                        let e = ServiceError::parse(&error)?;
                        return Err(Error::Service { class: e.class, code: e.code });
                    }
                    answer = Some(pdu);
                }
                AssociationEvent::Timeout { invoke_id: id } if id == invoke_id => {
                    return Err(Error::Io(String::from("request timed out")));
                }
                // A reject *is* the answer: the server will send nothing else, so failing
                // now with the reason it gave beats waiting out the request timeout and
                // reporting silence.
                AssociationEvent::Rejected { invoke_id: Some(id), reject } if id == invoke_id => return Err(rejected(&reject)),
                // One that names no request cannot be attributed, but it is still the peer
                // telling us it could not read what we sent — and it will not answer.
                AssociationEvent::Rejected { invoke_id: None, reject } => return Err(rejected(&reject)),
                // The peer withdrew the request this call is waiting on. Nothing else is
                // coming, so the call fails now rather than waiting out the request timeout.
                AssociationEvent::Cancelled { invoke_id: id } if id == invoke_id => {
                    return Err(Error::Io(String::from("the peer cancelled the request")));
                }
                AssociationEvent::Unconfirmed { pdu } => self.keep_unsolicited(&pdu),
                // The server asking this end for something: answered, never ignored, or it
                // waits out its timeout. Outside a `set_file` every request is refused.
                AssociationEvent::Request { invoke_id: id, pdu } => {
                    self.answer_peer_request(id, &pdu)?;
                    if self.serving.is_some() {
                        let now = self.now();
                        self.assoc.extend_deadline(invoke_id, now);
                    }
                }
                // An answer that did not decode is still the end of this call. Failing with
                // the decode error names what actually happened; waiting for the request
                // timeout reports "the server did not reply" about a server that did.
                AssociationEvent::Malformed { invoke_id: Some(id), error } if id == invoke_id => return Err(error),
                AssociationEvent::Refused { layer, code } => {
                    return Err(Error::Io(format!("association refused at {layer}: {code:?}")));
                }
                AssociationEvent::Closed(reason) => return Err(closed(reason)),
                // Another request's answer, timeout or reject, a request from the peer (this
                // end is a client and serves none), an established event, an undecodable PDU:
                // none of them answer *this* request, and none of them end the association.
                AssociationEvent::Response { .. }
                | AssociationEvent::Timeout { .. }
                | AssociationEvent::Rejected { .. }
                | AssociationEvent::Malformed { .. }
                // A blocking client cancels nothing — every call here is answered before the
                // caller gets control back — so a cancel either way concerns a request no
                // call is waiting on. The association has already released or kept the slot.
                | AssociationEvent::Cancelled { .. }
                | AssociationEvent::CancelRefused { .. }
                | AssociationEvent::Established(_) => {}
            }
        }
        self.flush()?;
        Ok(answer)
    }

    /// Counters for the segmented reports this client has had to join.
    pub const fn report_assembler_stats(&self) -> AssemblerStats {
        self.assembler.stats()
    }

    /// Classify an unconfirmed PDU and queue it.
    ///
    /// A segmented report is held until its last segment arrives; the application is handed
    /// the whole report or nothing, never a report with a hole in it.
    fn keep_unsolicited(&mut self, pdu: &[u8]) {
        let Some(item) = Unsolicited::from_pdu(pdu, &self.limits) else { return };
        let item = match item {
            Unsolicited::Report(r) => match self.assembler.push(*r) {
                Some(whole) => Unsolicited::Report(Box::new(whole)),
                None => return,
            },
            other => other,
        };
        // The queue is bounded for the same reason the cores' event queues are: a client
        // that stops draining must not grow memory without limit.
        if self.unsolicited.len() >= 256 {
            self.unsolicited.pop_front();
        }
        self.unsolicited.push_back(item);
    }

    fn drain_events(&mut self) -> Result<()> {
        while let Some(event) = self.assoc.poll_event() {
            // Every variant is named rather than caught by a wildcard. A `_ => {}` here is
            // how `Rejected` was silently absorbed when it was added: the compiler cannot
            // ask about a variant a wildcard already answers for.
            match event {
                AssociationEvent::Unconfirmed { pdu } => self.keep_unsolicited(&pdu),
                AssociationEvent::Request { invoke_id, pdu } => self.answer_peer_request(invoke_id, &pdu)?,
                AssociationEvent::Closed(reason) => return Err(closed(reason)),
                AssociationEvent::Refused { layer, code } => return Err(Error::Io(format!("association refused at {layer}: {code:?}"))),
                // A reject arriving outside a call answers a request that already timed out,
                // or is the peer objecting to something we sent and are no longer waiting on.
                // The association has released the invoke and counted it in
                // `AssociationStats::rejected`; there is no call left to fail.
                AssociationEvent::Rejected { .. }
                // An answer or a timeout for a request nobody is waiting on any more, the
                // establishment event, and a PDU that did not decode — one bad report is not a
                // reason to drop a connection, and `AssociationStats::malformed` counts it.
                | AssociationEvent::Response { .. }
                | AssociationEvent::Timeout { .. }
                | AssociationEvent::Malformed { .. }
                // A blocking client cancels nothing — every call here is answered before the
                // caller gets control back — so a cancel either way concerns a request no
                // call is waiting on. The association has already released or kept the slot.
                | AssociationEvent::Cancelled { .. }
                | AssociationEvent::CancelRefused { .. }
                | AssociationEvent::Established(_) => {}
            }
        }
        self.flush()
    }

    /// Read once and feed the association; `Ok(())` even when nothing arrived in time.
    fn read_once(&mut self, timeout: Duration) -> Result<()> {
        let timeout = timeout.max(Duration::from_millis(1));
        let stream = self.stream.as_mut().ok_or(Error::InvalidValue("association released"))?;
        (self.set_read_timeout)(stream, timeout).map_err(|e| Error::Io(e.to_string()))?;
        match stream.read(&mut self.rx) {
            Ok(0) => {
                self.assoc.abort();
                Err(Error::Io(String::from("the peer closed the connection")))
            }
            Ok(n) => {
                let now = self.now();
                // The association borrows the slice, and it also lives in `self`, so the
                // buffer is moved out for the call and put back afterwards. That is what
                // keeps a busy association from allocating one buffer per socket read.
                let buf = core::mem::take(&mut self.rx);
                self.assoc.on_bytes(now, buf.get(..n).unwrap_or(&[]));
                self.rx = buf;
                Ok(())
            }
            Err(e) if matches!(e.kind(), std::io::ErrorKind::Interrupted | std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => {
                let now = self.now();
                self.assoc.on_timeout(now);
                Ok(())
            }
            Err(e) => Err(Error::Io(e.to_string())),
        }
    }

    /// Read and feed until `keep_going` says stop, or the deadline passes.
    fn pump_while(&mut self, keep_going: impl Fn(&Association) -> bool, timeout: Duration) -> Result<()> {
        let deadline = StdInstant::now() + timeout;
        while keep_going(&self.assoc) {
            if StdInstant::now() >= deadline {
                return Err(Error::Io(String::from("timed out waiting for the peer")));
            }
            self.read_once(deadline.saturating_duration_since(StdInstant::now()))?;
            self.drain_events()?;
        }
        Ok(())
    }

    fn flush(&mut self) -> Result<()> {
        let stream = self.stream.as_mut().ok_or(Error::InvalidValue("association released"))?;
        while let Some(packet) = self.assoc.poll_transmit() {
            stream.write_all(packet).map_err(|e| Error::Io(e.to_string()))?;
        }
        stream.flush().map_err(|e| Error::Io(e.to_string()))
    }

    /// The association's notion of now, on a monotonic clock this client owns.
    fn now(&self) -> Instant {
        Instant(self.epoch.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64)
    }
}

/// An `ObjectName` as the reference a human reads.
fn object_name(name: &ObjectName<'_>) -> String {
    match name {
        ObjectName::DomainSpecific { domain, item } => format!("{domain}/{item}"),
        ObjectName::VmdSpecific(n) | ObjectName::AaSpecific(n) => String::from(*n),
    }
}

/// One reference, resolved into what a `Read` or a `Write` has to carry for it.
///
/// A reference is a name and, sometimes, a part of it: `MHAI1.HA.phsAHar(2).cVal.mag.f` names
/// the variable `MHAI1$MX$HA$phsAHar` and selects one element and three components inside it.
/// Every service that takes references goes through here, so a caller cannot ask for an array
/// element in one place and read the whole array in another.
struct Addressed<'r> {
    domain: String,
    item: String,
    access: AlternateAccess<'r>,
}

impl<'r> Addressed<'r> {
    fn of(reference: &'r str, fc: Fc) -> Result<Addressed<'r>> {
        let parsed = ObjectReference::parse(reference)?;
        let (domain, item) = parsed.to_mms(fc);
        Ok(Addressed { domain: String::from(domain), item, access: AlternateAccess::new(parsed.selection()) })
    }

    fn all(references: &[(&'r str, Fc)]) -> Result<Vec<Addressed<'r>>> {
        references.iter().map(|(reference, fc)| Addressed::of(reference, *fc)).collect()
    }

    fn spec(&self) -> VariableSpecification<'_> {
        VariableSpecification::of(ObjectName::DomainSpecific { domain: &self.domain, item: &self.item }, self.access.clone())
    }
}

fn specification_name(spec: &VariableSpecification<'_>) -> String {
    spec.name().map(object_name).unwrap_or_default()
}

/// Recognise a `CommandTermination` (IEC 61850-8-1 §20.9).
///
/// Positive: one variable, the control object's `$Oper`, with the `Oper` value the client
/// sent. Negative: `LastApplError` first — VMD-specific, with no domain — then the `$Oper`.
fn termination(names: &[VariableSpecification<'_>], values: &[Value]) -> Option<CommandTermination> {
    let named: Vec<String> = names.iter().map(specification_name).collect();
    let is_oper = |n: &String| n.ends_with("$Oper") || n.ends_with("$SBOw") || n.ends_with("$Cancel");
    match (named.as_slice(), values) {
        ([first], [oper]) if is_oper(first) => {
            Some(CommandTermination::Positive { control_object: first.clone(), request: ControlRequest::from_value(oper).ok()? })
        }
        ([first, second], [err, oper]) if first == "LastApplError" && is_oper(second) => {
            Some(CommandTermination::Negative { error: LastApplError::from_value(err).ok()?, request: ControlRequest::from_value(oper).ok() })
        }
        ([only], [err]) if only == "LastApplError" => Some(CommandTermination::Negative { error: LastApplError::from_value(err).ok()?, request: None }),
        _ => None,
    }
}

/// Split `LD/LLN0$dsName` into the MMS domain and item a data set is named by.
fn split_data_set(name: &str) -> Result<(String, String)> {
    let (ld, rest) = name.split_once('/').ok_or(Error::InvalidReference("a data set is `LD/LN$dsName`"))?;
    if ld.is_empty() || rest.is_empty() {
        return Err(Error::InvalidReference("a data set is `LD/LN$dsName`"));
    }
    Ok((String::from(ld), rest.replace('.', "$")))
}

fn alloc_buffer() -> Vec<u8> {
    vec![0u8; 8192]
}

/// Append the MMS port when `addr` does not already carry one.
///
/// A bare IPv6 literal is full of colons, so "contains a colon" is not the question — the
/// question is whether the text ends in `:<port>`, which for an IPv6 literal means it is
/// bracketed. `Client::connect("::1")` has to reach port 102, not fail to resolve.
fn with_default_port(addr: &str) -> String {
    let has_port = match addr.rfind(']') {
        // `[::1]:102` has a port; `[::1]` does not.
        Some(bracket) => addr.get(bracket + 1..).is_some_and(|rest| rest.starts_with(':')),
        None => addr.matches(':').count() == 1,
    };
    if has_port {
        String::from(addr)
    } else if addr.contains(':') && !addr.starts_with('[') {
        // A bare IPv6 literal has to be bracketed before a port can be appended to it.
        format!("[{addr}]:{PORT}")
    } else {
        format!("{addr}:{PORT}")
    }
}

/// `0` means "no request timeout" to the association; a blocking client still needs a
/// ceiling, or a server that never answers blocks the caller for ever.
fn request_timeout(cfg: &AssociationConfig) -> Duration {
    Duration::from_millis(if cfg.request_timeout_ms == 0 { 30_000 } else { cfg.request_timeout_ms })
}

/// The reject as the error a caller sees.
///
/// The named reason lives in `proto::mms::reject`; the error carries the wire numbers,
/// because `common::Error` is built by every feature and cannot name an MMS type.
fn rejected(reject: &crate::proto::mms::reject::Reject) -> Error {
    let (invoke_id, reason_tag, code) = reject.to_error_parts();
    Error::Rejected { invoke_id, reason_tag, code }
}

fn closed(reason: CloseReason) -> Error {
    Error::Io(match reason {
        CloseReason::Released | CloseReason::PeerReleased => String::from("the association was released"),
        CloseReason::Aborted => String::from("the association was aborted"),
        CloseReason::ConnectTimeout => String::from("the association handshake timed out"),
        CloseReason::Refused => String::from("the peer refused the association"),
        CloseReason::ProtocolError => String::from("the peer sent something that is not the protocol"),
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_host_without_a_port_gets_102() {
        // Nothing is listening, so the connect fails — but on the address it built, which is
        // what this checks: the error names port 102 rather than a parse failure.
        let e = Client::connect("127.0.0.1").unwrap_err();
        assert!(matches!(e, Error::Io(_)), "{e:?}");
    }

    #[test]
    fn a_host_without_a_port_gets_one_whatever_family_it_is() {
        assert_eq!(with_default_port("10.0.0.5"), "10.0.0.5:102");
        assert_eq!(with_default_port("10.0.0.5:3782"), "10.0.0.5:3782");
        assert_eq!(with_default_port("ied1.substation.local"), "ied1.substation.local:102");
        // An IPv6 literal is full of colons; "contains a colon" is not "carries a port".
        assert_eq!(with_default_port("::1"), "[::1]:102");
        assert_eq!(with_default_port("fe80::1"), "[fe80::1]:102");
        assert_eq!(with_default_port("[::1]"), "[::1]:102");
        assert_eq!(with_default_port("[::1]:102"), "[::1]:102");
    }

    #[test]
    fn a_data_set_name_splits_into_the_domain_and_the_list() {
        assert_eq!(split_data_set("IED1LD0/LLN0$dsTrip").unwrap(), (String::from("IED1LD0"), String::from("LLN0$dsTrip")));
        assert_eq!(split_data_set("IED1LD0/LLN0.dsTrip").unwrap(), (String::from("IED1LD0"), String::from("LLN0$dsTrip")));
        assert!(split_data_set("dsTrip").is_err());
    }

    #[test]
    fn a_closed_reason_becomes_an_error_a_human_can_read() {
        assert_eq!(closed(CloseReason::Refused), Error::Io(String::from("the peer refused the association")));
    }
}