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
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 Fabian Schmieder

//! Common External Message Interface (cEMI) frame parsing and serialization.
//!
//! A cEMI frame is the standard encoding for KNX telegrams across all media.
//!
//! # Wire Layout
//!
//! ```text
//! Offset  Field              Size
//! ──────  ─────              ────
//!   0     Message Code       1 byte
//!   1     Additional Info Len 1 byte  (usually 0)
//!   2+N   Control Field 1    1 byte
//!   3+N   Control Field 2    1 byte
//!   4+N   Source Address     2 bytes (big-endian)
//!   6+N   Destination Addr   2 bytes (big-endian)
//!   8+N   NPDU Length        1 byte  (octet count of TPDU/APDU)
//!   9+N   TPDU/APDU data    variable
//! ```
//!
//! Where N = additional info length.

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

use crate::address::{DestinationAddress, GroupAddress, IndividualAddress};
use crate::message::{ApduType, MessageCode};
use crate::tpdu::Tpdu;
use crate::types::{
    AckType, AddressType, Confirm, FrameFormat, Priority, Repetition, SystemBroadcast,
};

/// Minimum cEMI frame size: msg code + add info len + ctrl1 + ctrl2 + src(2) + dst(2) + npdu len.
const MIN_FRAME_SIZE: usize = 9;

/// Offset from start of control fields to NPDU length byte.
const NPDU_LEN_OFFSET: usize = 6;

/// Offset from start of control fields to TPDU/APDU data.
const TPDU_OFFSET: usize = 7;

/// Error returned when parsing a cEMI frame fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CemiError {
    /// Frame is shorter than the minimum required size.
    TooShort,
    /// The declared length does not match the actual data.
    LengthMismatch,
    /// Unknown or unsupported message code.
    UnknownMessageCode(u8),
    /// Control field contains invalid bit combinations.
    InvalidControlField,
    /// TPDU/APDU payload cannot fit in the NPDU length field.
    PayloadTooLong(usize),
}

impl fmt::Display for CemiError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TooShort => f.write_str("cEMI frame too short"),
            Self::LengthMismatch => f.write_str("cEMI frame length mismatch"),
            Self::UnknownMessageCode(c) => write!(f, "unknown cEMI message code: {c:#04x}"),
            Self::InvalidControlField => f.write_str("invalid cEMI control field"),
            Self::PayloadTooLong(len) => write!(f, "cEMI payload too long: {len} bytes"),
        }
    }
}

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

/// A parsed cEMI frame providing typed access to all fields.
///
/// This is an owned representation — the raw bytes are copied into an internal
/// buffer on construction. Field accessors decode directly from the buffer,
/// matching the C++ reference implementation's approach.
#[derive(Clone, PartialEq, Eq)]
pub struct CemiFrame {
    /// Raw frame bytes (message code through end of APDU).
    data: Vec<u8>,
    /// Offset to control field 1 (after message code + add info).
    ctrl_offset: usize,
}

impl CemiFrame {
    /// Parse a cEMI frame from raw bytes.
    ///
    /// # Errors
    ///
    /// Returns [`CemiError`] if the data is too short, has a length mismatch,
    /// or contains invalid fields.
    pub fn parse(data: &[u8]) -> Result<Self, CemiError> {
        if data.len() < 2 {
            return Err(CemiError::TooShort);
        }
        MessageCode::try_from(data[0]).map_err(|_| CemiError::UnknownMessageCode(data[0]))?;

        let add_info_len = data[1] as usize;
        let ctrl_offset = 2 + add_info_len;

        // Need at least: header(2) + add_info(N) + ctrl1 + ctrl2 + src(2) + dst(2) + npdu_len
        if data.len() < ctrl_offset + 7 {
            return Err(CemiError::TooShort);
        }

        let npdu_octet_count = data[ctrl_offset + NPDU_LEN_OFFSET] as usize;
        // TPDU is always at least 2 bytes (TPCI + APCI), even when npdu_octet_count is 0
        let payload_len = (npdu_octet_count + 1).max(2);
        let expected_len = ctrl_offset + TPDU_OFFSET + payload_len;

        if data.len() != expected_len {
            return Err(CemiError::LengthMismatch);
        }

        Ok(Self {
            data: data[..expected_len].to_vec(),
            ctrl_offset,
        })
    }

