pnio 0.1.0

PROFINET RT IO-Device stack in pure Rust (community, not affiliated with PI)
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
//! RTA-PDU codec: the alarm transport (RTA) frame carried over Ethernet `0x8892`
//! (FrameID `0xFC01` High priority / `0xFE01` Low priority), and the two PNIO
//! blocks it carries in its DATA variant — AlarmNotification and AlarmAck.
//! Byte-exact against the p-net goldens in `testdata/alarm/`
//! (see `docs/alarm-golden-frames.md` for the wire reference).

use crate::cm::block::{BlockHeader, Cursor};
use crate::cm::{BlockError, PnioStatus};
use crate::eth::{EthError, EthHeader, MacAddr, ETHERTYPE_PROFINET};
use thiserror::Error;

// ---------------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------------

/// FrameID for the High priority alarm channel.
pub const FRAME_ID_HIGH: u16 = 0xFC01;
/// FrameID for the Low priority alarm channel.
pub const FRAME_ID_LOW: u16 = 0xFE01;
/// VLAN TCI (priority 6) for the High priority alarm channel.
pub const TCI_HIGH: u16 = 0xC000;
/// VLAN TCI (priority 5) for the Low priority alarm channel.
pub const TCI_LOW: u16 = 0xA000;
/// `SendSeqNum`/`AckSeqNum` value before any DATA has been sent/accepted on a fresh AR.
pub const SEQ_INIT: u16 = 0xFFFF;
/// `AckSeqNum` value before any DATA has been accepted from the peer.
pub const SEQ_NONE: u16 = 0xFFFE;
/// USI for a `ChannelDiagnosis` payload (6 bytes).
pub const USI_CHANNEL_DIAG: u16 = 0x8000;
/// USI for an `ExtChannelDiagnosis` payload (12 bytes).
pub const USI_EXT_CHANNEL_DIAG: u16 = 0x8002;

// ---------------------------------------------------------------------------------
// Priority / PduType / RtaHeader
// ---------------------------------------------------------------------------------

/// Which of the two alarm channels (VLAN priority / FrameID) a PDU travels on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Priority {
    /// FrameID `0xFC01`, VLAN priority 6, TCI `0xC000`.
    High,
    /// FrameID `0xFE01`, VLAN priority 5, TCI `0xA000`. ERR-RTA is always sent here,
    /// regardless of which channel the aborted exchange used.
    Low,
}

impl Priority {
    /// This channel's alarm FrameID: [`FRAME_ID_HIGH`] or [`FRAME_ID_LOW`].
    pub fn frame_id(self) -> u16 {
        match self {
            Priority::High => FRAME_ID_HIGH,
            Priority::Low => FRAME_ID_LOW,
        }
    }

    /// This channel's VLAN TCI: [`TCI_HIGH`] or [`TCI_LOW`].
    pub fn tci(self) -> u16 {
        match self {
            Priority::High => TCI_HIGH,
            Priority::Low => TCI_LOW,
        }
    }
}

/// RTA-PDU `PDUType` (low nibble of the type/version byte).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PduType {
    /// Carries one PNIO block (`AlarmNotification` or `AlarmAck`); `VarPartLen` is the block's length.
    Data = 1,
    /// Negative acknowledgement of the last DATA received; empty `VarPartLen`.
    Nack = 2,
    /// Transport-level acknowledgement of the last DATA received; empty `VarPartLen`.
    Ack = 3,
    /// Aborts the alarm exchange; `VarPartLen` 4, carrying a [`PnioStatus`].
    Err = 4,
}

/// The 12-byte RTA-PDU header that follows the alarm FrameID.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RtaHeader {
    /// `AlarmDstEndpoint`: the peer's `LocalAlarmReference` (the CPU sends `0x0000`).
    pub dst_ref: u16,
    /// `AlarmSrcEndpoint`: our `LocalAlarmReference` (we answer `0x0000`).
    pub src_ref: u16,
    /// `PDUType`, low nibble of byte 4; the high nibble is always the RTA-PDU version (1).
    pub pdu_type: PduType,
    /// `AddFlags` bit 4: transport ack requested (1 on DATA, 0 on ACK/ERR).
    pub tack: bool,
    /// `SendSeqNum`: this side's DATA sequence counter — [`SEQ_INIT`] before any DATA has
    /// been sent, then `0x0000, 0x0001, …`, wrapping after `0x7FFF`.
    pub send_seq: u16,
    /// `AckSeqNum`: the last DATA sequence accepted from the peer — [`SEQ_NONE`] before any
    /// DATA has been accepted.
    pub ack_seq: u16,
}

impl RtaHeader {
    /// Fixed on-wire length of the RTA-PDU header, in bytes.
    pub const LEN: usize = 12;

