knx-rs-core 0.2.0

Platform-independent KNX protocol types, CEMI frames, and DPT conversions
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
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Fabian Schmieder

//! KNXnet/IP frame types.
//!
//! Provides parsing and construction of KNXnet/IP protocol frames used for
//! IP-based KNX communication (tunneling, routing, discovery).
//!
//! # Wire Layout
//!
//! ```text
//! Offset  Field              Size
//! ──────  ─────              ────
//!   0     Header Length       1 byte  (always 0x06)
//!   1     Protocol Version    1 byte  (always 0x10)
//!   2     Service Type        2 bytes (big-endian)
//!   4     Total Length         2 bytes (big-endian, includes header)
//!   6     Body                variable
//! ```

use alloc::vec::Vec;
use core::fmt;

/// KNXnet/IP header length (always 6 bytes).
pub const HEADER_LEN: u8 = 0x06;

/// KNXnet/IP protocol version 1.0.
pub const PROTOCOL_VERSION_10: u8 = 0x10;

/// KNXnet/IP service type identifiers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u16)]
pub enum ServiceType {
    /// Search request.
    SearchRequest = 0x0201,
    /// Search response.
    SearchResponse = 0x0202,
    /// Description request.
    DescriptionRequest = 0x0203,
    /// Description response.
    DescriptionResponse = 0x0204,
    /// Connect request.
    ConnectRequest = 0x0205,
    /// Connect response.
    ConnectResponse = 0x0206,
    /// Connection state request.
    ConnectionStateRequest = 0x0207,
    /// Connection state response.
    ConnectionStateResponse = 0x0208,
    /// Disconnect request.
    DisconnectRequest = 0x0209,
    /// Disconnect response.
    DisconnectResponse = 0x020A,
    /// Extended search request.
    SearchRequestExtended = 0x020B,
    /// Extended search response.
    SearchResponseExtended = 0x020C,
    /// Device configuration request.
    DeviceConfigurationRequest = 0x0310,
    /// Device configuration acknowledgement.
    DeviceConfigurationAck = 0x0311,
    /// Tunneling request.
    TunnelingRequest = 0x0420,
    /// Tunneling acknowledgement.
    TunnelingAck = 0x0421,
    /// Routing indication (multicast).
    RoutingIndication = 0x0530,
    /// Routing lost message.
    RoutingLostMessage = 0x0531,
    /// Routing busy.
    RoutingBusy = 0x0532,
}

impl ServiceType {
    /// Try to convert a raw `u16` to a `ServiceType`.
    pub const fn from_raw(raw: u16) -> Option<Self> {
        Some(match raw {
            0x0201 => Self::SearchRequest,
            0x0202 => Self::SearchResponse,
            0x0203 => Self::DescriptionRequest,
            0x0204 => Self::DescriptionResponse,
            0x0205 => Self::ConnectRequest,
            0x0206 => Self::ConnectResponse,
            0x0207 => Self::ConnectionStateRequest,
            0x0208 => Self::ConnectionStateResponse,
            0x0209 => Self::DisconnectRequest,
            0x020A => Self::DisconnectResponse,
            0x020B => Self::SearchRequestExtended,
            0x020C => Self::SearchResponseExtended,
            0x0310 => Self::DeviceConfigurationRequest,
            0x0311 => Self::DeviceConfigurationAck,
            0x0420 => Self::TunnelingRequest,
            0x0421 => Self::TunnelingAck,
            0x0530 => Self::RoutingIndication,
            0x0531 => Self::RoutingLostMessage,
            0x0532 => Self::RoutingBusy,
            _ => return None,
        })
    }
}

/// Host protocol code for HPAI.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum HostProtocol {
    /// IPv4 over UDP.
    Ipv4Udp = 0x01,
    /// IPv4 over TCP.
    Ipv4Tcp = 0x02,
}

impl HostProtocol {
    /// Try to convert a raw host protocol code to a [`HostProtocol`].
    pub const fn from_raw(raw: u8) -> Option<Self> {
        Some(match raw {
            0x01 => Self::Ipv4Udp,
            0x02 => Self::Ipv4Tcp,
            _ => return None,
        })
    }
}