    /// Create a new cEMI frame for an `L_Data` indication/request with the given APDU payload.
    ///
    /// The frame is initialized with broadcast system broadcast, no additional info.
    ///
    /// # Errors
    ///
    /// Returns [`CemiError::PayloadTooLong`] if the TPDU/APDU payload cannot
    /// fit in the 8-bit NPDU length field.
    pub fn try_new_l_data(
        message_code: MessageCode,
        source: IndividualAddress,
        destination: DestinationAddress,
        priority: Priority,
        payload: &[u8],
    ) -> Result<Self, CemiError> {
        if payload.len() > usize::from(u8::MAX) + 1 {
            return Err(CemiError::PayloadTooLong(payload.len()));
        }

        let npdu_octet_count = if payload.is_empty() {
            0
        } else {
            payload.len() - 1
        };
        let encoded_payload_len = payload.len().max(2);
        let total_len = MIN_FRAME_SIZE + encoded_payload_len;
        let mut data = alloc::vec![0u8; total_len];

        data[0] = message_code as u8;
        data[1] = 0; // no additional info

        let ctrl_offset = 2;

        // Control field 1: standard frame, broadcast, given priority
        data[ctrl_offset] = FrameFormat::Standard as u8
            | Repetition::WasNotRepeated as u8
            | SystemBroadcast::Broadcast as u8
            | priority as u8;

        // Control field 2: address type + hop count 6
        let addr_type = match destination {
            DestinationAddress::Group(_) => AddressType::Group,
            DestinationAddress::Individual(_) => AddressType::Individual,
        };
        data[ctrl_offset + 1] = addr_type as u8 | (6 << 4);

        // Source address
        let src_bytes = source.to_bytes();
        data[ctrl_offset + 2] = src_bytes[0];
        data[ctrl_offset + 3] = src_bytes[1];

        // Destination address
        let dst_raw = match destination {
            DestinationAddress::Group(ga) => ga.raw(),
            DestinationAddress::Individual(ia) => ia.raw(),
        };
        let dst_bytes = dst_raw.to_be_bytes();
        data[ctrl_offset + 4] = dst_bytes[0];
        data[ctrl_offset + 5] = dst_bytes[1];

        // NPDU length
        data[ctrl_offset + NPDU_LEN_OFFSET] =
            u8::try_from(npdu_octet_count).map_err(|_| CemiError::PayloadTooLong(payload.len()))?;

        // TPDU/APDU payload
        if !payload.is_empty() {
            data[ctrl_offset + TPDU_OFFSET..][..payload.len()].copy_from_slice(payload);
        }

        Ok(Self { data, ctrl_offset })
    }

    /// Create a new cEMI frame for an `L_Data` indication/request with the given APDU payload.
    ///
    /// The frame is initialized with broadcast system broadcast, no additional info.
    ///
    /// # Panics
    ///
    /// Panics if the TPDU/APDU payload cannot fit in the 8-bit NPDU length
    /// field. Use [`Self::try_new_l_data`] when the payload length is not
    /// statically bounded.
    pub fn new_l_data(
        message_code: MessageCode,
        source: IndividualAddress,
        destination: DestinationAddress,
        priority: Priority,
        payload: &[u8],
    ) -> Self {
        match Self::try_new_l_data(message_code, source, destination, priority, payload) {
            Ok(frame) => frame,
            Err(CemiError::PayloadTooLong(len)) => {
                panic!("cEMI payload length {len} exceeds the NPDU length field")
            }
            Err(_) => unreachable!("constructing an L_Data frame cannot fail for this reason"),
        }
    }

    // ── Field accessors ───────────────────────────────────────

    /// The raw message code byte.
    pub fn message_code_raw(&self) -> u8 {
        self.data[0]
    }

    /// Additional info length.
    pub fn additional_info_length(&self) -> u8 {
        self.data[1]
    }

    /// Control field 1 (raw byte).
    fn ctrl1(&self) -> u8 {
        self.data[self.ctrl_offset]
    }

