can_decode 0.6.1

Decode and encode CAN frames into messages/signals in a fast and easy way.
Documentation
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
//! # can_decode
//!
//! Decode and encode CAN frames into messages/signals in a fast and easy way.
//!
//! ## Features
//!
//! - Parse DBC (CAN Database) files
//! - Decode CAN messages into signals with physical values
//! - Encode signal values back into raw CAN messages
//! - Support for both standard and extended CAN IDs
//! - Handle big-endian and little-endian byte ordering
//! - Support for signed and unsigned signal values
//! - Apply scaling factors and offsets (and inverse for encoding)
//!
//! ## Decoding Example
//!
//! ```no_run
//! use can_decode::Parser;
//! use std::path::Path;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Load a DBC file
//! let parser = Parser::from_dbc_file(Path::new("my_can_database.dbc"))?;
//!
//! // Decode a CAN message
//! let msg_id = 0x123;
//! let data = [0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0];
//!
//! if let Some(decoded) = parser.decode_msg(msg_id, &data) {
//!     println!("Message: {}", decoded.name);
//!     for (signal_name, signal) in &decoded.signals {
//!         println!("  {}: {:?} {}", signal_name, signal.value, signal.unit);
//!     }
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Encoding Example
//!
//! ```no_run
//! use can_decode::Parser;
//! use std::path::Path;
//! use std::collections::HashMap;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let parser = Parser::from_dbc_file(Path::new("my_can_database.dbc"))?;
//!
//! // Encode a CAN message from signal values
//! let signal_values = HashMap::from([
//!     ("EngineSpeed".to_string(), 2500.0),
//!     ("ThrottlePosition".to_string(), 45.5),
//! ]);
//!
//! if let Some(data) = parser.encode_msg(0x123, &signal_values) {
//!     println!("Encoded CAN data: {:02X?}", data);
//! }
//!
//! // Or encode by message name
//! if let Some((msg_id, data)) = parser.encode_msg_by_name("EngineData", &signal_values) {
//!     println!("Message ID: {:#X}, Data: {:02X?}", msg_id, data);
//! }
//! # Ok(())
//! # }
//! ```

/// Creates a bitmask with the lowest N bits set to 1.
///
/// This macro generates a mask value of the specified type with the lower `bits` bits set to 1
/// and all other bits set to 0. It's used internally for extracting or masking the lower portion of
/// integer values.
///
/// # Arguments
///
/// * `$bits` - The number of low bits to set (must be <= the bit width of the type)
/// * `$ty` - The integer type for the mask (e.g., u8, u16, u32, u64)
///
/// # Examples
///
/// ```ignore
/// let mask = low_bits_mask!(4, u8);  // Returns 0b00001111 (15)
/// let mask = low_bits_mask!(8, u8);  // Returns 0b11111111 (255)
/// let mask = low_bits_mask!(0, u16); // Returns 0
/// ```
///
/// # Panics
///
/// Panics in debug builds if `bits` exceeds the bit width of the specified type.
macro_rules! low_bits_mask {
    ($bits:expr, $ty:ty) => {{
        debug_assert!($bits <= <$ty>::BITS as usize);
        match $bits {
            0 => 0 as $ty,
            n if n == <$ty>::BITS as usize => <$ty>::MAX,
            n => <$ty>::MAX >> (<$ty>::BITS as usize - n),
        }
    }};
}

/// Type alias for the ordered map of signals returned by decoding.
///
/// This allows downstream crates to reference the signal map type without
/// needing to add indexmap as a dependency.
pub type SignalMap = indexmap::map::IndexMap<String, DecodedSignal>;

/// A decoded CAN message containing signal values.
///
/// This structure represents a fully decoded CAN message with all its signals
/// extracted and converted to physical values.
#[derive(Debug, Clone)]
pub struct DecodedMessage {
    /// The name of the message as defined in the DBC file
    pub name: String,
    /// The CAN message ID
    pub msg_id: u32,
    /// Whether this is an extended (29-bit) CAN ID
    pub is_extended: bool,
    /// Transmitting node of the message ("Unknown" if not specified)
    pub tx_node: String,
    /// Ordered map of signal names to their decoded values (maintains insertion order)
    pub signals: SignalMap,
}