/// Error returned when parsing a KNXnet/IP frame fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KnxIpError {
    /// Frame is shorter than the header.
    TooShort,
    /// Header length field is not 0x06.
    InvalidHeaderLength,
    /// Protocol version is not 0x10.
    InvalidProtocolVersion,
    /// Total length does not match actual data.
    LengthMismatch,
    /// Unknown service type.
    UnknownServiceType(u16),
    /// Serialized frame length exceeds the KNXnet/IP 16-bit length field.
    FrameTooLong(usize),
}

impl fmt::Display for KnxIpError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TooShort => f.write_str("KNXnet/IP frame too short"),
            Self::InvalidHeaderLength => f.write_str("invalid KNXnet/IP header length"),
            Self::InvalidProtocolVersion => f.write_str("invalid KNXnet/IP protocol version"),
            Self::LengthMismatch => f.write_str("KNXnet/IP frame length mismatch"),
            Self::UnknownServiceType(st) => write!(f, "unknown KNXnet/IP service type: {st:#06x}"),
            Self::FrameTooLong(len) => write!(f, "KNXnet/IP frame too long: {len} bytes"),
        }
    }
}

impl core::error::Error for KnxIpError {}

/// A parsed KNXnet/IP frame header + body.
#[derive(Clone, PartialEq, Eq)]
pub struct KnxIpFrame {
    /// The service type.
    pub service_type: ServiceType,
    /// The frame body (after the 6-byte header).
    pub body: Vec<u8>,
}

impl KnxIpFrame {
    /// Parse a KNXnet/IP frame from raw bytes.
    ///
    /// # Errors
    ///
    /// Returns [`KnxIpError`] if the frame is malformed.
    pub fn parse(data: &[u8]) -> Result<Self, KnxIpError> {
        if data.len() < HEADER_LEN as usize {
            return Err(KnxIpError::TooShort);
        }
        if data[0] != HEADER_LEN {
            return Err(KnxIpError::InvalidHeaderLength);
        }
        if data[1] != PROTOCOL_VERSION_10 {
            return Err(KnxIpError::InvalidProtocolVersion);
        }

        let service_raw = u16::from_be_bytes([data[2], data[3]]);
        let total_len = u16::from_be_bytes([data[4], data[5]]) as usize;

        if data.len() != total_len {
            return Err(KnxIpError::LengthMismatch);
        }

        let service_type = ServiceType::from_raw(service_raw)
            .ok_or(KnxIpError::UnknownServiceType(service_raw))?;

        Ok(Self {
            service_type,
            body: data[HEADER_LEN as usize..total_len].to_vec(),
        })
    }

    /// Serialize the frame to bytes (header + body).
    ///
    /// # Errors
    ///
    /// Returns [`KnxIpError::FrameTooLong`] if the frame body cannot fit in
    /// the 16-bit KNXnet/IP length field.
    pub fn try_to_bytes(&self) -> Result<Vec<u8>, KnxIpError> {
        let total_len = HEADER_LEN as usize + self.body.len();
        let total_len_u16 =
            u16::try_from(total_len).map_err(|_| KnxIpError::FrameTooLong(total_len))?;
        let mut buf = Vec::with_capacity(total_len);
        buf.push(HEADER_LEN);
        buf.push(PROTOCOL_VERSION_10);
        buf.extend_from_slice(&(self.service_type as u16).to_be_bytes());
        buf.extend_from_slice(&total_len_u16.to_be_bytes());
        buf.extend_from_slice(&self.body);
        Ok(buf)
    }

    /// Serialize the frame to bytes (header + body).
    ///
    /// # Panics
    ///
    /// Panics if the frame body cannot fit in the 16-bit KNXnet/IP length
    /// field. Use [`Self::try_to_bytes`] when the body length is not statically
    /// bounded.
    pub fn to_bytes(&self) -> Vec<u8> {
        match self.try_to_bytes() {
            Ok(bytes) => bytes,
            Err(KnxIpError::FrameTooLong(len)) => {
                panic!("KNXnet/IP frame length {len} exceeds u16::MAX")
            }
            Err(_) => unreachable!("serializing a well-typed frame cannot fail for this reason"),
        }
    }
}

impl fmt::Debug for KnxIpFrame {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("KnxIpFrame")
            .field("service_type", &self.service_type)
            .field("body_len", &self.body.len())
            .finish()
    }
}