    /// Control field 2 (raw byte).
    fn ctrl2(&self) -> u8 {
        self.data[self.ctrl_offset + 1]
    }

    /// Frame format (standard or extended).
    pub fn frame_type(&self) -> FrameFormat {
        if self.ctrl1() & 0x80 != 0 {
            FrameFormat::Standard
        } else {
            FrameFormat::Extended
        }
    }

    /// Repetition flag.
    pub fn repetition(&self) -> Repetition {
        if self.ctrl1() & 0x20 != 0 {
            Repetition::WasNotRepeated
        } else {
            Repetition::WasRepeated
        }
    }

    /// System broadcast flag.
    pub fn system_broadcast(&self) -> SystemBroadcast {
        if self.ctrl1() & 0x10 != 0 {
            SystemBroadcast::Broadcast
        } else {
            SystemBroadcast::System
        }
    }

    /// Telegram priority.
    pub fn priority(&self) -> Priority {
        match self.ctrl1() & 0x0C {
            0x00 => Priority::System,
            0x04 => Priority::Normal,
            0x08 => Priority::Urgent,
            _ => Priority::Low,
        }
    }

    /// Acknowledgement request flag.
    pub fn ack(&self) -> AckType {
        if self.ctrl1() & 0x02 != 0 {
            AckType::Requested
        } else {
            AckType::DontCare
        }
    }

    /// Confirmation flag.
    pub fn confirm(&self) -> Confirm {
        if self.ctrl1() & 0x01 != 0 {
            Confirm::Error
        } else {
            Confirm::NoError
        }
    }

    /// Destination address type.
    pub fn address_type(&self) -> AddressType {
        if self.ctrl2() & 0x80 != 0 {
            AddressType::Group
        } else {
            AddressType::Individual
        }
    }

    /// Hop count (0–7).
    pub fn hop_count(&self) -> u8 {
        (self.ctrl2() >> 4) & 0x07
    }

    /// Source individual address.
    pub fn source_address(&self) -> IndividualAddress {
        let off = self.ctrl_offset + 2;
        IndividualAddress::from_bytes([self.data[off], self.data[off + 1]])
    }

    /// Raw destination address as 16-bit value.
    pub fn destination_address_raw(&self) -> u16 {
        let off = self.ctrl_offset + 4;
        u16::from_be_bytes([self.data[off], self.data[off + 1]])
    }

    /// Typed destination address (group or individual based on address type flag).
    pub fn destination_address(&self) -> DestinationAddress {
        let raw = self.destination_address_raw();
        match self.address_type() {
            AddressType::Group => DestinationAddress::Group(GroupAddress::from_raw(raw)),
            AddressType::Individual => {
                DestinationAddress::Individual(IndividualAddress::from_raw(raw))
            }
        }
    }

    /// NPDU octet count (length of TPDU/APDU data minus 1 for the TPCI byte).
    pub fn npdu_length(&self) -> u8 {
        self.data[self.ctrl_offset + NPDU_LEN_OFFSET]
    }

    /// The TPDU/APDU payload bytes (starting with the TPCI byte).
    pub fn payload(&self) -> &[u8] {
        let start = self.ctrl_offset + TPDU_OFFSET;
        &self.data[start..]
    }

    /// The complete raw frame bytes.
    pub fn as_bytes(&self) -> &[u8] {
        &self.data
    }

    /// Total frame length in bytes.
    pub fn total_length(&self) -> usize {
        self.data.len()
    }

    // ── Mutable setters ───────────────────────────────────────

    /// Set the frame format (standard or extended).
    pub fn set_frame_type(&mut self, value: FrameFormat) {
        self.data[self.ctrl_offset] = (self.data[self.ctrl_offset] & !0x80) | (value as u8);
    }

    /// Set the repetition flag.
    pub fn set_repetition(&mut self, value: Repetition) {
        self.data[self.ctrl_offset] = (self.data[self.ctrl_offset] & !0x20) | (value as u8);
    }