    /// Parses the 12-byte header; returns `(header, var_part_len)`.
    pub fn parse(buf: &[u8]) -> Result<(RtaHeader, u16), RtaError> {
        if buf.len() < Self::LEN {
            return Err(RtaError::TooShort);
        }
        let u16at = |o: usize| u16::from_be_bytes([buf[o], buf[o + 1]]);
        let (version, ty) = (buf[4] >> 4, buf[4] & 0x0F);
        if version != 1 {
            return Err(RtaError::BadVersion(version));
        }
        let pdu_type = match ty {
            1 => PduType::Data,
            2 => PduType::Nack,
            3 => PduType::Ack,
            4 => PduType::Err,
            t => return Err(RtaError::BadPduType(t)),
        };
        Ok((
            RtaHeader {
                dst_ref: u16at(0),
                src_ref: u16at(2),
                pdu_type,
                tack: buf[5] & 0x10 != 0,
                send_seq: u16at(6),
                ack_seq: u16at(8),
            },
            u16at(10),
        ))
    }

    /// Serializes the header (`var_part_len` is the length of what follows).
    pub fn write(&self, out: &mut Vec<u8>, var_part_len: u16) {
        out.extend_from_slice(&self.dst_ref.to_be_bytes());
        out.extend_from_slice(&self.src_ref.to_be_bytes());
        out.push(0x10 | self.pdu_type as u8);
        out.push(0x01 | if self.tack { 0x10 } else { 0 }); // window size 1
        out.extend_from_slice(&self.send_seq.to_be_bytes());
        out.extend_from_slice(&self.ack_seq.to_be_bytes());
        out.extend_from_slice(&var_part_len.to_be_bytes());
    }
}

// ---------------------------------------------------------------------------------
// AlarmType
// ---------------------------------------------------------------------------------

/// `AlarmType` field of an AlarmNotification/AlarmAck.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlarmType {
    /// `AlarmType` 0x0001 — a channel or extended-channel diagnosis appeared.
    Diagnosis,
    /// `AlarmType` 0x0002 — a manufacturer-specific process alarm.
    Process,
    /// `AlarmType` 0x0003 — a submodule was pulled.
    Pull,
    /// `AlarmType` 0x0004 — a submodule was plugged.
    Plug,
    /// `AlarmType` 0x0005 — device status changed.
    Status,
    /// `AlarmType` 0x0006 — a submodule's identification changed.
    Update,
    /// `AlarmType` 0x0007 — redundancy state changed.
    Redundancy,
    /// `AlarmType` 0x0008 — the AR is now controlled by a supervisor.
    ControlledBySupervisor,
    /// `AlarmType` 0x0009 — the AR was released.
    Released,
    /// `AlarmType` 0x000A — the wrong submodule was plugged into a slot.
    PlugWrongSubmodule,
    /// `AlarmType` 0x000B — a previously missing submodule returned.
    ReturnOfSubmodule,
    /// `AlarmType` 0x000C — a channel or extended-channel diagnosis cleared.
    DiagnosisDisappears,
    /// Any `AlarmType` value not otherwise known, carried verbatim.
    Other(u16),
}

impl AlarmType {
    /// Decodes an `AlarmType` field; an unrecognized value becomes [`AlarmType::Other`].
    pub fn from_u16(v: u16) -> Self {
        match v {
            0x0001 => AlarmType::Diagnosis,
            0x0002 => AlarmType::Process,
            0x0003 => AlarmType::Pull,
            0x0004 => AlarmType::Plug,
            0x0005 => AlarmType::Status,
            0x0006 => AlarmType::Update,
            0x0007 => AlarmType::Redundancy,
            0x0008 => AlarmType::ControlledBySupervisor,
            0x0009 => AlarmType::Released,
            0x000A => AlarmType::PlugWrongSubmodule,
            0x000B => AlarmType::ReturnOfSubmodule,
            0x000C => AlarmType::DiagnosisDisappears,
            other => AlarmType::Other(other),
        }
    }

    /// Inverse of [`AlarmType::from_u16`].
    pub fn to_u16(self) -> u16 {
        match self {
            AlarmType::Diagnosis => 0x0001,
            AlarmType::Process => 0x0002,
            AlarmType::Pull => 0x0003,
            AlarmType::Plug => 0x0004,
            AlarmType::Status => 0x0005,
            AlarmType::Update => 0x0006,
            AlarmType::Redundancy => 0x0007,
            AlarmType::ControlledBySupervisor => 0x0008,
            AlarmType::Released => 0x0009,
            AlarmType::PlugWrongSubmodule => 0x000A,
            AlarmType::ReturnOfSubmodule => 0x000B,
            AlarmType::DiagnosisDisappears => 0x000C,
            AlarmType::Other(v) => v,
        }
    }
}

// ---------------------------------------------------------------------------------
// AlarmSpecifier
// ---------------------------------------------------------------------------------