/// KNXnet/IP Connection Header (4 bytes).
///
/// Used in tunneling request/ack frames.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConnectionHeader {
    /// Channel ID.
    pub channel_id: u8,
    /// Sequence counter.
    pub sequence_counter: u8,
    /// Status code.
    pub status: u8,
}

impl ConnectionHeader {
    /// Header length on the wire (always 4).
    pub const LEN: u8 = 4;

    /// Parse from a 4-byte slice.
    pub const fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < Self::LEN as usize {
            return None;
        }
        Some(Self {
            channel_id: data[1],
            sequence_counter: data[2],
            status: data[3],
        })
    }

    /// Serialize to 4 bytes.
    pub const fn to_bytes(self) -> [u8; 4] {
        [
            Self::LEN,
            self.channel_id,
            self.sequence_counter,
            self.status,
        ]
    }
}

/// Host Protocol Address Information (HPAI) — 8 bytes.
///
/// Identifies an IP endpoint (address + port).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Hpai {
    /// Host protocol (UDP or TCP).
    pub protocol: HostProtocol,
    /// IPv4 address as 4 bytes.
    pub ip: [u8; 4],
    /// Port number.
    pub port: u16,
}

impl Hpai {
    /// HPAI length on the wire (always 8).
    pub const LEN: u8 = 8;

    /// Parse from an 8-byte slice.
    pub const fn parse(data: &[u8]) -> Option<Self> {
        if data.len() < Self::LEN as usize || data[0] != Self::LEN {
            return None;
        }
        let Some(protocol) = HostProtocol::from_raw(data[1]) else {
            return None;
        };
        Some(Self {
            protocol,
            ip: [data[2], data[3], data[4], data[5]],
            port: u16::from_be_bytes([data[6], data[7]]),
        })
    }

    /// Create a UDP HPAI in NAT mode.
    ///
    /// KNXnet/IP HPAI carries IPv4 endpoints only. For IPv6 sockets, callers
    /// should use this NAT-mode representation and rely on the UDP source
    /// address as the authoritative endpoint.
    pub const fn nat_udp(port: u16) -> Self {
        Self {
            protocol: HostProtocol::Ipv4Udp,
            ip: [0, 0, 0, 0],
            port,
        }
    }

    /// Whether this HPAI uses the wildcard IPv4 address.
    pub fn is_unspecified(self) -> bool {
        self.ip == [0, 0, 0, 0]
    }

    /// Serialize to 8 bytes.
    pub const fn to_bytes(self) -> [u8; 8] {
        let port = self.port.to_be_bytes();
        [
            Self::LEN,
            self.protocol as u8,
            self.ip[0],
            self.ip[1],
            self.ip[2],
            self.ip[3],
            port[0],
            port[1],
        ]
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::cast_possible_truncation
)]
mod tests {
    use alloc::vec;

    use super::*;

    #[test]
    fn parse_routing_indication() {
        // KNXnet/IP header + CEMI frame (routing indication)
        let mut frame_data = Vec::new();
        frame_data.push(0x06); // header length
        frame_data.push(0x10); // protocol version
        frame_data.extend_from_slice(&0x0530u16.to_be_bytes()); // RoutingIndication
        let cemi = [
            0x29, 0x00, 0xBC, 0xE0, 0x11, 0x01, 0x08, 0x01, 0x01, 0x00, 0x81,
        ];
        let total_len = u16::from(HEADER_LEN) + cemi.len() as u16;
        frame_data.extend_from_slice(&total_len.to_be_bytes());
        frame_data.extend_from_slice(&cemi);

        let frame = KnxIpFrame::parse(&frame_data).unwrap();
        assert_eq!(frame.service_type, ServiceType::RoutingIndication);
        assert_eq!(frame.body, cemi);
    }