#[derive(Debug, Clone)]
pub enum DecodedSignalValue {
    /// The physical value after applying factor and offset
    Numeric(f64),
    /// The raw value and the string value for an enumerated signal (if defined in the DBC)
    Enum(i64, String),
}

/// A decoded signal with its physical value.
///
/// Represents a single signal from a CAN message after decoding. The value is
/// either a numeric physical value (after scaling/offset) or an enum label from
/// DBC value descriptions.
#[derive(Debug, Clone)]
pub struct DecodedSignal {
    /// The name of the signal as defined in the DBC file
    pub name: String,
    /// The decoded value, either a numeric physical value or an enum label
    pub value: DecodedSignalValue,
    /// The unit of measurement (e.g., "km/h", "°C", "RPM")
    pub unit: String,
}

/// Value-description mapping for a specific signal.
///
/// DBC files can define enum-like value descriptions per signal, such as
/// `0 = "Off"`, `1 = "On"`. This structure stores those mappings so decoded
/// raw values can be returned as human-readable labels.
#[derive(Debug, Clone)]
pub struct EnumDef {
    /// Signal name this value-description map belongs to.
    pub signal_name: String,
    /// Map from raw integer signal value to label.
    pub enum_map: std::collections::HashMap<i64, String>,
}

/// A CAN message parser that uses DBC file definitions.
///
/// The parser loads message and signal definitions from DBC files and uses them
/// to decode raw CAN frame data into structured messages with physical signal values.
///
/// # Example
///
/// ```no_run
/// use can_decode::Parser;
/// use std::path::Path;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let mut parser = Parser::new();
/// parser.add_from_dbc_file(Path::new("engine.dbc"))?;
/// parser.add_from_dbc_file(Path::new("transmission.dbc"))?;
///
/// let data = [0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70];
/// if let Some(decoded) = parser.decode_msg(0x100, &data) {
///     println!("Decoded message: {}", decoded.name);
/// }
/// # Ok(())
/// # }
/// ```
pub struct Parser {
    /// Map of message ID to message definitions
    msg_defs: std::collections::HashMap<u32, can_dbc::Message>,

    /// Map of message ID to per-signal enum/value-description mappings.
    enum_defs: std::collections::HashMap<u32, Vec<EnumDef>>,
}

impl Parser {
    /// Creates a new empty parser.
    ///
    /// Use [`add_from_dbc_file`](Parser::add_from_dbc_file) or
    /// [`add_from_str`](Parser::add_from_str) to add message definitions.
    ///
    /// # Example
    ///
    /// ```
    /// use can_decode::Parser;
    ///
    /// let parser = Parser::new();
    /// ```
    pub fn new() -> Self {
        Self {
            msg_defs: std::collections::HashMap::new(),
            enum_defs: std::collections::HashMap::new(),
        }
    }

