Skip to main content

knx_pico/protocol/
services.rs

1//! KNXnet/IP service request and response builders.
2//!
3//! This module provides zero-copy builders for constructing KNXnet/IP service
4//! frames used in tunneling communication. All builders work with provided
5//! buffers to avoid heap allocations, making them suitable for embedded systems.
6//!
7//! ## Supported Services
8//!
9//! - **CONNECT** - Establish tunnel connection with gateway
10//! - **CONNECTIONSTATE** - Heartbeat/keep-alive checks
11//! - **DISCONNECT** - Clean connection shutdown
12//! - **TUNNELING** - Send/receive KNX telegrams through tunnel
13//!
14//! ## Example
15//!
16//! ```rust,no_run
17//! use knx_pico::protocol::services::ConnectRequest;
18//! use knx_pico::protocol::frame::Hpai;
19//!
20//! // Build a connection request
21//! let control = Hpai::new([192, 168, 1, 100], 3671);
22//! let data = Hpai::new([192, 168, 1, 100], 3671);
23//! let request = ConnectRequest::new(control, data);
24//!
25//! // Encode to buffer
26//! let mut buffer = [0u8; 32];
27//! let len = request.build(&mut buffer)?;
28//! // Send buffer[..len] to gateway
29//! ```
30//!
31//! ## Protocol Flow
32//!
33//! ```text
34//! Client                          Gateway
35//!   |                                |
36//!   |------- CONNECT_REQUEST ------->|
37//!   |<------ CONNECT_RESPONSE -------|
38//!   |                                |
39//!   |------ TUNNELING_REQUEST ------>|
40//!   |<------ TUNNELING_ACK ----------|
41//!   |                                |
42//!   |--- CONNECTIONSTATE_REQUEST --->|  (every 60s)
43//!   |<-- CONNECTIONSTATE_RESPONSE ---|
44//!   |                                |
45//!   |------ DISCONNECT_REQUEST ----->|
46//!   |<----- DISCONNECT_RESPONSE -----|
47//! ```
48
49use crate::error::{KnxError, Result};
50use crate::protocol::constants::{
51    SERVICE_CONNECTIONSTATE_REQUEST, SERVICE_CONNECT_REQUEST, SERVICE_DISCONNECT_REQUEST,
52    SERVICE_TUNNELING_ACK, SERVICE_TUNNELING_REQUEST,
53};
54use crate::protocol::frame::Hpai;
55
56/// Connection Request Information (CRI) for tunneling
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
58pub struct ConnectionRequestInfo {
59    /// Connection type (`TUNNEL_CONNECTION` = 0x04)
60    pub connection_type: u8,
61    /// KNX layer (`TUNNEL_LINKLAYER` = 0x02)
62    pub knx_layer: u8,
63}
64
65impl ConnectionRequestInfo {
66    /// Create a new CRI for tunnel link layer connection
67    pub const fn tunnel_link_layer() -> Self {
68        Self {
69            connection_type: 0x04, // TUNNEL_CONNECTION
70            knx_layer: 0x02,       // TUNNEL_LINKLAYER
71        }
72    }
73
74    /// Encode CRI to bytes
75    pub fn encode(&self, buf: &mut [u8]) -> Result<usize> {
76        if buf.len() < 4 {
77            return Err(KnxError::buffer_too_small());
78        }
79
80        buf[0] = 4; // Structure length
81        buf[1] = self.connection_type;
82        buf[2] = self.knx_layer;
83        buf[3] = 0x00; // Reserved
84
85        Ok(4)
86    }
87
88    /// Decode CRI from bytes
89    pub fn decode(data: &[u8]) -> Result<Self> {
90        if data.len() < 4 {
91            return Err(KnxError::buffer_too_small());
92        }
93
94        let length = data[0];
95        if length != 4 {
96            return Err(KnxError::invalid_frame());
97        }
98
99        Ok(Self {
100            connection_type: data[1],
101            knx_layer: data[2],
102        })
103    }
104}
105
106/// `CONNECT_REQUEST` service (0x0205)
107#[derive(Debug, Clone, Copy)]
108pub struct ConnectRequest {
109    /// Control endpoint (for connection management)
110    pub control_endpoint: Hpai,
111    /// Data endpoint (for tunneling data)
112    pub data_endpoint: Hpai,
113    /// Connection request information
114    pub cri: ConnectionRequestInfo,
115}
116
117impl ConnectRequest {
118    /// Create a new `CONNECT_REQUEST`
119    pub const fn new(control_endpoint: Hpai, data_endpoint: Hpai) -> Self {
120        Self {
121            control_endpoint,
122            data_endpoint,
123            cri: ConnectionRequestInfo::tunnel_link_layer(),
124        }
125    }
126
127    /// Build the complete frame
128    ///
129    /// Returns the number of bytes written to the buffer
130    pub fn build(&self, buf: &mut [u8]) -> Result<usize> {
131        if buf.len() < 26 {
132            return Err(KnxError::buffer_too_small());
133        }
134
135        let mut offset = 0;
136
137        // Header (6 bytes)
138        buf[0] = 0x06; // Header length
139        buf[1] = 0x10; // Protocol version 1.0
140        buf[2..4].copy_from_slice(&SERVICE_CONNECT_REQUEST.to_be_bytes());
141        // Total length will be filled at the end
142        offset += 6;
143
144        // Control endpoint (8 bytes)
145        offset += self.control_endpoint.encode(&mut buf[offset..])?;
146
147        // Data endpoint (8 bytes)
148        offset += self.data_endpoint.encode(&mut buf[offset..])?;
149
150        // CRI (4 bytes)
151        offset += self.cri.encode(&mut buf[offset..])?;
152
153        // Fill total length
154        buf[4..6].copy_from_slice(&(offset as u16).to_be_bytes());
155
156        Ok(offset)
157    }
158}
159
160/// `CONNECT_RESPONSE` service (0x0206)
161#[derive(Debug, Clone, Copy)]
162pub struct ConnectResponse {
163    /// Communication channel ID
164    pub channel_id: u8,
165    /// Status code (0 = OK)
166    pub status: u8,
167    /// Data endpoint assigned by server
168    pub data_endpoint: Hpai,
169    /// Connection response data
170    pub crd: [u8; 4],
171}
172
173impl ConnectResponse {
174    /// Parse from frame body
175    pub fn parse(data: &[u8]) -> Result<Self> {
176        if data.len() < 14 {
177            return Err(KnxError::buffer_too_small());
178        }
179
180        let channel_id = data[0];
181        let status = data[1];
182        let data_endpoint = Hpai::parse(&data[2..10])?;
183
184        let mut crd = [0u8; 4];
185        crd.copy_from_slice(&data[10..14]);
186
187        Ok(Self {
188            channel_id,
189            status,
190            data_endpoint,
191            crd,
192        })
193    }
194
195    /// Check if connection was successful
196    pub const fn is_ok(&self) -> bool {
197        self.status == 0
198    }
199}
200
201/// `CONNECTIONSTATE_REQUEST` service (0x0207)
202#[derive(Debug, Clone, Copy)]
203pub struct ConnectionStateRequest {
204    /// Communication channel ID
205    pub channel_id: u8,
206    /// Control endpoint
207    pub control_endpoint: Hpai,
208}
209
210impl ConnectionStateRequest {
211    /// Create a new `CONNECTIONSTATE_REQUEST`
212    pub const fn new(channel_id: u8, control_endpoint: Hpai) -> Self {
213        Self {
214            channel_id,
215            control_endpoint,
216        }
217    }
218
219    /// Build the complete frame
220    pub fn build(&self, buf: &mut [u8]) -> Result<usize> {
221        if buf.len() < 16 {
222            return Err(KnxError::buffer_too_small());
223        }
224
225        let mut offset = 0;
226
227        // Header
228        buf[0] = 0x06;
229        buf[1] = 0x10;
230        buf[2..4].copy_from_slice(&SERVICE_CONNECTIONSTATE_REQUEST.to_be_bytes());
231        offset += 6;
232
233        // Channel ID + reserved
234        buf[offset] = self.channel_id;
235        buf[offset + 1] = 0x00;
236        offset += 2;
237
238        // Control endpoint
239        offset += self.control_endpoint.encode(&mut buf[offset..])?;
240
241        // Fill total length
242        buf[4..6].copy_from_slice(&(offset as u16).to_be_bytes());
243
244        Ok(offset)
245    }
246}
247
248/// `CONNECTIONSTATE_RESPONSE` service (0x0208)
249#[derive(Debug, Clone, Copy)]
250pub struct ConnectionStateResponse {
251    /// Communication channel ID
252    pub channel_id: u8,
253    /// Status code (0 = OK)
254    pub status: u8,
255}
256
257impl ConnectionStateResponse {
258    /// Parse from frame body
259    pub fn parse(data: &[u8]) -> Result<Self> {
260        if data.len() < 2 {
261            return Err(KnxError::buffer_too_small());
262        }
263
264        Ok(Self {
265            channel_id: data[0],
266            status: data[1],
267        })
268    }
269
270    /// Check if connection is still alive
271    pub const fn is_ok(&self) -> bool {
272        self.status == 0
273    }
274}
275
276/// `DISCONNECT_REQUEST` service (0x0209)
277#[derive(Debug, Clone, Copy)]
278pub struct DisconnectRequest {
279    /// Communication channel ID
280    pub channel_id: u8,
281    /// Control endpoint
282    pub control_endpoint: Hpai,
283}
284
285impl DisconnectRequest {
286    /// Create a new `DISCONNECT_REQUEST`
287    pub const fn new(channel_id: u8, control_endpoint: Hpai) -> Self {
288        Self {
289            channel_id,
290            control_endpoint,
291        }
292    }
293
294    /// Build the complete frame
295    pub fn build(&self, buf: &mut [u8]) -> Result<usize> {
296        if buf.len() < 16 {
297            return Err(KnxError::buffer_too_small());
298        }
299
300        let mut offset = 0;
301
302        // Header
303        buf[0] = 0x06;
304        buf[1] = 0x10;
305        buf[2..4].copy_from_slice(&SERVICE_DISCONNECT_REQUEST.to_be_bytes());
306        offset += 6;
307
308        // Channel ID + reserved
309        buf[offset] = self.channel_id;
310        buf[offset + 1] = 0x00;
311        offset += 2;
312
313        // Control endpoint
314        offset += self.control_endpoint.encode(&mut buf[offset..])?;
315
316        // Fill total length
317        buf[4..6].copy_from_slice(&(offset as u16).to_be_bytes());
318
319        Ok(offset)
320    }
321}
322
323/// `DISCONNECT_RESPONSE` service (0x020A)
324#[derive(Debug, Clone, Copy)]
325pub struct DisconnectResponse {
326    /// Communication channel ID
327    pub channel_id: u8,
328    /// Status code (0 = OK)
329    pub status: u8,
330}
331
332impl DisconnectResponse {
333    /// Parse from frame body
334    pub fn parse(data: &[u8]) -> Result<Self> {
335        if data.len() < 2 {
336            return Err(KnxError::buffer_too_small());
337        }
338
339        Ok(Self {
340            channel_id: data[0],
341            status: data[1],
342        })
343    }
344
345    /// Check if disconnect was acknowledged
346    pub const fn is_ok(&self) -> bool {
347        self.status == 0
348    }
349}
350
351/// Connection header for tunneling requests
352#[derive(Debug, Clone, Copy)]
353pub struct ConnectionHeader {
354    /// Communication channel ID
355    pub channel_id: u8,
356    /// Sequence counter
357    pub sequence_counter: u8,
358}
359
360impl ConnectionHeader {
361    /// Create a new connection header
362    pub const fn new(channel_id: u8, sequence_counter: u8) -> Self {
363        Self {
364            channel_id,
365            sequence_counter,
366        }
367    }
368
369    /// Encode to bytes
370    pub fn encode(&self, buf: &mut [u8]) -> Result<usize> {
371        if buf.len() < 4 {
372            return Err(KnxError::buffer_too_small());
373        }
374
375        buf[0] = 4; // Structure length
376        buf[1] = self.channel_id;
377        buf[2] = self.sequence_counter;
378        buf[3] = 0x00; // Reserved
379
380        Ok(4)
381    }
382
383    /// Decode from bytes
384    pub fn decode(data: &[u8]) -> Result<Self> {
385        if data.len() < 4 {
386            return Err(KnxError::buffer_too_small());
387        }
388
389        Ok(Self {
390            channel_id: data[1],
391            sequence_counter: data[2],
392        })
393    }
394}
395
396/// `TUNNELING_REQUEST` service (0x0420)
397#[derive(Debug)]
398pub struct TunnelingRequest<'a> {
399    /// Connection header
400    pub connection_header: ConnectionHeader,
401    /// cEMI frame data
402    pub cemi_data: &'a [u8],
403}
404
405impl<'a> TunnelingRequest<'a> {
406    /// Create a new `TUNNELING_REQUEST`
407    pub const fn new(connection_header: ConnectionHeader, cemi_data: &'a [u8]) -> Self {
408        Self {
409            connection_header,
410            cemi_data,
411        }
412    }
413
414    /// Build the complete frame
415    pub fn build(&self, buf: &mut [u8]) -> Result<usize> {
416        let total_len = 6 + 4 + self.cemi_data.len();
417        if buf.len() < total_len {
418            return Err(KnxError::buffer_too_small());
419        }
420
421        let mut offset = 0;
422
423        // Header
424        buf[0] = 0x06;
425        buf[1] = 0x10;
426        buf[2..4].copy_from_slice(&SERVICE_TUNNELING_REQUEST.to_be_bytes());
427        buf[4..6].copy_from_slice(&(total_len as u16).to_be_bytes());
428        offset += 6;
429
430        // Connection header
431        offset += self.connection_header.encode(&mut buf[offset..])?;
432
433        // cEMI data
434        buf[offset..offset + self.cemi_data.len()].copy_from_slice(self.cemi_data);
435        offset += self.cemi_data.len();
436
437        Ok(offset)
438    }
439
440    /// Parse from frame body
441    pub fn parse(data: &'a [u8]) -> Result<Self> {
442        if data.len() < 4 {
443            return Err(KnxError::buffer_too_small());
444        }
445
446        let connection_header = ConnectionHeader::decode(&data[0..4])?;
447        let cemi_data = &data[4..];
448
449        Ok(Self {
450            connection_header,
451            cemi_data,
452        })
453    }
454}
455
456/// `TUNNELING_ACK` service (0x0421)
457#[derive(Debug, Clone, Copy)]
458pub struct TunnelingAck {
459    /// Connection header
460    pub connection_header: ConnectionHeader,
461    /// Status code (0 = OK)
462    pub status: u8,
463}
464
465impl TunnelingAck {
466    /// Create a new `TUNNELING_ACK`
467    pub const fn new(connection_header: ConnectionHeader, status: u8) -> Self {
468        Self {
469            connection_header,
470            status,
471        }
472    }
473
474    /// Build the complete frame
475    pub fn build(&self, buf: &mut [u8]) -> Result<usize> {
476        if buf.len() < 11 {
477            return Err(KnxError::buffer_too_small());
478        }
479
480        let mut offset = 0;
481
482        // Header
483        buf[0] = 0x06;
484        buf[1] = 0x10;
485        buf[2..4].copy_from_slice(&SERVICE_TUNNELING_ACK.to_be_bytes());
486        buf[4..6].copy_from_slice(&11u16.to_be_bytes());
487        offset += 6;
488
489        // Connection header
490        offset += self.connection_header.encode(&mut buf[offset..])?;
491
492        // Status
493        buf[offset] = self.status;
494        offset += 1;
495
496        Ok(offset)
497    }
498
499    /// Parse from frame body
500    pub fn parse(data: &[u8]) -> Result<Self> {
501        if data.len() < 5 {
502            return Err(KnxError::buffer_too_small());
503        }
504
505        let connection_header = ConnectionHeader::decode(&data[0..4])?;
506        let status = data[4];
507
508        Ok(Self {
509            connection_header,
510            status,
511        })
512    }
513
514    /// Check if request was acknowledged successfully
515    pub const fn is_ok(&self) -> bool {
516        self.status == 0
517    }
518}
519
520#[cfg(test)]
521mod tests {
522    use super::*;
523
524    #[test]
525    fn test_hpai_encode_decode() {
526        let hpai = Hpai::new([192, 168, 1, 10], 3671);
527        let mut buf = [0u8; 8];
528        let len = hpai.encode(&mut buf).unwrap();
529        assert_eq!(len, 8);
530
531        let decoded = Hpai::parse(&buf).unwrap();
532        assert_eq!(decoded, hpai);
533    }
534
535    #[test]
536    fn test_connect_request_build() {
537        let control = Hpai::new([192, 168, 1, 100], 3671);
538        let data = Hpai::new([192, 168, 1, 100], 3671);
539        let request = ConnectRequest::new(control, data);
540
541        let mut buf = [0u8; 32];
542        let len = request.build(&mut buf).unwrap();
543
544        assert_eq!(len, 26);
545        assert_eq!(&buf[0..2], &[0x06, 0x10]); // Header
546        assert_eq!(
547            u16::from_be_bytes([buf[2], buf[3]]),
548            SERVICE_CONNECT_REQUEST
549        );
550    }
551
552    #[test]
553    fn test_connection_header() {
554        let header = ConnectionHeader::new(5, 10);
555        let mut buf = [0u8; 4];
556        let len = header.encode(&mut buf).unwrap();
557
558        assert_eq!(len, 4);
559
560        let decoded = ConnectionHeader::decode(&buf).unwrap();
561        assert_eq!(decoded.channel_id, 5);
562        assert_eq!(decoded.sequence_counter, 10);
563    }
564
565    #[test]
566    fn test_tunneling_ack() {
567        let header = ConnectionHeader::new(3, 15);
568        let ack = TunnelingAck::new(header, 0);
569
570        let mut buf = [0u8; 16];
571        let len = ack.build(&mut buf).unwrap();
572
573        assert_eq!(len, 11);
574        assert!(ack.is_ok());
575    }
576}