    /// Set the system broadcast flag.
    pub fn set_system_broadcast(&mut self, value: SystemBroadcast) {
        self.data[self.ctrl_offset] = (self.data[self.ctrl_offset] & !0x10) | (value as u8);
    }

    /// Set the telegram priority.
    pub fn set_priority(&mut self, value: Priority) {
        self.data[self.ctrl_offset] = (self.data[self.ctrl_offset] & !0x0C) | (value as u8);
    }

    /// Set the acknowledgement request flag.
    pub fn set_ack(&mut self, value: AckType) {
        self.data[self.ctrl_offset] = (self.data[self.ctrl_offset] & !0x02) | (value as u8);
    }

    /// Set the confirmation flag.
    pub fn set_confirm(&mut self, value: Confirm) {
        self.data[self.ctrl_offset] = (self.data[self.ctrl_offset] & !0x01) | (value as u8);
    }

    /// Set the destination address type.
    pub fn set_address_type(&mut self, value: AddressType) {
        self.data[self.ctrl_offset + 1] = (self.data[self.ctrl_offset + 1] & !0x80) | (value as u8);
    }

    /// Set the hop count (0–7).
    pub fn set_hop_count(&mut self, value: u8) {
        self.data[self.ctrl_offset + 1] =
            (self.data[self.ctrl_offset + 1] & !0x70) | ((value & 0x07) << 4);
    }

    /// Set the source individual address.
    pub fn set_source_address(&mut self, addr: IndividualAddress) {
        let bytes = addr.to_bytes();
        let off = self.ctrl_offset + 2;
        self.data[off] = bytes[0];
        self.data[off + 1] = bytes[1];
    }

    /// Set the destination address (raw 16-bit value).
    pub fn set_destination_address_raw(&mut self, addr: u16) {
        let bytes = addr.to_be_bytes();
        let off = self.ctrl_offset + 4;
        self.data[off] = bytes[0];
        self.data[off + 1] = bytes[1];
    }

    // ── Convenience extractors ─────────────────────────────────

    /// Extract group write data if this is a `GroupValueWrite` or `GroupValueResponse`.
    ///
    /// Returns `(GroupAddress, data)` or `None` if this frame is not a
    /// group-addressed data frame with a write/response APDU.
    pub fn as_group_write(&self) -> Option<(GroupAddress, Vec<u8>)> {
        if self.address_type() != AddressType::Group {
            return None;
        }
        let tpdu = self.tpdu()?;
        let apdu = tpdu.apdu()?;
        match apdu.apdu_type {
            ApduType::GroupValueWrite | ApduType::GroupValueResponse => {}
            _ => return None,
        }
        let ga = GroupAddress::from_raw(self.destination_address_raw());
        Some((ga, apdu.data.clone()))
    }

    /// Check if this is a `GroupValueRead` request and return the target group address.
    pub fn as_group_read(&self) -> Option<GroupAddress> {
        if self.address_type() != AddressType::Group {
            return None;
        }
        let tpdu = self.tpdu()?;
        let apdu = tpdu.apdu()?;
        if apdu.apdu_type != ApduType::GroupValueRead {
            return None;
        }
        Some(GroupAddress::from_raw(self.destination_address_raw()))
    }

    /// Calculate TP CRC over a buffer (XOR of all bytes, inverted).
    pub fn calc_crc_tp(buffer: &[u8]) -> u8 {
        let mut crc: u8 = 0xFF;
        for &b in buffer {
            crc ^= b;
        }
        crc
    }

    /// Parse the TPDU from this frame's payload.
    ///
    /// Returns `None` if the payload cannot be parsed as a valid TPDU.
    pub fn tpdu(&self) -> Option<Tpdu> {
        Tpdu::parse(
            self.payload(),
            self.npdu_length(),
            self.address_type(),
            self.destination_address_raw(),
        )
    }
}

impl fmt::Debug for CemiFrame {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CemiFrame")
            .field("message_code", &self.message_code_raw())
            .field("frame_type", &self.frame_type())
            .field("priority", &self.priority())
            .field("source", &self.source_address())
            .field("destination", &self.destination_address())
            .field("hop_count", &self.hop_count())
            .field("payload_len", &self.npdu_length())
            .finish()
    }
}