/// `AlarmSpecifier` field: per-AR sequence number plus diagnosis-state flags.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct AlarmSpecifier {
    /// Bits 0-10: per-AR sequence number, starting at 0 and wrapping at `0x7FF`.
    pub sequence: u16,
    /// Bit 11: a channel diagnosis exists on this submodule after this alarm.
    pub channel_diag: bool,
    /// Bit 12: a manufacturer-specific diagnosis exists on this submodule after this alarm.
    pub manufacturer_diag: bool,
    /// Bit 13: any diagnosis exists on this submodule after this alarm.
    pub submodule_diag: bool,
    /// Bit 15: any diagnosis exists anywhere on the AR after this alarm.
    pub ar_diag: bool,
}

impl AlarmSpecifier {
    /// Decodes an `AlarmSpecifier` u16 field.
    pub fn from_u16(raw: u16) -> Self {
        AlarmSpecifier {
            sequence: raw & 0x07FF,
            channel_diag: raw & 0x0800 != 0,
            manufacturer_diag: raw & 0x1000 != 0,
            submodule_diag: raw & 0x2000 != 0,
            ar_diag: raw & 0x8000 != 0,
        }
    }

    /// Inverse of [`AlarmSpecifier::from_u16`].
    pub fn to_u16(self) -> u16 {
        (self.sequence & 0x07FF)
            | (self.channel_diag as u16) << 11
            | (self.manufacturer_diag as u16) << 12
            | (self.submodule_diag as u16) << 13
            | (self.ar_diag as u16) << 15
    }
}

// ---------------------------------------------------------------------------------
// ChannelProperties / ChannelDiagnosis / ExtChannelDiagnosis
// ---------------------------------------------------------------------------------

/// `ChannelProperties.Maintenance` (bits 9-10).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Maintenance {
    /// `Maintenance` 00 — a fault: the channel is not usable.
    Fault = 0,
    /// `Maintenance` 01 — maintenance is required soon.
    Required = 1,
    /// `Maintenance` 10 — maintenance is demanded now.
    Demanded = 2,
    /// `Maintenance` 11 — reserved/qualified (not produced by this crate; seen on the wire as a placeholder value).
    Qualified = 3,
}

/// `ChannelProperties.Specifier` (bits 11-12).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Specifier {
    /// `Specifier` 00 — every diagnosis on this channel disappears (p-net's encoding of a
    /// standard-diagnosis removal, e.g. `properties 0x2001` on the bench).
    AllDisappear = 0,
    /// `Specifier` 01 — this diagnosis appears.
    Appears = 1,
    /// `Specifier` 10 — this diagnosis disappears and it was the last one on the channel.
    Disappears = 2,
    /// `Specifier` 11 — this diagnosis disappears but other diagnoses remain on the channel.
    DisappearsOthersRemain = 3,
}

/// `ChannelProperties` u16 bitfield carried by `ChannelDiagnosis`/`ExtChannelDiagnosis`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChannelProperties {
    /// Bits 0-7: manufacturer-specific channel type (this crate always sends 0 = unspecified).
    pub type_: u8,
    /// Bit 8: whether this is an accumulative (summary) diagnosis.
    pub accumulative: bool,
    /// Bits 9-10: severity; see [`Maintenance`].
    pub maintenance: Maintenance,
    /// Bits 11-12: appears/disappears state; see [`Specifier`].
    pub specifier: Specifier,
    /// Bits 13-15: `0` manufacturer-specific, `1` input, `2` output, `3` input+output.
    pub direction: u8,
}

impl ChannelProperties {
    /// Decodes a `ChannelProperties` u16 field.
    pub fn from_u16(raw: u16) -> Self {
        let maintenance = match (raw >> 9) & 0x3 {
            0 => Maintenance::Fault,
            1 => Maintenance::Required,
            2 => Maintenance::Demanded,
            _ => Maintenance::Qualified,
        };
        let specifier = match (raw >> 11) & 0x3 {
            0 => Specifier::AllDisappear,
            1 => Specifier::Appears,
            2 => Specifier::Disappears,
            _ => Specifier::DisappearsOthersRemain,
        };
        ChannelProperties {
            type_: (raw & 0x00FF) as u8,
            accumulative: raw & 0x0100 != 0,
            maintenance,
            specifier,
            direction: ((raw >> 13) & 0x7) as u8,
        }
    }

    /// Inverse of [`ChannelProperties::from_u16`].
    pub fn to_u16(self) -> u16 {
        self.type_ as u16
            | (self.accumulative as u16) << 8
            | (self.maintenance as u16) << 9
            | (self.specifier as u16) << 11
            | (self.direction as u16) << 13
    }
}

/// `ChannelDiagnosis` USI `0x8000` payload (6 bytes).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChannelDiagnosis {
    /// `ChannelNumber`; [`crate::diag::WHOLE_SUBMODULE`] (`0x8000`) means the whole submodule.
    pub channel: u16,
    /// `ChannelProperties` bitfield.
    pub properties: ChannelProperties,
    /// `ChannelErrorType`; see [`crate::diag::ChannelError`] for the codes this crate raises.
    pub error_type: u16,
}

