Skip to main content

knx_pico/dpt/
dpt3.rs

1//! DPT 3.xxx - 3-bit controlled (dimming and blinds)
2//!
3//! Control datapoint types for stepwise dimming and blind positioning.
4//!
5//! ## Format
6//!
7//! 4 bits total:
8//! - Bit 3 (MSB): Control bit (direction)
9//! - Bits 0-2 (LSB): Stepcode (0-7)
10//!
11//! ```text
12//! ┌─────────┬─────────────┐
13//! │ Control │  Stepcode   │
14//! │  (1b)   │    (3b)     │
15//! └─────────┴─────────────┘
16//!    Bit 3     Bits 0-2
17//! ```
18//!
19//! ## Stepcode Values
20//!
21//! - **0**: Break/Stop - halts current operation
22//! - **1-7**: Intervals (1, 2, 4, 8, 16, 32, 64 intervals respectively)
23//!
24//! ## Common Subtypes
25//!
26//! - **3.007** - Dimming control (decrease/increase light intensity)
27//! - **3.008** - Blind control (up/down blind positioning)
28//!
29//! ## Example
30//!
31//! ```rust,no_run
32//! use knx_pico::dpt::{Dpt3, StepCode, DptEncode};
33//!
34//! let mut buf = [0u8; 1];
35//!
36//! // Increase dimming by 4 intervals
37//! let len = Dpt3::Dimming.encode((true, StepCode::Intervals4), &mut buf)?;
38//!
39//! // Stop dimming
40//! let len = Dpt3::Dimming.encode((false, StepCode::Break), &mut buf)?;
41//!
42//! // Move blind down by 1 interval
43//! let len = Dpt3::Blind.encode((true, StepCode::Intervals1), &mut buf)?;
44//! ```
45
46use crate::dpt::DptEncode;
47use crate::error::{KnxError, Result};
48
49/// DPT 3.xxx 3-bit controlled types
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub enum Dpt3 {
52    /// DPT 3.007 - Dimming control (decrease/increase)
53    Dimming,
54    /// DPT 3.008 - Blind control (up/down)
55    Blind,
56}
57
58/// Stepcode values for 3-bit controlled types
59///
60/// Represents the number of intervals for the control operation.
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62#[repr(u8)]
63pub enum StepCode {
64    /// Break/Stop - halts the current operation
65    Break = 0,
66    /// 1 interval
67    Intervals1 = 1,
68    /// 2 intervals
69    Intervals2 = 2,
70    /// 4 intervals
71    Intervals4 = 3,
72    /// 8 intervals
73    Intervals8 = 4,
74    /// 16 intervals
75    Intervals16 = 5,
76    /// 32 intervals
77    Intervals32 = 6,
78    /// 64 intervals (maximum)
79    Intervals64 = 7,
80}
81
82/// Control direction for DPT 3 operations
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84pub struct ControlCommand {
85    /// Control bit: false = decrease/up, true = increase/down
86    pub control: bool,
87    /// Stepcode (0-7)
88    pub stepcode: StepCode,
89}
90
91impl Dpt3 {
92    /// Decode a byte to a control command
93    ///
94    /// # Arguments
95    ///
96    /// * `data` - Byte slice containing the command (at least 1 byte)
97    ///
98    /// # Returns
99    ///
100    /// A `ControlCommand` with the decoded control and stepcode
101    ///
102    /// # Errors
103    ///
104    /// Returns `KnxError::InvalidDptData` if data is empty or stepcode is invalid
105    ///
106    /// # Examples
107    ///
108    /// ```rust,no_run
109    /// use knx_pico::dpt::{Dpt3, StepCode};
110    ///
111    /// let cmd = Dpt3::Dimming.decode(&[0x0B])?;
112    /// assert_eq!(cmd.control, true);
113    /// assert_eq!(cmd.stepcode, StepCode::Intervals4);
114    /// # Ok::<(), knx_pico::KnxError>(())
115    /// ```
116    pub fn decode(&self, data: &[u8]) -> Result<ControlCommand> {
117        if data.is_empty() {
118            return Err(KnxError::invalid_dpt_data());
119        }
120
121        let byte = data[0];
122        let control = (byte & 0x08) != 0;
123        let stepcode_value = byte & 0x07;
124
125        let stepcode = StepCode::from_u8(stepcode_value)?;
126
127        Ok(ControlCommand { control, stepcode })
128    }
129
130    /// Get the DPT identifier string (e.g., "3.007")
131    pub const fn identifier(&self) -> &'static str {
132        match self {
133            Dpt3::Dimming => "3.007",
134            Dpt3::Blind => "3.008",
135        }
136    }
137
138    /// Get semantic labels for control directions
139    ///
140    /// Returns a tuple (`control_false_label`, `control_true_label`)
141    pub const fn control_labels(&self) -> (&'static str, &'static str) {
142        match self {
143            Dpt3::Dimming => ("decrease", "increase"),
144            Dpt3::Blind => ("up", "down"),
145        }
146    }
147}
148
149impl StepCode {
150    /// Convert a u8 value to a StepCode
151    ///
152    /// # Errors
153    ///
154    /// Returns `KnxError::InvalidDptData` if value is not in range 0-7
155    pub fn from_u8(value: u8) -> Result<Self> {
156        match value {
157            0 => Ok(StepCode::Break),
158            1 => Ok(StepCode::Intervals1),
159            2 => Ok(StepCode::Intervals2),
160            3 => Ok(StepCode::Intervals4),
161            4 => Ok(StepCode::Intervals8),
162            5 => Ok(StepCode::Intervals16),
163            6 => Ok(StepCode::Intervals32),
164            7 => Ok(StepCode::Intervals64),
165            _ => Err(KnxError::invalid_dpt_data()),
166        }
167    }
168
169    /// Get the number of intervals this stepcode represents
170    ///
171    /// Returns 0 for Break, otherwise 1, 2, 4, 8, 16, 32, or 64
172    pub const fn intervals(&self) -> u8 {
173        match self {
174            StepCode::Break => 0,
175            StepCode::Intervals1 => 1,
176            StepCode::Intervals2 => 2,
177            StepCode::Intervals4 => 4,
178            StepCode::Intervals8 => 8,
179            StepCode::Intervals16 => 16,
180            StepCode::Intervals32 => 32,
181            StepCode::Intervals64 => 64,
182        }
183    }
184}
185
186impl DptEncode<(bool, StepCode)> for Dpt3 {
187    fn encode(&self, value: (bool, StepCode), buf: &mut [u8]) -> Result<usize> {
188        if buf.is_empty() {
189            return Err(KnxError::buffer_too_small());
190        }
191
192        let control_bit = if value.0 { 0x08 } else { 0x00 };
193        let step_bits = value.1 as u8 & 0x07;
194        buf[0] = control_bit | step_bits;
195        Ok(1)
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202
203    // =========================================================================
204    // Encoding Tests
205    // =========================================================================
206
207    #[test]
208    fn test_encode_break() {
209        let mut buf = [0u8; 1];
210
211        // Break with control=false (0b0000_0000 = 0x00)
212        let len = Dpt3::Dimming
213            .encode((false, StepCode::Break), &mut buf)
214            .unwrap();
215        assert_eq!(len, 1);
216        assert_eq!(buf[0], 0x00);
217
218        // Break with control=true (0b0000_1000 = 0x08)
219        let len = Dpt3::Dimming
220            .encode((true, StepCode::Break), &mut buf)
221            .unwrap();
222        assert_eq!(len, 1);
223        assert_eq!(buf[0], 0x08);
224    }
225
226    #[test]
227    fn test_encode_dimming_decrease() {
228        let mut buf = [0u8; 1];
229
230        // Decrease by 1 interval: control=false, stepcode=1
231        // 0b0000_0001 = 0x01
232        let len = Dpt3::Dimming
233            .encode((false, StepCode::Intervals1), &mut buf)
234            .unwrap();
235        assert_eq!(len, 1);
236        assert_eq!(buf[0], 0x01);
237
238        // Decrease by 4 intervals: control=false, stepcode=3
239        // 0b0000_0011 = 0x03
240        let len = Dpt3::Dimming
241            .encode((false, StepCode::Intervals4), &mut buf)
242            .unwrap();
243        assert_eq!(len, 1);
244        assert_eq!(buf[0], 0x03);
245    }
246
247    #[test]
248    fn test_encode_dimming_increase() {
249        let mut buf = [0u8; 1];
250
251        // Increase by 1 interval: control=true, stepcode=1
252        // 0b0000_1001 = 0x09
253        let len = Dpt3::Dimming
254            .encode((true, StepCode::Intervals1), &mut buf)
255            .unwrap();
256        assert_eq!(len, 1);
257        assert_eq!(buf[0], 0x09);
258
259        // Increase by 4 intervals: control=true, stepcode=3
260        // 0b0000_1011 = 0x0B
261        let len = Dpt3::Dimming
262            .encode((true, StepCode::Intervals4), &mut buf)
263            .unwrap();
264        assert_eq!(len, 1);
265        assert_eq!(buf[0], 0x0B);
266    }
267
268    #[test]
269    fn test_encode_blind_up() {
270        let mut buf = [0u8; 1];
271
272        // Move up by 2 intervals: control=false, stepcode=2
273        // 0b0000_0010 = 0x02
274        let len = Dpt3::Blind
275            .encode((false, StepCode::Intervals2), &mut buf)
276            .unwrap();
277        assert_eq!(len, 1);
278        assert_eq!(buf[0], 0x02);
279    }
280
281    #[test]
282    fn test_encode_blind_down() {
283        let mut buf = [0u8; 1];
284
285        // Move down by 8 intervals: control=true, stepcode=4
286        // 0b0000_1100 = 0x0C
287        let len = Dpt3::Blind
288            .encode((true, StepCode::Intervals8), &mut buf)
289            .unwrap();
290        assert_eq!(len, 1);
291        assert_eq!(buf[0], 0x0C);
292    }
293
294    #[test]
295    fn test_encode_all_stepcodes() {
296        let mut buf = [0u8; 1];
297        let stepcodes = [
298            (StepCode::Break, 0),
299            (StepCode::Intervals1, 1),
300            (StepCode::Intervals2, 2),
301            (StepCode::Intervals4, 3),
302            (StepCode::Intervals8, 4),
303            (StepCode::Intervals16, 5),
304            (StepCode::Intervals32, 6),
305            (StepCode::Intervals64, 7),
306        ];
307
308        for (stepcode, expected_bits) in &stepcodes {
309            // Control = false
310            let len = Dpt3::Dimming.encode((false, *stepcode), &mut buf).unwrap();
311            assert_eq!(len, 1);
312            assert_eq!(buf[0], *expected_bits);
313
314            // Control = true
315            let len = Dpt3::Dimming.encode((true, *stepcode), &mut buf).unwrap();
316            assert_eq!(len, 1);
317            assert_eq!(buf[0], 0x08 | expected_bits);
318        }
319    }
320
321    // =========================================================================
322    // Decoding Tests
323    // =========================================================================
324
325    #[test]
326    fn test_decode_break() {
327        let cmd = Dpt3::Dimming.decode(&[0x00]).unwrap();
328        assert_eq!(cmd.control, false);
329        assert_eq!(cmd.stepcode, StepCode::Break);
330
331        let cmd = Dpt3::Dimming.decode(&[0x08]).unwrap();
332        assert_eq!(cmd.control, true);
333        assert_eq!(cmd.stepcode, StepCode::Break);
334    }
335
336    #[test]
337    fn test_decode_dimming_decrease() {
338        // Decrease by 1 interval
339        let cmd = Dpt3::Dimming.decode(&[0x01]).unwrap();
340        assert_eq!(cmd.control, false);
341        assert_eq!(cmd.stepcode, StepCode::Intervals1);
342
343        // Decrease by 4 intervals
344        let cmd = Dpt3::Dimming.decode(&[0x03]).unwrap();
345        assert_eq!(cmd.control, false);
346        assert_eq!(cmd.stepcode, StepCode::Intervals4);
347    }
348
349    #[test]
350    fn test_decode_dimming_increase() {
351        // Increase by 1 interval
352        let cmd = Dpt3::Dimming.decode(&[0x09]).unwrap();
353        assert_eq!(cmd.control, true);
354        assert_eq!(cmd.stepcode, StepCode::Intervals1);
355
356        // Increase by 4 intervals
357        let cmd = Dpt3::Dimming.decode(&[0x0B]).unwrap();
358        assert_eq!(cmd.control, true);
359        assert_eq!(cmd.stepcode, StepCode::Intervals4);
360    }
361
362    #[test]
363    fn test_decode_blind_up() {
364        let cmd = Dpt3::Blind.decode(&[0x02]).unwrap();
365        assert_eq!(cmd.control, false);
366        assert_eq!(cmd.stepcode, StepCode::Intervals2);
367    }
368
369    #[test]
370    fn test_decode_blind_down() {
371        let cmd = Dpt3::Blind.decode(&[0x0C]).unwrap();
372        assert_eq!(cmd.control, true);
373        assert_eq!(cmd.stepcode, StepCode::Intervals8);
374    }
375
376    #[test]
377    fn test_decode_all_combinations() {
378        // Test all 16 possible combinations (2 control × 8 stepcodes)
379        for byte in 0x00..=0x0F {
380            let cmd = Dpt3::Dimming.decode(&[byte]).unwrap();
381
382            let expected_control = (byte & 0x08) != 0;
383            let expected_stepcode = StepCode::from_u8(byte & 0x07).unwrap();
384
385            assert_eq!(cmd.control, expected_control);
386            assert_eq!(cmd.stepcode, expected_stepcode);
387        }
388    }
389
390    #[test]
391    fn test_decode_empty_data() {
392        let result = Dpt3::Dimming.decode(&[]);
393        assert!(result.is_err());
394        assert!(matches!(result.unwrap_err(), KnxError::Dpt(_)));
395    }
396
397    #[test]
398    fn test_decode_ignores_upper_bits() {
399        // Upper 4 bits should be ignored
400        let cmd = Dpt3::Dimming.decode(&[0xFF]).unwrap();
401        assert_eq!(cmd.control, true); // Bit 3 is set
402        assert_eq!(cmd.stepcode, StepCode::Intervals64); // Bits 0-2 are 111
403
404        let cmd = Dpt3::Dimming.decode(&[0xF0]).unwrap();
405        assert_eq!(cmd.control, false); // Bit 3 is not set
406        assert_eq!(cmd.stepcode, StepCode::Break); // Bits 0-2 are 000
407    }
408
409    // =========================================================================
410    // Round-trip Tests
411    // =========================================================================
412
413    #[test]
414    fn test_round_trip() {
415        let mut buf = [0u8; 1];
416        let test_cases = [
417            (false, StepCode::Break),
418            (true, StepCode::Break),
419            (false, StepCode::Intervals1),
420            (true, StepCode::Intervals1),
421            (false, StepCode::Intervals4),
422            (true, StepCode::Intervals4),
423            (false, StepCode::Intervals64),
424            (true, StepCode::Intervals64),
425        ];
426
427        for (control, stepcode) in &test_cases {
428            // Encode
429            let len = Dpt3::Dimming
430                .encode((*control, *stepcode), &mut buf)
431                .unwrap();
432            assert_eq!(len, 1);
433
434            // Decode
435            let cmd = Dpt3::Dimming.decode(&buf[..len]).unwrap();
436
437            // Verify
438            assert_eq!(cmd.control, *control);
439            assert_eq!(cmd.stepcode, *stepcode);
440        }
441    }
442
443    // =========================================================================
444    // StepCode Tests
445    // =========================================================================
446
447    #[test]
448    fn test_stepcode_from_u8_valid() {
449        assert_eq!(StepCode::from_u8(0).unwrap(), StepCode::Break);
450        assert_eq!(StepCode::from_u8(1).unwrap(), StepCode::Intervals1);
451        assert_eq!(StepCode::from_u8(2).unwrap(), StepCode::Intervals2);
452        assert_eq!(StepCode::from_u8(3).unwrap(), StepCode::Intervals4);
453        assert_eq!(StepCode::from_u8(4).unwrap(), StepCode::Intervals8);
454        assert_eq!(StepCode::from_u8(5).unwrap(), StepCode::Intervals16);
455        assert_eq!(StepCode::from_u8(6).unwrap(), StepCode::Intervals32);
456        assert_eq!(StepCode::from_u8(7).unwrap(), StepCode::Intervals64);
457    }
458
459    #[test]
460    fn test_stepcode_from_u8_invalid() {
461        let result = StepCode::from_u8(8);
462        assert!(result.is_err());
463        assert!(matches!(result.unwrap_err(), KnxError::Dpt(_)));
464    }
465
466    #[test]
467    fn test_stepcode_intervals() {
468        assert_eq!(StepCode::Break.intervals(), 0);
469        assert_eq!(StepCode::Intervals1.intervals(), 1);
470        assert_eq!(StepCode::Intervals2.intervals(), 2);
471        assert_eq!(StepCode::Intervals4.intervals(), 4);
472        assert_eq!(StepCode::Intervals8.intervals(), 8);
473        assert_eq!(StepCode::Intervals16.intervals(), 16);
474        assert_eq!(StepCode::Intervals32.intervals(), 32);
475        assert_eq!(StepCode::Intervals64.intervals(), 64);
476    }
477
478    // =========================================================================
479    // Metadata Tests
480    // =========================================================================
481
482    #[test]
483    fn test_identifier() {
484        assert_eq!(Dpt3::Dimming.identifier(), "3.007");
485        assert_eq!(Dpt3::Blind.identifier(), "3.008");
486    }
487
488    #[test]
489    fn test_control_labels() {
490        assert_eq!(Dpt3::Dimming.control_labels(), ("decrease", "increase"));
491        assert_eq!(Dpt3::Blind.control_labels(), ("up", "down"));
492    }
493
494    // =========================================================================
495    // Semantic Tests
496    // =========================================================================
497
498    #[test]
499    fn test_semantic_dimming() {
500        let mut buf = [0u8; 1];
501
502        // Start dimming up
503        let len = Dpt3::Dimming
504            .encode((true, StepCode::Intervals1), &mut buf)
505            .unwrap();
506        assert_eq!(len, 1);
507        let cmd = Dpt3::Dimming.decode(&buf[..len]).unwrap();
508        assert_eq!(cmd.control, true); // increase
509        assert_eq!(cmd.stepcode.intervals(), 1);
510
511        // Stop dimming
512        let len = Dpt3::Dimming
513            .encode((false, StepCode::Break), &mut buf)
514            .unwrap();
515        assert_eq!(len, 1);
516        let cmd = Dpt3::Dimming.decode(&buf[..len]).unwrap();
517        assert_eq!(cmd.stepcode, StepCode::Break);
518    }
519
520    #[test]
521    fn test_semantic_blind() {
522        let mut buf = [0u8; 1];
523
524        // Move blind down
525        let len = Dpt3::Blind
526            .encode((true, StepCode::Intervals8), &mut buf)
527            .unwrap();
528        assert_eq!(len, 1);
529        let cmd = Dpt3::Blind.decode(&buf[..len]).unwrap();
530        assert_eq!(cmd.control, true); // down
531        assert_eq!(cmd.stepcode.intervals(), 8);
532
533        // Stop blind
534        let len = Dpt3::Blind
535            .encode((false, StepCode::Break), &mut buf)
536            .unwrap();
537        assert_eq!(len, 1);
538        let cmd = Dpt3::Blind.decode(&buf[..len]).unwrap();
539        assert_eq!(cmd.stepcode, StepCode::Break);
540    }
541
542    // =========================================================================
543    // DptEncode Trait Tests
544    // =========================================================================
545
546    #[test]
547    fn test_trait_encode_basic() {
548        let mut buf = [0u8; 1];
549
550        // Increase dimming by 4 intervals
551        let len = Dpt3::Dimming
552            .encode((true, StepCode::Intervals4), &mut buf)
553            .unwrap();
554        assert_eq!(len, 1);
555        assert_eq!(buf[0], 0x0B);
556
557        // Stop dimming
558        let len = Dpt3::Dimming
559            .encode((false, StepCode::Break), &mut buf)
560            .unwrap();
561        assert_eq!(len, 1);
562        assert_eq!(buf[0], 0x00);
563    }
564
565    #[test]
566    fn test_trait_encode_buffer_too_small() {
567        let mut buf = [0u8; 0];
568        let result = Dpt3::Dimming.encode((true, StepCode::Intervals1), &mut buf);
569        assert!(result.is_err());
570        assert!(matches!(result.unwrap_err(), KnxError::Transport(_)));
571    }
572
573    #[test]
574    fn test_trait_encode_all_combinations() {
575        let mut buf = [0u8; 2];
576
577        for control in [false, true] {
578            for stepcode in [
579                StepCode::Break,
580                StepCode::Intervals1,
581                StepCode::Intervals2,
582                StepCode::Intervals4,
583                StepCode::Intervals8,
584                StepCode::Intervals16,
585                StepCode::Intervals32,
586                StepCode::Intervals64,
587            ] {
588                let len = Dpt3::Dimming.encode((control, stepcode), &mut buf).unwrap();
589                assert_eq!(len, 1);
590
591                // Verify the byte matches expected encoding
592                let control_bit = if control { 0x08 } else { 0x00 };
593                let step_bits = stepcode as u8 & 0x07;
594                let expected = control_bit | step_bits;
595                assert_eq!(buf[0], expected);
596            }
597        }
598    }
599
600    #[test]
601    fn test_trait_encode_round_trip() {
602        let mut buf = [0u8; 1];
603        let test_cases = [
604            (false, StepCode::Break),
605            (true, StepCode::Break),
606            (false, StepCode::Intervals1),
607            (true, StepCode::Intervals4),
608            (false, StepCode::Intervals64),
609            (true, StepCode::Intervals64),
610        ];
611
612        for (control, stepcode) in &test_cases {
613            let len = Dpt3::Dimming
614                .encode((*control, *stepcode), &mut buf)
615                .unwrap();
616            assert_eq!(len, 1);
617
618            let cmd = Dpt3::Dimming.decode(&buf[..len]).unwrap();
619            assert_eq!(cmd.control, *control);
620            assert_eq!(cmd.stepcode, *stepcode);
621        }
622    }
623}