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
use ::dbc;
use std::collections::HashMap;
/// Trait for converting `Entry` values into a library's own entries.
pub trait FromDbc {
type Err;
/// Converts an `Entity` value from scratch.
fn from_entry(entry: dbc::Entry) -> Result<Self, Self::Err>
where
Self: Sized;
/// Merges the given `Entity` with a `mut` version of the library's entity. Useful for when
/// multiple `Entry` types contribute to various attributes within the same destination.
fn merge_entry(&mut self, entry: dbc::Entry) -> Result<(), Self::Err>;
}
type SignalAttribute = String;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Signal {
/// e.g., {"SPN", "190"}
/// BA_ "SPN" SG_ 2364540158 EngSpeed 190;
/// BA_ "SigType" SG_ 2364540158 EngSpeed 1;
attributes: HashMap<String, SignalAttribute>,
/// e.g., "Actual engine speed which is calculated over a minimum
/// crankshaft angle of 720 degrees divided by the number of cylinders."
description: Option<String>,
/// e.g, SG_ EngSpeed : 24|16@1+ (0.125,0) [0|8031.875] "rpm" Vector__XXX
definition: Option<dbc::SignalDefinition>, // FIXME: hate that this has to be Option
/// Only applicable for enum types
/// e.g., VAL_ 2364540158 ActlEngPrcntTrqueHighResolution 8 "1111NotAvailable" 7 "0875" 1 "0125" 0 "0000" ;
value_definition: Option<dbc::ValueDefinition>,
}
type MessageAttribute = String;
#[derive(Clone, Debug, Default)]
pub struct Message {
name: String,
message_len: u32,
sending_node: String,
/// e.g., BA_ "VFrameFormat" BO_ 2364540158 3;
attributes: HashMap<String, MessageAttribute>,
/// e.g., CM_ BO_ 2364540158 "Electronic Engine Controller 1";
description: Option<String>,
signals: HashMap<String, Signal>,
}
impl FromDbc for Message {
type Err = ();
fn from_entry(entry: dbc::Entry) -> Result<Self, Self::Err> where
Self: Sized {
use dbc::Entry;
match entry {
Entry::MessageDefinition(dbc::MessageDefinition {
id: _id,
name,
message_len,
sending_node,
}) => {
Ok(Message {
name: name,
message_len: message_len,
sending_node: sending_node,
.. Default::default()
})
},
Entry::MessageDescription(dbc::MessageDescription {
id: _id,
signal_name: _signal_name,
description,
}) => {
Ok(Message {
description: Some(description),
.. Default::default()
})
},
Entry::MessageAttribute(dbc::MessageAttribute {
name,
signal_name: _signal_name,
id: _id,
value,
}) => {
let mut attributes = HashMap::new();
attributes.insert(name, value);
Ok(Message {
attributes: attributes,
.. Default::default()
})
},
// TODO: Need to propogate Signal FromDbc in here..maybe, or just search in DbcLibrary
_ => Err(())
}
}
fn merge_entry(&mut self, entry: dbc::Entry) -> Result<(), Self::Err> {
use dbc::Entry;
match entry {
Entry::MessageDefinition(
dbc::MessageDefinition {
id: _id,
name,
message_len,
sending_node,
}) => {
self.name = name;
self.message_len = message_len;
self.sending_node = sending_node;
Ok(())
},
Entry::MessageDescription(
dbc::MessageDescription {
id: _id,
signal_name: _signal_name,
description,
}) => {
self.description = Some(description);
Ok(())
},
Entry::MessageAttribute(
dbc::MessageAttribute {
name,
signal_name: _signal_name,
id: _id,
value,
}) => {
if let Some(_previous_value) = self.attributes.insert(name, value) {
// TODO: Warn that we somehow already had an existing entry
}
Ok(())
},
Entry::SignalDefinition(inner) => {
if self.signals.contains_key(&inner.name) {
(*self.signals.get_mut(&inner.name).expect("Already checked for Signal key"))
.merge_entry(Entry::SignalDefinition(inner))
} else {
let name = inner.name.clone();
let signal = Signal::from_entry(Entry::SignalDefinition(inner))?;
self.signals.insert(name, signal);
Ok(())
}
},
Entry::SignalDescription(inner) => {
if self.signals.contains_key(&inner.signal_name) {
(*self.signals.get_mut(&inner.signal_name).expect("Already checked for Signal key"))
.merge_entry(Entry::SignalDescription(inner))
} else {
let name = inner.signal_name.clone();
let signal = Signal::from_entry(Entry::SignalDescription(inner))?;
self.signals.insert(name, signal);
Ok(())
}
},
Entry::SignalAttribute(inner) => {
if self.signals.contains_key(&inner.signal_name) {
(*self.signals.get_mut(&inner.signal_name).expect("Already checked for Signal key"))
.merge_entry(Entry::SignalAttribute(inner))
} else {
let name = inner.signal_name.clone();
let signal = Signal::from_entry(Entry::SignalAttribute(inner))?;
self.signals.insert(name, signal);
Ok(())
}
},
_ => Err(())
}
}
}
impl FromDbc for Signal {
type Err = ();
fn from_entry(entry: dbc::Entry) -> Result<Self, Self::Err> where
Self: Sized {
use dbc::Entry;
match entry {
Entry::SignalDefinition(definition) => {
Ok(Signal {
attributes: HashMap::new(),
description: None,
definition: Some(definition),
value_definition: None,
})
},
Entry::SignalDescription(
dbc::SignalDescription {
id: _id,
signal_name: _signal_name,
description,
}) => {
Ok(Signal {
attributes: HashMap::new(),
description: Some(description),
definition: None,
value_definition: None,
})
},
Entry::SignalAttribute(dbc::SignalAttribute {
name,
id: _id,
signal_name: _signal_name,
value,
}) => {
let mut attributes = HashMap::new();
attributes.insert(name, value);
Ok(Signal {
attributes,
description: None,
definition: None,
value_definition: None
})
},
_ => Err(()),
}
}
fn merge_entry(&mut self, entry: dbc::Entry) -> Result<(), Self::Err> {
use dbc::Entry;
match entry {
Entry::SignalDefinition(definition) => {
self.definition = Some(definition);
Ok(())
},
Entry::SignalDescription(
dbc::SignalDescription {
id: _id,
signal_name: _signal_name,
description,
}) => {
self.description = Some(description);
Ok(())
},
Entry::SignalAttribute(dbc::SignalAttribute {
name,
id: _id,
signal_name: _signal_name,
value,
}) => {
if let Some(_previous_value) = self.attributes.insert(name, value) {
// TODO: Warn that we somehow already had an existing entry
}
Ok(())
},
_ => Err(()),
}
}
}
/// A struct that represents a CANdb file, and provides APIs for interacting
/// with CAN messages and signals.
#[derive(Clone, Debug, Default)]
pub struct DbcLibrary {
last_id: Option<u32>,
messages: HashMap<u32, Message>,
}
use std::fs::File;
use std::io;
use std::io::prelude::*;
use encoding::{DecoderTrap, Encoding};
use encoding::all::ISO_8859_1;
use std::path::Path;
use super::{nom as nomparse, *};
use nom;
impl DbcLibrary {
/// Creates a new `DbcLibrary` instance given an existing lookup table.
pub fn new(messages: HashMap<u32, Message>) -> Self {
DbcLibrary {
last_id: None,
messages,
}
}
/// Convenience function for loading an entire DBC file into a returned `DbcLibrary`. This
/// function ignores unparseable lines as well as `Entry` variants which don't apply to
/// `DbcLibrary` (such as `Entry::Version`). Fails on `io::Error`.
///
/// # Example
///
/// ```rust
/// use canparse::dbc::DbcLibrary;
///
/// let lib: DbcLibrary = DbcLibrary::from_dbc_file("./tests/data/sample.dbc").unwrap();
///
/// ```
pub fn from_dbc_file<P>(path: P) -> io::Result<Self>
where
P: AsRef<Path>,
{
Self::from_encoded_dbc_file(path, ISO_8859_1)
}
#[doc(hidden)]
pub fn from_encoded_dbc_file<P, E>(path: P, encoding: &E) -> io::Result<Self>
where
P: AsRef<Path>,
E: Encoding,
{
let mut lib = DbcLibrary::default();
let data = File::open(path)
.and_then(|mut f| {
let mut contents: Vec<u8> = Vec::new();
f.read_to_end(&mut contents).map(|_bytes_read| contents)
})
.and_then(|mut contents| {
encoding
.decode(contents.as_slice(), DecoderTrap::Replace)
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
})?;
let mut i = data.as_str();
while !i.is_empty() {
match nomparse::entry(i) {
Ok((new_i, entry)) => {
if let Err(_e) = lib.add_entry(entry) {
// TODO: Handle add_entry error
}
i = new_i;
}
// FIXME: handling `IResult::Err`s could be better
Err(nom::Err::Incomplete(_)) => {
break;
}
Err(_) => {
i = &i[1..];
}
}
}
Ok(lib)
}
}
impl DbcLibrary {
pub fn add_entry(&mut self, entry: Entry) -> Result<(), String> {
let _id: u32 = *match entry {
Entry::MessageDefinition(dbc::MessageDefinition { ref id, .. }) => id,
Entry::MessageDescription(dbc::MessageDescription { ref id, .. }) => id,
Entry::MessageAttribute(dbc::MessageAttribute { ref id, .. }) => id,
Entry::SignalDefinition(..) => {
// no id, and by definition must follow MessageDefinition
if let Some(last_id) = self.last_id.as_ref() {
last_id
} else {
return Err("Tried to add SignalDefinition without last ID.".to_string());
}
}
Entry::SignalDescription(dbc::SignalDescription { ref id, .. }) => id,
Entry::SignalAttribute(dbc::SignalAttribute { ref id, .. }) => id,
_ => {
return Err(format!("Unsupported entry: {}.", entry).to_string());
}
};
self.messages.entry(_id)
.and_modify(|cur_entry| cur_entry.merge_entry(entry.clone())
.unwrap_or_else(|_| panic!("Already checked for Signal key: {:?}", entry))
).or_insert_with(|| Message::from_entry(entry.clone())
.unwrap_or_else(|_| panic!("Some inserted a Signal for empty key: {:?}", _id)));
self.last_id = Some(_id);
Ok(())
}
}
#[cfg(test)]
mod tests {
use dbc::{Entry, SignalDefinition, Version};
use super::{DbcLibrary};
lazy_static! {
static ref DBCLIB_EMPTY: DbcLibrary = DbcLibrary::default();
static ref DBCLIB_ONE: DbcLibrary = DbcLibrary::from_dbc_file("./tests/data/sample.dbc")
.expect("Failed to create DbcLibrary from file");
static ref SIGNALDEF: SignalDefinition = SignalDefinition {
name: "Engine_Speed".to_string(),
start_bit: 24,
bit_len: 16,
little_endian: true,
signed: false,
scale: 0.125,
offset: 0.0,
min_value: 0.0,
max_value: 8031.88,
units: "rpm".to_string(),
receiving_node: "Vector__XXX".to_string()
};
static ref SIGNALDEF_BE: SignalDefinition = {
let mut _spndef = SIGNALDEF.clone();
_spndef.little_endian = false;
_spndef
};
static ref MSG: [u8; 8] = [0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88];
static ref MSG_BE: [u8; 8] = [0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11];
}
#[test]
fn default_pgnlibrary() {
assert_eq!(DBCLIB_EMPTY.messages.len(), 0);
}
#[test]
fn get_spndefinition() {
assert_eq!(
*DBCLIB_ONE
.messages
.get(&2364539904)
.expect("failed to get DbcDefinition from DbcLibrary")
.signals
.get("Engine_Speed")
.expect("failed to get Signal from DbcDefinition")
.definition.as_ref()
.expect("failed to get SignalDefinition from DbcDefinition")
,*SIGNALDEF
);
}
#[test]
fn unsupported_entry() {
let mut dbclib: DbcLibrary = DbcLibrary::default();
let unsupported = Entry::Version(Version("Don't care about version entry".to_string()));
let res = dbclib.add_entry(unsupported);
assert!(res.is_err(), "Unsupported entry: Version".to_string());
}
}