impl ChannelDiagnosis {
    fn parse(b: &[u8]) -> Self {
        ChannelDiagnosis {
            channel: u16::from_be_bytes([b[0], b[1]]),
            properties: ChannelProperties::from_u16(u16::from_be_bytes([b[2], b[3]])),
            error_type: u16::from_be_bytes([b[4], b[5]]),
        }
    }

    fn write(&self, out: &mut Vec<u8>) {
        out.extend_from_slice(&self.channel.to_be_bytes());
        out.extend_from_slice(&self.properties.to_u16().to_be_bytes());
        out.extend_from_slice(&self.error_type.to_be_bytes());
    }
}

/// `ExtChannelDiagnosis` USI `0x8002` payload (12 bytes): `ChannelDiagnosis` plus
/// `ExtChannelErrorType` and `ExtChannelAddValue`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExtChannelDiagnosis {
    /// `ChannelNumber`; [`crate::diag::WHOLE_SUBMODULE`] (`0x8000`) means the whole submodule.
    pub channel: u16,
    /// `ChannelProperties` bitfield.
    pub properties: ChannelProperties,
    /// `ChannelErrorType`; see [`crate::diag::ChannelError`] for the codes this crate raises.
    pub error_type: u16,
    /// `ExtChannelErrorType`: manufacturer-specific detail code for `error_type`.
    pub ext_error_type: u16,
    /// `ExtChannelAddValue`: manufacturer-specific additional value for `ext_error_type`.
    pub ext_add_value: u32,
}

impl ExtChannelDiagnosis {
    fn parse(b: &[u8]) -> Self {
        ExtChannelDiagnosis {
            channel: u16::from_be_bytes([b[0], b[1]]),
            properties: ChannelProperties::from_u16(u16::from_be_bytes([b[2], b[3]])),
            error_type: u16::from_be_bytes([b[4], b[5]]),
            ext_error_type: u16::from_be_bytes([b[6], b[7]]),
            ext_add_value: u32::from_be_bytes([b[8], b[9], b[10], b[11]]),
        }
    }

    fn write(&self, out: &mut Vec<u8>) {
        out.extend_from_slice(&self.channel.to_be_bytes());
        out.extend_from_slice(&self.properties.to_u16().to_be_bytes());
        out.extend_from_slice(&self.error_type.to_be_bytes());
        out.extend_from_slice(&self.ext_error_type.to_be_bytes());
        out.extend_from_slice(&self.ext_add_value.to_be_bytes());
    }
}

/// The USI-specific user data carried by an `AlarmNotification`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UserData {
    /// USI [`USI_CHANNEL_DIAG`]: a 6-byte [`ChannelDiagnosis`].
    Channel(ChannelDiagnosis),
    /// USI [`USI_EXT_CHANNEL_DIAG`]: a 12-byte [`ExtChannelDiagnosis`].
    ExtChannel(ExtChannelDiagnosis),
    /// Any other USI, carried verbatim (e.g. process alarm payloads).
    Raw(Vec<u8>),
}

// ---------------------------------------------------------------------------------
// AlarmNotification / AlarmAck
// ---------------------------------------------------------------------------------

/// AlarmNotification block body (BlockType `0x0001` High / `0x0002` Low).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AlarmNotification {
    /// What kind of event this alarm reports.
    pub alarm_type: AlarmType,
    /// Application Process Identifier the alarm applies to (`0` for the device AP).
    pub api: u32,
    /// Slot the alarm applies to.
    pub slot: u16,
    /// Subslot the alarm applies to.
    pub subslot: u16,
    /// The slot's module identity number.
    pub module_ident: u32,
    /// The submodule's identity number.
    pub submodule_ident: u32,
    /// Per-AR sequence number plus diagnosis-state flags.
    pub specifier: AlarmSpecifier,
    /// User Structure Identifier selecting how `data` is interpreted; see [`UserData`].
    pub usi: u16,
    /// USI-specific payload; see [`UserData`].
    pub data: UserData,
}

/// AlarmAck block body (BlockType `0x8001` High / `0x8002` Low).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AlarmAck {
    /// Echoes the acknowledged notification's `alarm_type`.
    pub alarm_type: AlarmType,
    /// Echoes the acknowledged notification's `api`.
    pub api: u32,
    /// Echoes the acknowledged notification's `slot`.
    pub slot: u16,
    /// Echoes the acknowledged notification's `subslot`.
    pub subslot: u16,
    /// Echoes the acknowledged notification's `specifier`.
    pub specifier: AlarmSpecifier,
    /// Result of processing the alarm; `PnioStatus::OK` on success.
    pub status: PnioStatus,
}

