Skip to main content

opcua_kit/
pubsub.rs

1//! A bounded OPC UA Part 14 UADP wire profile for host-owned transports.
2//!
3//! One unsigned NetworkMessage carries one Variant key frame, the UInt16 PublisherId,
4//! WriterGroupId, DataSetWriterId and DataSetMessage sequence number. Match these
5//! identifiers and an agreed field layout at the receiver. They identify a stream
6//! but do not authenticate its sender. The host supplies transport security, sequence
7//! tracking and metadata. No I/O occurs in the codec.
8use alloc::vec::Vec;
9use core::{error::Error, fmt, num::NonZeroU16};
10
11/// Maximum scalar fields per frame. Each encoded field takes at most nine bytes.
12pub const MAX_FIELDS: usize = 64;
13const HEADER_BYTES: usize = 15;
14
15/// Built-in scalar Variant types supported by this profile.
16#[derive(Debug, Clone, Copy, PartialEq)]
17pub enum Field {
18    Boolean(bool),
19    SByte(i8),
20    Byte(u8),
21    Int16(i16),
22    UInt16(u16),
23    Int32(i32),
24    UInt32(u32),
25    Int64(i64),
26    UInt64(u64),
27    Float(f32),
28    Double(f64),
29}
30
31/// Unauthenticated routing information carried in a NetworkMessage.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub struct DataSetId {
34    /// PublisherId shared by the publisher’s writer groups.
35    pub publisher: NonZeroU16,
36    /// WriterGroupId within the publisher.
37    pub writer_group: NonZeroU16,
38    /// DataSetWriterId assigned to this dataset writer.
39    pub writer: NonZeroU16,
40}
41
42/// Complete key frame. Field order follows the publisher's configured dataset.
43#[derive(Debug, Clone, PartialEq)]
44pub struct KeyFrame {
45    /// Routing identifiers to match against the subscriber configuration.
46    pub id: DataSetId,
47    /// DataSetMessage sequence, incremented modulo 65536 by the publisher.
48    pub sequence: u16,
49    /// One to [`MAX_FIELDS`] scalar values in the agreed field order.
50    pub fields: Vec<Field>,
51}
52
53/// Invalid wire data or a UADP profile outside the supported subset.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum FrameError {
56    Unsupported,
57    FieldCount,
58    NullId,
59    Length,
60}
61
62impl fmt::Display for FrameError {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        f.write_str(match self {
65            Self::Unsupported => "unsupported UADP header, field encoding or Variant type",
66            Self::FieldCount => "expected 1 to 64 UADP key-frame fields",
67            Self::NullId => "publisher, writer group and dataset writer IDs must be nonzero",
68            Self::Length => "invalid UADP message length",
69        })
70    }
71}
72impl Error for FrameError {}
73
74impl KeyFrame {
75    /// Encode header and fields as a single UADP NetworkMessage.
76    pub fn encode(&self) -> Result<Vec<u8>, FrameError> {
77        if !(1..=MAX_FIELDS).contains(&self.fields.len()) {
78            return Err(FrameError::FieldCount);
79        }
80        let mut out = Vec::with_capacity(HEADER_BYTES + self.fields.len() * 9);
81        out.extend([0xf1, 0x01]); // Version 1, UInt16 publisher, group and payload headers.
82        out.extend(self.id.publisher.get().to_le_bytes());
83        out.push(1); // Group contains only WriterGroupId.
84        out.extend(self.id.writer_group.get().to_le_bytes());
85        out.push(1); // Exactly one DataSetMessage.
86        out.extend(self.id.writer.get().to_le_bytes());
87        out.push(9); // Valid Variant key frame with sequence number.
88        out.extend(self.sequence.to_le_bytes());
89        out.extend((self.fields.len() as u16).to_le_bytes());
90        for &field in &self.fields {
91            field.encode_into(&mut out);
92        }
93        Ok(out)
94    }
95
96    /// Decode a complete datagram. Unsupported flags, signed messages, unknown
97    /// types, truncated fields and trailing data fail as a whole.
98    pub fn decode(mut input: &[u8]) -> Result<Self, FrameError> {
99        if input.len() > HEADER_BYTES + MAX_FIELDS * 9 {
100            return Err(FrameError::Length);
101        }
102        if take::<2>(&mut input)? != [0xf1, 0x01] {
103            return Err(FrameError::Unsupported);
104        }
105        let publisher =
106            NonZeroU16::new(u16::from_le_bytes(take(&mut input)?)).ok_or(FrameError::NullId)?;
107        expect_byte(&mut input, 1)?;
108        let writer_group =
109            NonZeroU16::new(u16::from_le_bytes(take(&mut input)?)).ok_or(FrameError::NullId)?;
110        expect_byte(&mut input, 1)?;
111        let writer =
112            NonZeroU16::new(u16::from_le_bytes(take(&mut input)?)).ok_or(FrameError::NullId)?;
113        expect_byte(&mut input, 9)?;
114        let sequence = u16::from_le_bytes(take(&mut input)?);
115        let count = usize::from(u16::from_le_bytes(take(&mut input)?));
116        if !(1..=MAX_FIELDS).contains(&count) {
117            return Err(FrameError::FieldCount);
118        }
119        let fields = (0..count)
120            .map(|_| Field::decode_from(&mut input))
121            .collect::<Result<_, _>>()?;
122        if !input.is_empty() {
123            return Err(FrameError::Length);
124        }
125        Ok(Self {
126            id: DataSetId {
127                publisher,
128                writer_group,
129                writer,
130            },
131            sequence,
132            fields,
133        })
134    }
135}
136
137fn take<const N: usize>(input: &mut &[u8]) -> Result<[u8; N], FrameError> {
138    let (value, rest) = input.split_first_chunk::<N>().ok_or(FrameError::Length)?;
139    *input = rest;
140    Ok(*value)
141}
142
143fn expect_byte(input: &mut &[u8], byte: u8) -> Result<(), FrameError> {
144    if take::<1>(input)? == [byte] {
145        Ok(())
146    } else {
147        Err(FrameError::Unsupported)
148    }
149}
150
151impl Field {
152    fn encode_into(self, out: &mut Vec<u8>) {
153        fn append<const N: usize>(out: &mut Vec<u8>, kind: u8, bytes: [u8; N]) {
154            out.push(kind);
155            out.extend(bytes);
156        }
157        match self {
158            Self::Boolean(v) => append(out, 1, [u8::from(v)]),
159            Self::SByte(v) => append(out, 2, v.to_le_bytes()),
160            Self::Byte(v) => append(out, 3, [v]),
161            Self::Int16(v) => append(out, 4, v.to_le_bytes()),
162            Self::UInt16(v) => append(out, 5, v.to_le_bytes()),
163            Self::Int32(v) => append(out, 6, v.to_le_bytes()),
164            Self::UInt32(v) => append(out, 7, v.to_le_bytes()),
165            Self::Int64(v) => append(out, 8, v.to_le_bytes()),
166            Self::UInt64(v) => append(out, 9, v.to_le_bytes()),
167            Self::Float(v) => append(out, 10, v.to_le_bytes()),
168            Self::Double(v) => append(out, 11, v.to_le_bytes()),
169        }
170    }
171
172    fn decode_from(input: &mut &[u8]) -> Result<Self, FrameError> {
173        Ok(match take::<1>(input)?[0] {
174            1 => Self::Boolean(take::<1>(input)?[0] != 0),
175            2 => Self::SByte(i8::from_le_bytes(take(input)?)),
176            3 => Self::Byte(take::<1>(input)?[0]),
177            4 => Self::Int16(i16::from_le_bytes(take(input)?)),
178            5 => Self::UInt16(u16::from_le_bytes(take(input)?)),
179            6 => Self::Int32(i32::from_le_bytes(take(input)?)),
180            7 => Self::UInt32(u32::from_le_bytes(take(input)?)),
181            8 => Self::Int64(i64::from_le_bytes(take(input)?)),
182            9 => Self::UInt64(u64::from_le_bytes(take(input)?)),
183            10 => Self::Float(f32::from_le_bytes(take(input)?)),
184            11 => Self::Double(f64::from_le_bytes(take(input)?)),
185            _ => return Err(FrameError::Unsupported),
186        })
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use alloc::vec;
194
195    fn frame() -> KeyFrame {
196        KeyFrame {
197            id: DataSetId {
198                publisher: NonZeroU16::new(0x1234).unwrap(),
199                writer_group: NonZeroU16::new(9).unwrap(),
200                writer: NonZeroU16::new(2).unwrap(),
201            },
202            sequence: 65535,
203            fields: vec![
204                Field::Boolean(true),
205                Field::SByte(-128),
206                Field::Byte(255),
207                Field::Int16(i16::MIN),
208                Field::UInt16(u16::MAX),
209                Field::Int32(i32::MIN),
210                Field::UInt32(u32::MAX),
211                Field::Int64(i64::MIN),
212                Field::UInt64(u64::MAX),
213                Field::Float(f32::from_bits(1)),
214                Field::Double(f64::from_bits(1)),
215            ],
216        }
217    }
218
219    #[test]
220    fn preserves_numeric_fields_and_rejects_incomplete_or_wrong_profile() {
221        let frame = frame();
222        let bytes = frame.encode().unwrap();
223        assert_eq!(KeyFrame::decode(&bytes), Ok(frame));
224        for i in 0..bytes.len() {
225            assert!(KeyFrame::decode(&bytes[..i]).is_err());
226        }
227        let mut damaged = bytes.clone();
228        damaged.push(0);
229        assert_eq!(KeyFrame::decode(&damaged), Err(FrameError::Length));
230        for (index, value) in [(0, 0xf2), (1, 0x11), (4, 2), (7, 2), (10, 2), (15, 0x80)] {
231            let mut damaged = bytes.clone();
232            damaged[index] = value;
233            assert_eq!(KeyFrame::decode(&damaged), Err(FrameError::Unsupported));
234        }
235        for range in [2..4, 5..7, 8..10] {
236            let mut damaged = bytes.clone();
237            damaged[range].fill(0);
238            assert_eq!(KeyFrame::decode(&damaged), Err(FrameError::NullId));
239        }
240    }
241
242    #[test]
243    fn bounds_fields_and_bytes_before_allocating() {
244        let mut frame = frame();
245        frame.fields = vec![Field::UInt64(7); MAX_FIELDS];
246        let mut data = frame.encode().unwrap();
247        assert_eq!(data.len(), HEADER_BYTES + MAX_FIELDS * 9);
248        assert_eq!(KeyFrame::decode(&data), Ok(frame.clone()));
249        data.push(9);
250        assert_eq!(KeyFrame::decode(&data), Err(FrameError::Length));
251        data.pop();
252        data[13..15].copy_from_slice(&u16::MAX.to_le_bytes());
253        assert_eq!(KeyFrame::decode(&data), Err(FrameError::FieldCount));
254        frame.fields.push(Field::Boolean(false));
255        assert_eq!(frame.encode(), Err(FrameError::FieldCount));
256        frame.fields.clear();
257        assert_eq!(frame.encode(), Err(FrameError::FieldCount));
258    }
259}