    /// Creates a parser and loads definitions from a DBC file.
    ///
    /// This is a convenience method that combines [`new`](Parser::new) and
    /// [`add_from_str`](Parser::add_from_str).
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the DBC file
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or parsed.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use can_decode::Parser;
    /// use std::path::Path;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let parser = Parser::from_dbc_file(Path::new("my_database.dbc"))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_dbc_file(path: &std::path::Path) -> Result<Self, Box<dyn std::error::Error>> {
        let mut parser = Self::new();
        parser.add_from_dbc_file(path)?;
        Ok(parser)
    }

    /// Adds message and enum/value-description definitions from a DBC string.
    ///
    /// This method parses DBC content from a string slice and adds all message
    /// definitions to the parser. If a message ID already exists, it will be
    /// overwritten and a warning will be logged. Signal value descriptions
    /// (enumerations) are also captured for enum decoding.
    ///
    /// # Arguments
    ///
    /// * `buffer` - String slice containing the full DBC file contents
    ///
    /// # Errors
    ///
    /// Returns an error if the DBC content cannot be parsed.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use can_decode::Parser;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let dbc_content = "VERSION \"\"..."; // DBC file content as &str
    /// let mut parser = Parser::new();
    /// parser.add_from_str(dbc_content)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_from_str(&mut self, buffer: &str) -> Result<(), Box<dyn std::error::Error>> {
        let dbc = can_dbc::Dbc::try_from(buffer).map_err(|e| {
            log::error!("Failed to parse DBC: {:?}", e);
            format!("{:?}", e)
        })?;
        for msg_def in dbc.messages {
            let msg_id = msg_def.id.raw();
            if self.msg_defs.contains_key(&msg_id) {
                log::warn!(
                    "Duplicate message ID {msg_id:#X} ({}). Overwriting existing definition.",
                    msg_def.name
                );
            }
            self.msg_defs.insert(msg_id, msg_def.clone());
        }
        for val_desc in dbc.value_descriptions {
            match val_desc {
                can_dbc::ValueDescription::Signal {
                    message_id,
                    name,
                    value_descriptions,
                } => {
                    let msg_id = message_id.raw();
                    let enum_def = EnumDef {
                        signal_name: name.clone(),
                        enum_map: value_descriptions
                            .iter()
                            .map(|vd| (vd.id, vd.description.clone()))
                            .collect(),
                    };
                    let entry = self.enum_defs.entry(msg_id).or_default();
                    if let Some(existing) = entry
                        .iter_mut()
                        .find(|e| e.signal_name == enum_def.signal_name)
                    {
                        *existing = enum_def;
                        log::warn!(
                            "Duplicate value description for signal '{}' in message ID {:#X}. \
                            Overwriting existing enum definition.",
                            name,
                            msg_id
                        );
                    } else {
                        entry.push(enum_def);
                    }
                }
                can_dbc::ValueDescription::EnvironmentVariable { .. } => {}
            }
        }
        Ok(())
    }

    /// Adds message definitions from a DBC file.
    ///
    /// Reads and parses a DBC file from disk, adding all message definitions
    /// to the parser. Multiple DBC files can be loaded to combine definitions
    /// from different sources.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the DBC file
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or parsed.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use can_decode::Parser;
    /// use std::path::Path;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let mut parser = Parser::new();
    /// parser.add_from_dbc_file(Path::new("vehicle.dbc"))?;
    /// parser.add_from_dbc_file(Path::new("diagnostics.dbc"))?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_from_dbc_file(
        &mut self,
        path: &std::path::Path,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let buffer = std::fs::read(path)?;
        let s = String::from_utf8(buffer)?;
        self.add_from_str(&s)?;
        Ok(())
    }

    /// Decodes a raw CAN message into structured data.
    ///
    /// Takes a CAN message ID and raw data bytes, then decodes all signals
    /// according to the DBC definitions. Each signal is extracted, scaled,
    /// and converted to its physical value or enum label (if defined).
    ///
    /// # Arguments
    ///
    /// * `msg_id` - The CAN message identifier
    /// * `data` - The raw message data bytes (typically 0-8 bytes for standard CAN)
    ///
    /// # Returns
    ///
    /// Returns `Some(DecodedMessage)` if the message ID is known, or `None` if
    /// the message ID is not found in the loaded DBC definitions.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use can_decode::Parser;
    /// use std::path::Path;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let parser = Parser::from_dbc_file(Path::new("my_database.dbc"))?;
    ///
    /// let msg_id = 0x123;
    /// let data = [0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0];
    ///
    /// if let Some(decoded) = parser.decode_msg(msg_id, &data) {
    ///     println!("Message: {} (ID: {:#X})", decoded.name, decoded.msg_id);
    ///     for (name, signal) in &decoded.signals {
    ///         println!("  {}: {:?} {}", name, signal.value, signal.unit);
    ///     }
    /// } else {
    ///     println!("Unknown message ID: {:#X}", msg_id);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn decode_msg(&self, msg_id: u32, data: &[u8]) -> Option<DecodedMessage> {
        // Grab msg metadata and then for every signal in the message, decode it and add
        // to the decoded message
        let msg_def = self.msg_defs.get(&msg_id)?;
        let is_extended = matches!(msg_def.id, can_dbc::MessageId::Extended(_));
        let tx_node = match &msg_def.transmitter {
            can_dbc::Transmitter::NodeName(name) => name.clone(),
            can_dbc::Transmitter::VectorXXX => "Unknown".to_string(),
        };
        let mut decoded_signals = SignalMap::new();

        for signal_def in &msg_def.signals {
            match self.decode_signal(msg_id, signal_def, data) {
                Some(decoded_signal) => {
                    decoded_signals.insert(decoded_signal.name.to_string(), decoded_signal);
                }
                _ => {
                    log::error!(
                        "Failed to decode signal {} from message {}",
                        signal_def.name,
                        msg_def.name
                    );
                    return None;
                }
            }
        }

        Some(DecodedMessage {
            name: msg_def.name.clone(),
            msg_id,
            is_extended,
            tx_node,
            signals: decoded_signals,
        })
    }

    /// Decodes a single signal from raw CAN data.
    ///
    /// Extracts the raw bits for a signal, converts to signed/unsigned as needed,
    /// and then either resolves a DBC enum label or applies scaling/offset to
    /// produce a numeric physical value.
    fn decode_signal(
        &self,
        msg_id: u32,
        signal_def: &can_dbc::Signal,
        data: &[u8],
    ) -> Option<DecodedSignal> {
        // Extract raw value based on byte order and signal properties
        let raw_value = self.extract_signal_value(
            data,
            signal_def.start_bit as usize,
            signal_def.size as usize,
            signal_def.byte_order,
        )?;

        // Convert to signed if needed
        let raw_value_with_sign = if signal_def.value_type == can_dbc::ValueType::Signed {
            // Convert to signed based on signal size
            let max_unsigned = low_bits_mask!(signal_def.size as usize, u64);
            let sign_bit = 1u64 << (signal_def.size - 1);

            if raw_value & sign_bit != 0 {
                // Negative number - extend sign
                (raw_value | (!max_unsigned)) as i64
            } else {
                raw_value as i64
            }
        } else {
            raw_value as i64
        };

        // Check if this signal has an enum definition
        let enum_name = self
            .enum_defs
            .get(&msg_id)
            .and_then(|enums| {
                enums
                    .iter()
                    .find(|e| e.signal_name == signal_def.name)
                    .and_then(|e| e.enum_map.get(&raw_value_with_sign))
            })
            .cloned();

        if let Some(enum_str) = enum_name {
            Some(DecodedSignal {
                name: signal_def.name.clone(),
                value: DecodedSignalValue::Enum(raw_value_with_sign, enum_str),
                unit: signal_def.unit.clone(),
            })
        } else {
            // Apply scaling
            let scaled_value = raw_value_with_sign as f64 * signal_def.factor + signal_def.offset;

            Some(DecodedSignal {
                name: signal_def.name.clone(),
                value: DecodedSignalValue::Numeric(scaled_value),
                unit: signal_def.unit.clone(),
            })
        }
    }

    /// Extracts raw signal bits from CAN data.
    ///
    /// Handles both little-endian and big-endian byte ordering according to
    /// the signal definition.
    fn extract_signal_value(
        &self,
        data: &[u8],
        start_bit: usize,
        size: usize,
        byte_order: can_dbc::ByteOrder,
    ) -> Option<u64> {
        if data.is_empty() || size == 0 {
            return None;
        }

        let mut result = 0u64;

        match byte_order {
            can_dbc::ByteOrder::LittleEndian => {
                let start_byte = start_bit / 8;
                let start_bit_in_byte = start_bit % 8;

                let mut remaining_bits = size;
                let mut current_byte = start_byte;
                let mut bit_offset = start_bit_in_byte;

                while remaining_bits > 0 {
                    if current_byte >= data.len() {
                        // Out of bounds: should not be considered a successful decode
                        return None;
                    }

                    let bits_in_this_byte = std::cmp::min(remaining_bits, 8 - bit_offset);
                    let mask = low_bits_mask!(bits_in_this_byte, u64) << bit_offset;
                    let byte_value = ((data[current_byte] as u64) & mask) >> bit_offset;

                    result |= byte_value << (size - remaining_bits);

                    remaining_bits -= bits_in_this_byte;
                    current_byte += 1;
                    bit_offset = 0;
                }
            }
            can_dbc::ByteOrder::BigEndian => {
                // start_bit is the MSB position in DBC sawtooth numbering
                // byte_idx = start_bit / 8, bit_in_byte = start_bit % 8 (counts from LSB of byte)
                // Actual bit position within the byte = bit_in_byte (7=MSB, 0=LSB)

                let start_byte = start_bit / 8;
                let start_bit_in_byte = start_bit % 8; // Physical bit index

                let mut byte_idx = start_byte;
                let mut bit_in_byte = start_bit_in_byte as i32; // Counts down within byte

                for _i in 0..size {
                    if byte_idx >= data.len() {
                        // Out of bounds: should not be considered a successful decode
                        return None;
                    }

                    let bit_val = (data[byte_idx] >> bit_in_byte) & 1;
                    result = (result << 1) | (bit_val as u64);

                    bit_in_byte -= 1;
                    if bit_in_byte < 0 {
                        bit_in_byte = 7;
                        byte_idx += 1;
                    }
                }
            }
        }

        Some(result)
    }

    /// Encodes a CAN message from signal values into raw bytes.
    ///
    /// Takes a message ID and a map of signal names to their physical values,
    /// then encodes them according to the DBC definitions into raw CAN data bytes.
    /// Applies inverse scaling (offset and factor) and packs bits according to
    /// the signal's byte order and position. Applies scaling factors.
    ///
    /// # Arguments
    ///
    /// * `msg_id` - The CAN message identifier
    /// * `signal_values` - Map of signal names to their physical values
    ///
    /// # Returns
    ///
    /// Returns `Some(Vec<u8>)` containing the encoded message data, or `None` if
    /// the message ID is not found in the loaded DBC definitions or encoding fails.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use can_decode::Parser;
    /// use std::path::Path;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let parser = Parser::from_dbc_file(Path::new("my_database.dbc"))?;
    ///
    /// let signal_values = HashMap::from([
    ///     ("EngineSpeed".to_string(), 2500.0),
    ///     ("ThrottlePosition".to_string(), 45.5),
    /// ]);
    ///
    /// if let Some(data) = parser.encode_msg(0x123, &signal_values) {
    ///     println!("Encoded data: {:02X?}", data);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn encode_msg(
        &self,
        msg_id: u32,
        signal_values: &std::collections::HashMap<String, f64>,
    ) -> Option<Vec<u8>> {
        let msg_def = self.msg_defs.get(&msg_id)?;

        let msg_size = msg_def.size as usize;
        let mut data = vec![0u8; msg_size];

        for signal_def in &msg_def.signals {
            let physical_value = match signal_values.get(&signal_def.name) {
                Some(&v) => v,
                _ => {
                    log::error!(
                        "Signal {} not provided for message {} during encoding",
                        signal_def.name,
                        msg_def.name
                    );
                    return None;
                }
            };

            // encode_signal() modifies the data buffer in place
            if self
                .encode_signal(signal_def, physical_value, &mut data)
                .is_none()
            {
                log::error!(
                    "Failed to encode signal {} for message {}",
                    signal_def.name,
                    msg_def.name
                );
                return None;
            }
        }

        Some(data)
    }

    /// Encodes a CAN message by message name instead of ID.
    ///
    /// Looks up the message by name and then encode it. This is slower as it
    /// requires searching through all loaded messages. Applies scaling factors.
    ///
    /// # Arguments
    ///
    /// * `msg_name` - The name of the message as defined in the DBC file
    /// * `signal_values` - Map of signal names to their physical values
    ///
    /// # Returns
    ///
    /// Returns `Some((msg_id, data))` containing the message ID and encoded data,
    /// or `None` if the message name is not found or encoding fails.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use can_decode::Parser;
    /// use std::path::Path;
    /// use std::collections::HashMap;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let parser = Parser::from_dbc_file(Path::new("my_database.dbc"))?;
    ///
    /// let signal_values = HashMap::from([
    ///     ("EngineSpeed".to_string(), 2500.0),
    ///     ("ThrottlePosition".to_string(), 45.5),
    /// ]);
    ///
    /// if let Some((msg_id, data)) = parser.encode_msg_by_name("EngineData", &signal_values) {
    ///     println!("Message ID: {:#X}, Data: {:02X?}", msg_id, data);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn encode_msg_by_name(
        &self,
        msg_name: &str,
        signal_values: &std::collections::HashMap<String, f64>,
    ) -> Option<(u32, Vec<u8>)> {
        let (msg_id, _msg_def) = self
            .msg_defs
            .iter()
            .find(|(_id, msg)| msg.name == msg_name)?;

        let data = self.encode_msg(*msg_id, signal_values)?;
        Some((*msg_id, data))
    }

    /// Encodes a single signal into raw CAN data.
    ///
    /// Applies inverse scaling (subtracts offset, divides by factor), converts to
    /// the appropriate integer representation, and packs the bits into the data buffer.
    fn encode_signal(
        &self,
        signal_def: &can_dbc::Signal,
        physical_value: f64,
        data: &mut [u8],
    ) -> Option<()> {
        // Apply inverse scaling: raw = (physical - offset) / factor
        let raw_value = (physical_value - signal_def.offset) / signal_def.factor;

        // Convert to integer and handle signed/unsigned
        let raw_int = if signal_def.value_type == can_dbc::ValueType::Signed {
            // Convert signed physical value to the integer representation
            // then to the unsigned bit pattern (two's complement).
            let signed_val = raw_value.round() as i64;
            // For an N-bit signed value the allowed signed range is
            // -(1 << (N-1)) .. (1 << (N-1)) - 1
            let max_value = (1i64 << (signal_def.size - 1)) - 1;
            let min_value = -(1i64 << (signal_def.size - 1));

            // Clamp to valid signed range
            let clamped = signed_val.max(min_value).min(max_value);

            // Convert to unsigned representation (two's complement)
            if clamped < 0 {
                let mask = low_bits_mask!(signal_def.size as usize, u64);
                (clamped as u64) & mask
            } else {
                clamped as u64
            }
        } else {
            // Unsigned value
            let unsigned_val = raw_value.round() as u64;
            let max_value = low_bits_mask!(signal_def.size as usize, u64);

            // Clamp to valid range
            unsigned_val.min(max_value)
        };

        // Insert the value into the data buffer
        self.insert_signal_value(
            data,
            signal_def.start_bit as usize,
            signal_def.size as usize,
            signal_def.byte_order,
            raw_int,
        )
    }

    /// Inserts raw signal bits into CAN data.
    ///
    /// Handles both little-endian and big-endian byte ordering according to
    /// the signal definition.
    fn insert_signal_value(
        &self,
        data: &mut [u8],
        start_bit: usize,
        size: usize,
        byte_order: can_dbc::ByteOrder,
        value: u64,
    ) -> Option<()> {
        if data.is_empty() || size == 0 {
            return None;
        }

        let total_bits = data.len() * 8;
        if start_bit + size > total_bits {
            return None;
        }

        match byte_order {
            can_dbc::ByteOrder::LittleEndian => {
                let start_byte = start_bit / 8;
                let start_bit_in_byte = start_bit % 8;

                let mut remaining_bits = size;
                let mut current_byte = start_byte;
                let mut bit_offset = start_bit_in_byte;
                let mut value_offset = 0;

                while remaining_bits > 0 && current_byte < data.len() {
                    let bits_in_this_byte = std::cmp::min(remaining_bits, 8 - bit_offset);
                    let mask = low_bits_mask!(bits_in_this_byte, u8) << bit_offset;

                    // Extract bits from value
                    let value_mask = low_bits_mask!(bits_in_this_byte, u64);
                    let value_bits = ((value >> value_offset) & value_mask) as u8;

                    // Clear the bits in the data byte and set new bits
                    data[current_byte] =
                        (data[current_byte] & !mask) | ((value_bits << bit_offset) & mask);

                    remaining_bits -= bits_in_this_byte;
                    value_offset += bits_in_this_byte;
                    current_byte += 1;
                    bit_offset = 0;
                }
            }
            can_dbc::ByteOrder::BigEndian => {
                let start_byte = start_bit / 8;
                let start_bit_in_byte = start_bit % 8;

                let mut byte_idx = start_byte;
                let mut bit_in_byte = start_bit_in_byte as i32;

                for i in 0..size {
                    if byte_idx >= data.len() {
                        return None;
                    }

                    let bit_val = ((value >> (size - 1 - i)) & 1) as u8;
                    let mask = 1u8 << bit_in_byte;
                    data[byte_idx] = (data[byte_idx] & !mask) | (bit_val << bit_in_byte);

                    bit_in_byte -= 1;
                    if bit_in_byte < 0 {
                        bit_in_byte = 7;
                        byte_idx += 1;
                    }
                }
            }
        }

        Some(())
    }

    /// Returns all signal definitions for a given message ID.
    ///
    /// # Arguments
    ///
    /// * `msg_id` - The CAN message identifier
    ///
    /// # Returns
    ///
    /// Returns `Some(Vec<Signal>)` if the message ID is known, or `None` otherwise.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use can_decode::Parser;
    /// use std::path::Path;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let parser = Parser::from_dbc_file(Path::new("my_database.dbc"))?;
    ///
    /// if let Some(signals) = parser.signal_defs(0x123) {
    ///     for signal in signals {
    ///         println!("Signal: {}", signal.name);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn signal_defs(&self, msg_id: u32) -> Option<Vec<can_dbc::Signal>> {
        let msg_def = self.msg_defs.get(&msg_id)?;
        Some(msg_def.signals.to_vec())
    }

    /// Returns all loaded message definitions.
    ///
    /// # Returns
    ///
    /// A vector containing all message definitions that have been loaded
    /// from DBC files.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use can_decode::Parser;
    /// use std::path::Path;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let parser = Parser::from_dbc_file(Path::new("my_database.dbc"))?;
    ///
    /// for msg in parser.msg_defs() {
    ///     println!("Message: {} (ID: {:#X})", msg.name,
    ///              match msg.id {
    ///                  can_dbc::MessageId::Standard(id) => id as u32,
    ///                  can_dbc::MessageId::Extended(id) => id,
    ///              });
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn msg_defs(&self) -> Vec<can_dbc::Message> {
        self.msg_defs.values().cloned().collect()
    }

    /// Returns the message definition for a given message ID.
    ///
    /// # Arguments
    ///
    /// * `msg_id` - The CAN message identifier
    ///
    /// # Returns
    ///
    /// Returns a reference to the message definition if found, or `None` if
    /// the message ID is not known.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use can_decode::Parser;
    /// use std::path::Path;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let parser = Parser::from_dbc_file(Path::new("my_database.dbc"))?;
    ///
    /// if let Some(msg_def) = parser.msg_def(0x123) {
    ///     println!("Message: {}", msg_def.name);
    /// }
    /// # Ok(())
    /// # }
    ///
    pub fn msg_def(&self, msg_id: u32) -> Option<&can_dbc::Message> {
        self.msg_defs.get(&msg_id)
    }

    /// Clears all loaded message definitions.
    ///
    /// After calling this method, the parser will have no message definitions
    /// or enum/value-description mappings and will need to reload DBC files.
    ///
    /// # Example
    ///
    /// ```
    /// use can_decode::Parser;
    ///
    /// let mut parser = Parser::new();
    /// parser.clear();
    /// ```
    pub fn clear(&mut self) {
        self.msg_defs.clear();
        self.enum_defs.clear();
    }
}

impl Default for Parser {
    fn default() -> Self {
        Self::new()
    }
}