/// The parsed content of an RTA DATA PDU's single PNIO block.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RtaData {
    /// BlockType `0x0001`/`0x0002`: an [`AlarmNotification`].
    Notification(AlarmNotification),
    /// BlockType `0x8001`/`0x8002`: an [`AlarmAck`].
    Ack(AlarmAck),
    /// Any other block type, carried verbatim.
    Unknown {
        /// The block's `BlockType`.
        block_type: u16,
        /// The block's body, excluding the block header.
        body: Vec<u8>,
    },
}

/// The RTA-PDU body, keyed by `PduType`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RtaBody {
    /// [`PduType::Data`]: one PNIO block.
    Data(RtaData),
    /// [`PduType::Ack`]: transport-level acknowledgement, no payload.
    Ack,
    /// [`PduType::Nack`]: negative acknowledgement, no payload.
    Nack,
    /// [`PduType::Err`]: the exchange is aborted, with the reason.
    Err(PnioStatus),
}

/// A fully parsed/to-be-built alarm frame: channel, RTA header, and body.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RtaPdu {
    /// Which alarm channel (FrameID/VLAN priority) this PDU travels on.
    pub priority: Priority,
    /// The 12-byte RTA-PDU header.
    pub header: RtaHeader,
    /// The PDU's payload, keyed by `header.pdu_type`.
    pub body: RtaBody,
}

// ---------------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------------