    #[test]
    fn roundtrip_tunneling_request() {
        let cemi = [
            0x29, 0x00, 0xBC, 0xE0, 0x11, 0x01, 0x08, 0x01, 0x01, 0x00, 0x81,
        ];
        let ch = ConnectionHeader {
            channel_id: 1,
            sequence_counter: 5,
            status: 0,
        };

        let mut body = Vec::new();
        body.extend_from_slice(&ch.to_bytes());
        body.extend_from_slice(&cemi);

        let frame = KnxIpFrame {
            service_type: ServiceType::TunnelingRequest,
            body,
        };

        let bytes = frame.to_bytes();
        let reparsed = KnxIpFrame::parse(&bytes).unwrap();
        assert_eq!(reparsed.service_type, ServiceType::TunnelingRequest);

        let ch2 = ConnectionHeader::parse(&reparsed.body).unwrap();
        assert_eq!(ch2.channel_id, 1);
        assert_eq!(ch2.sequence_counter, 5);
        assert_eq!(ch2.status, 0);
    }

    #[test]
    fn roundtrip_tunneling_ack() {
        let ch = ConnectionHeader {
            channel_id: 1,
            sequence_counter: 5,
            status: 0,
        };
        let frame = KnxIpFrame {
            service_type: ServiceType::TunnelingAck,
            body: ch.to_bytes().to_vec(),
        };
        let bytes = frame.to_bytes();
        assert_eq!(
            bytes.len(),
            HEADER_LEN as usize + ConnectionHeader::LEN as usize
        );

        let reparsed = KnxIpFrame::parse(&bytes).unwrap();
        assert_eq!(reparsed.service_type, ServiceType::TunnelingAck);
    }

    #[test]
    fn parse_hpai() {
        let data = [0x08, 0x01, 192, 168, 1, 50, 0x0E, 0x57]; // UDP, 192.168.1.50:3671
        let hpai = Hpai::parse(&data).unwrap();
        assert_eq!(hpai.protocol, HostProtocol::Ipv4Udp);
        assert_eq!(hpai.ip, [192, 168, 1, 50]);
        assert_eq!(hpai.port, 3671);
        assert!(!hpai.is_unspecified());
        assert_eq!(hpai.to_bytes(), data);
    }

    #[test]
    fn hpai_nat_udp_roundtrip() {
        let hpai = Hpai::nat_udp(3671);
        assert_eq!(hpai.protocol, HostProtocol::Ipv4Udp);
        assert!(hpai.is_unspecified());
        assert_eq!(Hpai::parse(&hpai.to_bytes()), Some(hpai));
    }

    #[test]
    fn parse_too_short() {
        assert!(KnxIpFrame::parse(&[0x06, 0x10]).is_err());
    }

    #[test]
    fn parse_bad_header_length() {
        let data = [0x05, 0x10, 0x05, 0x30, 0x00, 0x06];
        assert!(matches!(
            KnxIpFrame::parse(&data),
            Err(KnxIpError::InvalidHeaderLength)
        ));
    }

    #[test]
    fn parse_bad_version() {
        let data = [0x06, 0x11, 0x05, 0x30, 0x00, 0x06];
        assert!(matches!(
            KnxIpFrame::parse(&data),
            Err(KnxIpError::InvalidProtocolVersion)
        ));
    }

    #[test]
    fn parse_unknown_service() {
        let data = [0x06, 0x10, 0xFF, 0xFF, 0x00, 0x06];
        assert!(matches!(
            KnxIpFrame::parse(&data),
            Err(KnxIpError::UnknownServiceType(0xFFFF))
        ));
    }

    #[test]
    fn parse_rejects_trailing_bytes() {
        let data = [0x06, 0x10, 0x05, 0x30, 0x00, 0x06, 0x00];
        assert!(matches!(
            KnxIpFrame::parse(&data),
            Err(KnxIpError::LengthMismatch)
        ));
    }

    #[test]
    fn try_to_bytes_rejects_oversized_frame() {
        let frame = KnxIpFrame {
            service_type: ServiceType::RoutingIndication,
            body: vec![0; usize::from(u16::MAX)],
        };
        assert!(matches!(
            frame.try_to_bytes(),
            Err(KnxIpError::FrameTooLong(_))
        ));
    }

    #[test]
    fn connection_header_roundtrip() {
        let ch = ConnectionHeader {
            channel_id: 42,
            sequence_counter: 7,
            status: 0,
        };
        let bytes = ch.to_bytes();
        assert_eq!(bytes, [4, 42, 7, 0]);
        let parsed = ConnectionHeader::parse(&bytes).unwrap();
        assert_eq!(parsed, ch);
    }
}