/// Errors from [`parse_frame`].
#[derive(Debug, Error, PartialEq, Eq)]
pub enum RtaError {
    /// The Ethernet header failed to parse; see [`EthError`].
    #[error("ethernet header: {0}")]
    Eth(#[from] EthError),
    /// The frame's ethertype is not PROFINET, or its FrameID is not an alarm channel.
    #[error("not an alarm frame")]
    NotAlarm,
    /// The frame is shorter than the RTA-PDU header, or (for `PduType::Err`) than the
    /// 4-byte `PNIOStatus` its `VarPartLen` promises.
    #[error("frame too short")]
    TooShort,
    /// The RTA-PDU type nibble is not 1 (DATA), 2 (NACK), 3 (ACK) or 4 (ERR).
    #[error("bad RTA PDU type {0:#x}")]
    BadPduType(u8),
    /// The RTA-PDU version nibble is not 1.
    #[error("bad RTA-PDU version {0}")]
    BadVersion(u8),
    /// The DATA PDU's PNIO block failed to parse; see [`BlockError`].
    #[error("block error: {0}")]
    Block(#[from] BlockError),
    /// `VarPartLen` declares more bytes than the frame actually has left.
    #[error("bad var part length: declared {declared}, available {available}")]
    BadVarPartLen {
        /// `VarPartLen` as declared in the RTA-PDU header.
        declared: u16,
        /// Bytes actually remaining in the frame after the header.
        available: usize,
    },
}

// ---------------------------------------------------------------------------------
// parse_frame / build_frame / is_alarm_frame
// ---------------------------------------------------------------------------------

/// Parses a complete Ethernet frame (VLAN-tagged, `0x8892`, alarm FrameID) into an
/// `RtaPdu`.
pub fn parse_frame(frame: &[u8]) -> Result<RtaPdu, RtaError> {
    let (eth, off) = EthHeader::parse(frame)?;
    if eth.ethertype != ETHERTYPE_PROFINET {
        return Err(RtaError::NotAlarm);
    }
    if frame.len() < off + 2 {
        return Err(RtaError::TooShort);
    }
    let frame_id = u16::from_be_bytes([frame[off], frame[off + 1]]);
    let priority = match frame_id {
        FRAME_ID_HIGH => Priority::High,
        FRAME_ID_LOW => Priority::Low,
        _ => return Err(RtaError::NotAlarm),
    };

    let rta_off = off + 2;
    let (header, var_part_len) = RtaHeader::parse(&frame[rta_off..])?;
    let var_off = rta_off + RtaHeader::LEN;
    let available = frame.len() - var_off;
    if var_part_len as usize > available {
        return Err(RtaError::BadVarPartLen {
            declared: var_part_len,
            available,
        });
    }
    let var_part = &frame[var_off..var_off + var_part_len as usize];

    let body = match header.pdu_type {
        PduType::Ack => RtaBody::Ack,
        PduType::Nack => RtaBody::Nack,
        PduType::Err => {
            if var_part.len() < 4 {
                return Err(RtaError::TooShort);
            }
            RtaBody::Err(PnioStatus(u32::from_be_bytes([
                var_part[0],
                var_part[1],
                var_part[2],
                var_part[3],
            ])))
        }
        PduType::Data => {
            let (bh, body_bytes) = BlockHeader::parse(var_part)?;
            RtaBody::Data(parse_rta_data(bh.block_type, body_bytes)?)
        }
    };

    Ok(RtaPdu {
        priority,
        header,
        body,
    })
}

fn parse_rta_data(block_type: u16, body: &[u8]) -> Result<RtaData, RtaError> {
    match block_type {
        0x0001 | 0x0002 => Ok(RtaData::Notification(parse_notification(body)?)),
        0x8001 | 0x8002 => Ok(RtaData::Ack(parse_ack(body)?)),
        other => Ok(RtaData::Unknown {
            block_type: other,
            body: body.to_vec(),
        }),
    }
}

fn parse_notification(body: &[u8]) -> Result<AlarmNotification, RtaError> {
    let mut c = Cursor::new(body);
    let alarm_type = AlarmType::from_u16(c.u16()?);
    let api = c.u32()?;
    let slot = c.u16()?;
    let subslot = c.u16()?;
    let module_ident = c.u32()?;
    let submodule_ident = c.u32()?;
    let specifier = AlarmSpecifier::from_u16(c.u16()?);
    let usi = c.u16()?;
    let n = c.remaining();
    let data_bytes = c.bytes(n)?;
    let data = match usi {
        USI_CHANNEL_DIAG if data_bytes.len() == 6 => {
            UserData::Channel(ChannelDiagnosis::parse(data_bytes))
        }
        USI_EXT_CHANNEL_DIAG if data_bytes.len() == 12 => {
            UserData::ExtChannel(ExtChannelDiagnosis::parse(data_bytes))
        }
        _ => UserData::Raw(data_bytes.to_vec()),
    };
    Ok(AlarmNotification {
        alarm_type,
        api,
        slot,
        subslot,
        module_ident,
        submodule_ident,
        specifier,
        usi,
        data,
    })
}

fn parse_ack(body: &[u8]) -> Result<AlarmAck, RtaError> {
    let mut c = Cursor::new(body);
    let alarm_type = AlarmType::from_u16(c.u16()?);
    let api = c.u32()?;
    let slot = c.u16()?;
    let subslot = c.u16()?;
    let specifier = AlarmSpecifier::from_u16(c.u16()?);
    let status = PnioStatus(c.u32()?);
    Ok(AlarmAck {
        alarm_type,
        api,
        slot,
        subslot,
        specifier,
        status,
    })
}

/// Builds a complete Ethernet frame from an `RtaPdu`. Does not pad to 60 bytes: the
/// goldens are unpadded sender-side captures (the NIC pads on the wire).
pub fn build_frame(dst: MacAddr, src: MacAddr, pdu: &RtaPdu) -> Vec<u8> {
    let mut var_part = Vec::new();
    match &pdu.body {
        RtaBody::Ack | RtaBody::Nack => {}
        RtaBody::Err(status) => var_part.extend_from_slice(&status.to_u32().to_be_bytes()),
        RtaBody::Data(data) => write_rta_data(&mut var_part, data, pdu.priority),
    }

    let mut out = Vec::new();
    let eth = EthHeader {
        dst,
        src,
        vlan: Some(pdu.priority.tci()),
        ethertype: ETHERTYPE_PROFINET,
    };
    eth.write(&mut out);
    out.extend_from_slice(&pdu.priority.frame_id().to_be_bytes());
    pdu.header.write(&mut out, var_part.len() as u16);
    out.extend_from_slice(&var_part);
    out
}

fn write_rta_data(out: &mut Vec<u8>, data: &RtaData, priority: Priority) {
    match data {
        RtaData::Notification(n) => write_notification(out, n, priority),
        RtaData::Ack(a) => write_ack(out, a, priority),
        RtaData::Unknown { block_type, body } => {
            BlockHeader::write(out, *block_type, body.len() as u16);
            out.extend_from_slice(body);
        }
    }
}

fn write_notification(out: &mut Vec<u8>, n: &AlarmNotification, priority: Priority) {
    let block_type = match priority {
        Priority::High => 0x0001,
        Priority::Low => 0x0002,
    };
    let mut body = Vec::new();
    body.extend_from_slice(&n.alarm_type.to_u16().to_be_bytes());
    body.extend_from_slice(&n.api.to_be_bytes());
    body.extend_from_slice(&n.slot.to_be_bytes());
    body.extend_from_slice(&n.subslot.to_be_bytes());
    body.extend_from_slice(&n.module_ident.to_be_bytes());
    body.extend_from_slice(&n.submodule_ident.to_be_bytes());
    body.extend_from_slice(&n.specifier.to_u16().to_be_bytes());
    body.extend_from_slice(&n.usi.to_be_bytes());
    match &n.data {
        UserData::Channel(d) => d.write(&mut body),
        UserData::ExtChannel(d) => d.write(&mut body),
        UserData::Raw(bytes) => body.extend_from_slice(bytes),
    }
    BlockHeader::write(out, block_type, body.len() as u16);
    out.extend_from_slice(&body);
}

fn write_ack(out: &mut Vec<u8>, a: &AlarmAck, priority: Priority) {
    let block_type = match priority {
        Priority::High => 0x8001,
        Priority::Low => 0x8002,
    };
    let mut body = Vec::new();
    body.extend_from_slice(&a.alarm_type.to_u16().to_be_bytes());
    body.extend_from_slice(&a.api.to_be_bytes());
    body.extend_from_slice(&a.slot.to_be_bytes());
    body.extend_from_slice(&a.subslot.to_be_bytes());
    body.extend_from_slice(&a.specifier.to_u16().to_be_bytes());
    body.extend_from_slice(&a.status.to_u32().to_be_bytes());
    BlockHeader::write(out, block_type, body.len() as u16);
    out.extend_from_slice(&body);
}

/// True if `frame` is a PROFINET alarm frame (tagged or untagged `0x8892` with
/// FrameID `0xFC01`/`0xFE01`).
pub fn is_alarm_frame(frame: &[u8]) -> bool {
    match EthHeader::parse(frame) {
        Ok((eth, off)) => {
            eth.ethertype == ETHERTYPE_PROFINET
                && frame.len() >= off + 2
                && matches!(
                    u16::from_be_bytes([frame[off], frame[off + 1]]),
                    FRAME_ID_HIGH | FRAME_ID_LOW
                )
        }
        Err(_) => false,
    }
}

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

    const DEV: MacAddr = MacAddr([0x8c, 0xf3, 0x19, 0xcd, 0x19, 0xf8]);
    const CPU: MacAddr = MacAddr([0xec, 0x1c, 0x5d, 0x61, 0xe7, 0x3c]);

    #[test]
    fn process_notification_parses_and_rebuilds_byte_exact() {
        let g = golden_alarm("alarm_process_notif");
        let pdu = parse_frame(&g).unwrap();
        assert_eq!(pdu.priority, Priority::High);
        assert_eq!(
            pdu.header,
            RtaHeader {
                dst_ref: 0,
                src_ref: 0,
                pdu_type: PduType::Data,
                tack: true,
                send_seq: 0xFFFF,
                ack_seq: 0xFFFE
            }
        );
        let RtaBody::Data(RtaData::Notification(n)) = &pdu.body else {
            panic!("not a notification")
        };
        assert_eq!(n.alarm_type, AlarmType::Process);
        assert_eq!((n.api, n.slot, n.subslot), (0, 1, 1));
        assert_eq!((n.module_ident, n.submodule_ident), (0x30, 0x130));
        assert_eq!(
            n.specifier,
            AlarmSpecifier {
                sequence: 0,
                channel_diag: false,
                manufacturer_diag: false,
                submodule_diag: false,
                ar_diag: false
            }
        );
        assert_eq!(n.usi, 0x0010);
        assert_eq!(n.data, UserData::Raw(vec![0x01]));
        assert_eq!(build_frame(CPU, DEV, &pdu), g);
    }

    #[test]
    fn diagnosis_notification_parses_ext_channel_and_rebuilds() {
        let g = golden_alarm("alarm_diag_notif");
        let pdu = parse_frame(&g).unwrap();
        assert_eq!(pdu.priority, Priority::Low);
        let RtaBody::Data(RtaData::Notification(n)) = &pdu.body else {
            panic!()
        };
        assert_eq!(n.alarm_type, AlarmType::Diagnosis);
        assert_eq!(
            n.specifier,
            AlarmSpecifier {
                sequence: 0,
                channel_diag: true,
                manufacturer_diag: false,
                submodule_diag: true,
                ar_diag: true
            }
        );
        assert_eq!(n.usi, USI_EXT_CHANNEL_DIAG);
        let UserData::ExtChannel(d) = &n.data else {
            panic!()
        };
        assert_eq!(d.channel, 4);
        assert_eq!(
            d.properties,
            ChannelProperties {
                type_: 1,
                accumulative: false,
                maintenance: Maintenance::Fault,
                specifier: Specifier::Appears,
                direction: 1
            }
        );
        assert_eq!(d.properties.to_u16(), 0x2801);
        assert_eq!(d.error_type, 0x0001);
        assert_eq!((d.ext_error_type, d.ext_add_value), (0, 0));
        assert_eq!(build_frame(CPU, DEV, &pdu), g);
    }

    #[test]
    fn channel_properties_bit_fields_round_trip() {
        for raw in [0x2801u16, 0x3801, 0x2001, 0x0000, 0x6A00] {
            assert_eq!(ChannelProperties::from_u16(raw).to_u16(), raw);
        }
        assert_eq!(
            ChannelProperties::from_u16(0x3801).specifier,
            Specifier::DisappearsOthersRemain
        );
        assert_eq!(
            ChannelProperties::from_u16(0x2001).specifier,
            Specifier::AllDisappear
        );
    }

    #[test]
    fn cpu_ack_rta_and_alarm_ack_parse() {
        let ack = parse_frame(&golden_alarm("alarm_ack_rta_high_cpu")).unwrap();
        assert_eq!(ack.body, RtaBody::Ack);
        assert_eq!(
            (ack.header.send_seq, ack.header.ack_seq, ack.header.tack),
            (0xFFFE, 0xFFFF, false)
        );
        let aa = parse_frame(&golden_alarm("alarm_ack_high_cpu")).unwrap();
        let RtaBody::Data(RtaData::Ack(a)) = &aa.body else {
            panic!()
        };
        assert_eq!(a.alarm_type, AlarmType::Process);
        assert_eq!((a.slot, a.subslot), (1, 1));
        assert_eq!(a.status, PnioStatus::OK);
        assert_eq!((aa.header.send_seq, aa.header.ack_seq), (0xFFFF, 0xFFFF));
    }

    #[test]
    fn our_ack_rta_rebuilds_byte_exact() {
        for name in ["alarm_ack_rta_high_dev", "alarm_ack_rta_low_dev"] {
            let g = golden_alarm(name);
            let pdu = parse_frame(&g).unwrap();
            assert_eq!(pdu.body, RtaBody::Ack);
            assert_eq!(build_frame(CPU, DEV, &pdu), g, "{name}");
        }
    }

    #[test]
    fn err_rta_both_ways() {
        let dev = parse_frame(&golden_alarm("alarm_err_rta_dev")).unwrap();
        assert_eq!(
            dev.body,
            RtaBody::Err(PnioStatus::new(0xCF, 0x81, 0xFD, 0x00))
        );
        assert_eq!((dev.header.send_seq, dev.header.ack_seq), (6, 5));
        assert_eq!(
            build_frame(CPU, DEV, &dev),
            golden_alarm("alarm_err_rta_dev")
        );
        let cpu = parse_frame(&golden_alarm("alarm_err_rta_cpu")).unwrap();
        assert_eq!(
            cpu.body,
            RtaBody::Err(PnioStatus::new(0xCF, 0x81, 0xFD, 0x0B))
        );
        let removed = parse_frame(&golden_alarm("alarm_err_rta_cpu_removed")).unwrap();
        assert_eq!(
            removed.body,
            RtaBody::Err(PnioStatus::new(0xCF, 0x81, 0xFD, 0x11))
        );
        assert_eq!(
            (removed.header.send_seq, removed.header.ack_seq),
            (0xFFFE, 0xFFFE)
        );
        let removed_reply = parse_frame(&golden_alarm("alarm_err_rta_dev_removed_reply")).unwrap();
        assert_eq!(removed_reply.priority, Priority::Low);
        assert_eq!(
            removed_reply.body,
            RtaBody::Err(PnioStatus::new(0xCF, 0x81, 0xFD, 0x11))
        );
        assert_eq!(
            (removed_reply.header.send_seq, removed_reply.header.ack_seq),
            (0xFFFF, 0xFFFE)
        );
        assert_eq!(
            build_frame(CPU, DEV, &removed_reply),
            golden_alarm("alarm_err_rta_dev_removed_reply")
        );
    }

    #[test]
    fn disappears_and_std_remove_goldens_rebuild() {
        for name in [
            "alarm_diag_usi_disappears",
            "alarm_diag_std_remove",
            "alarm_diag_update_appears",
            "alarm_diag_update_others_remain",
        ] {
            let g = golden_alarm(name);
            let pdu = parse_frame(&g).unwrap();
            assert_eq!(build_frame(CPU, DEV, &pdu), g, "{name}");
        }
        let RtaBody::Data(RtaData::Notification(n)) =
            parse_frame(&golden_alarm("alarm_diag_usi_disappears"))
                .unwrap()
                .body
        else {
            panic!()
        };
        assert_eq!(n.alarm_type, AlarmType::DiagnosisDisappears);
        assert_eq!(n.usi, 0x1234);
        assert_eq!(n.specifier.sequence, 5);
    }

    #[test]
    fn is_alarm_frame_discriminates() {
        assert!(is_alarm_frame(&golden_alarm("alarm_process_notif")));
        assert!(!is_alarm_frame(&golden_alarm("im0_read_req")));
        assert!(!is_alarm_frame(&crate::testutil::golden("dcp_set_req")));
    }

    #[test]
    fn malformed_frames_are_errors_not_panics() {
        let g = golden_alarm("alarm_process_notif");
        assert!(matches!(parse_frame(&g[..25]), Err(RtaError::TooShort)));
        let mut bad = g.clone();
        bad[24] = 0x15; // pdu type 5
        assert!(matches!(parse_frame(&bad), Err(RtaError::BadPduType(5))));
        let mut short = g.clone();
        short[30] = 0x00;
        short[31] = 0x40; // var_part_len 64 > available
        assert!(matches!(
            parse_frame(&short),
            Err(RtaError::BadVarPartLen { .. })
        ));
    }
}