-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogging.rs
438 lines (380 loc) · 12.1 KB
/
logging.rs
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
//! Module contains logfile types used to access the underlying CAN-bus data.
use crate::data::CANRead;
use std::fs::File;
use std::io;
use std::io::{BufRead, BufReader, Lines};
use std::iter::{IntoIterator, Iterator};
use std::ops::Div;
use std::path::Path;
use std::str::FromStr;
///
///
/// # Format
/// ```bash
/// can0 00000042 [0]
/// can0 1FF [1] 01
/// vcan0 00001337 [8] 01 02 03 04 05 06 07 08
/// ```
/// # Example
/// ```no_run
/// use cantools::logging::CANDump;
/// let file = CANDump::open("raw_file");
/// ```
pub struct CANDump {
file: File,
}
impl CANDump {
pub fn open<P>(path: P) -> io::Result<CANDump>
where
P: AsRef<Path>,
{
let file = File::open(path)?;
Ok(CANDump { file })
}
pub fn into_inner(self) -> File {
self.file
}
}
#[derive(Debug, PartialEq)]
pub struct CANDumpEntry {
interface: String,
can_id: u32,
data: Vec<u8>,
}
impl CANRead for CANDumpEntry {
fn data(&self) -> &[u8] {
&self.data
}
fn dlc(&self) -> usize {
self.data.len()
}
}
#[derive(Debug, PartialEq)]
pub enum CANDumpEntryConstructionError {
EmptyInterface,
}
impl CANDumpEntry {
pub fn new(
interface: &str,
can_id: u32,
data: Vec<u8>,
) -> Result<Self, CANDumpEntryConstructionError> {
if interface.is_empty() {
Err(CANDumpEntryConstructionError::EmptyInterface)
} else {
Ok(CANDumpEntry {
interface: String::from(interface),
can_id,
data,
})
}
}
}
#[derive(Debug, PartialEq)]
pub enum CANDumpEntryParseError {
MissingInterfaceData,
MissingCanIdData,
MissingDlcData,
ParseDlcError,
ParseCanIdError,
ParseCanDataError,
DlcDataMismatch,
ConstructionError(CANDumpEntryConstructionError),
}
impl FromStr for CANDumpEntry {
type Err = CANDumpEntryParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let splits = s.split(' ').collect::<Vec<_>>();
let interface = match splits.get(0).copied() {
Some(interface) => interface,
None => return Err(CANDumpEntryParseError::MissingInterfaceData),
};
let can_id = match splits.get(1).copied().map(|e| u32::from_str_radix(e, 16)) {
Some(Ok(can_id)) => can_id,
_ => return Err(CANDumpEntryParseError::MissingCanIdData),
};
let dlc_string = match splits.get(2).copied() {
Some(dlc_string) => dlc_string,
None => return Err(CANDumpEntryParseError::MissingDlcData),
};
let dlc = match dlc_string[1..dlc_string.len() - 1].parse::<usize>() {
Ok(dlc) => dlc,
Err(_) => return Err(CANDumpEntryParseError::ParseDlcError),
};
let mut data = Vec::new();
for entry in splits.into_iter().skip(3) {
match u8::from_str_radix(entry, 16) {
Ok(value) => data.push(value),
_ => return Err(CANDumpEntryParseError::ParseCanDataError),
}
}
if dlc != data.len() {
return Err(CANDumpEntryParseError::DlcDataMismatch);
}
match CANDumpEntry::new(interface, can_id, data) {
Ok(entry) => Ok(entry),
Err(err) => Err(CANDumpEntryParseError::ConstructionError(err)),
}
}
}
impl ToString for CANDumpEntry {
fn to_string(&self) -> String {
let data_string = self
.data
.iter()
.map(|x| format!("{:02X}", x))
.collect::<Vec<_>>()
.join(" ");
format!(
"{} {:08X} [{}] {}",
self.interface,
self.can_id,
self.data.len(),
data_string
)
}
}
pub struct CANDumpIterator {
lines: Lines<BufReader<File>>,
}
impl Iterator for CANDumpIterator {
type Item = CANDumpEntry;
fn next(&mut self) -> Option<Self::Item> {
loop {
let line = self.lines.next();
match line {
Some(Ok(line)) => match line.parse::<Self::Item>() {
Ok(entry) => return Some(entry),
Err(_) => continue,
},
Some(Err(_)) => continue,
None => return None,
}
}
}
}
impl IntoIterator for CANDump {
type Item = CANDumpEntry;
type IntoIter = CANDumpIterator;
fn into_iter(self) -> Self::IntoIter {
CANDumpIterator {
lines: io::BufReader::new(self.into_inner()).lines(),
}
}
}
pub struct CANDumpLog {
file: File,
}
impl CANDumpLog {
pub fn open<P>(path: P) -> io::Result<CANDumpLog>
where
P: AsRef<Path>,
{
let file = File::open(path)?;
Ok(CANDumpLog { file })
}
pub fn into_inner(self) -> File {
self.file
}
}
#[derive(Debug, PartialEq)]
pub struct CANDumpLogEntry {
timestamp: f64,
interface: String,
can_id: u32,
data: Vec<u8>,
flag: Option<u8>,
}
#[derive(Debug, PartialEq)]
pub enum CANDumpLogEntryConstructionError {
InvalidTimestamp,
EmptyInterface,
InvalidFlagValue,
}
impl CANDumpLogEntry {
pub fn new(
timestamp: f64,
interface: &str,
can_id: u32,
data: Vec<u8>,
flag: Option<u8>,
) -> Result<Self, CANDumpLogEntryConstructionError> {
if timestamp.is_nan() || timestamp.is_infinite() {
return Err(CANDumpLogEntryConstructionError::InvalidTimestamp);
}
if interface.is_empty() {
return Err(CANDumpLogEntryConstructionError::EmptyInterface);
}
if let Some(x) = flag {
if x > 0x0F {
return Err(CANDumpLogEntryConstructionError::InvalidFlagValue);
};
}
Ok(CANDumpLogEntry {
timestamp,
interface: String::from(interface),
can_id,
data,
flag,
})
}
}
#[derive(Debug, PartialEq)]
pub enum CANDumpLogEntryParseError {
MissingTimestampData,
ParseTimestampError,
MissingInterfaceData,
MissingCompoundCanData,
MissingCanIdData,
MissingCanData,
MissingFlagData,
ParseCanIdError,
ParseCanDataError,
ParseFlagError,
ConstructionError(CANDumpLogEntryConstructionError),
Unspecified,
}
impl FromStr for CANDumpLogEntry {
type Err = CANDumpLogEntryParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let splits = s.split(' ').take(3).collect::<Vec<_>>();
let timestamp = match splits.get(0).copied() {
Some(timestamp) => timestamp,
None => return Err(CANDumpLogEntryParseError::MissingTimestampData),
};
let timestamp = match timestamp[1..timestamp.len() - 1].parse::<f64>() {
Ok(timestamp) => timestamp,
Err(_) => return Err(CANDumpLogEntryParseError::ParseTimestampError),
};
let interface = match splits.get(1).copied() {
Some(interface) => interface,
None => return Err(CANDumpLogEntryParseError::MissingInterfaceData),
};
let can_data = match splits.get(2).copied() {
Some(can_data) => can_data,
None => return Err(CANDumpLogEntryParseError::MissingCompoundCanData),
};
let can_data_splits = can_data.split('#').take(3).collect::<Vec<_>>();
return match can_data_splits.len() {
2 => {
let can_id_string = match can_data_splits.get(0).copied() {
Some(can_id_string) => can_id_string,
None => return Err(CANDumpLogEntryParseError::MissingCanIdData),
};
let can_id = match u32::from_str_radix(can_id_string, 16) {
Ok(can_id) => can_id,
Err(_) => return Err(CANDumpLogEntryParseError::ParseCanIdError),
};
let data_string = match can_data_splits.get(1).copied() {
Some(data_string) => data_string,
None => return Err(CANDumpLogEntryParseError::MissingCanData),
};
let mut data = Vec::new();
for i in 0..data_string.len().div(2) {
match u8::from_str_radix(&data_string[2 * i..2 * i + 2], 16) {
Ok(value) => data.push(value),
Err(_) => return Err(CANDumpLogEntryParseError::ParseCanDataError),
};
}
match CANDumpLogEntry::new(timestamp, interface, can_id, data, None) {
Ok(entry) => Ok(entry),
Err(err) => Err(CANDumpLogEntryParseError::ConstructionError(err)),
}
}
3 => {
let can_id_string = match can_data_splits.get(0).copied() {
Some(can_id_string) => can_id_string,
None => return Err(CANDumpLogEntryParseError::MissingCanIdData),
};
let can_id = match u32::from_str_radix(can_id_string, 16) {
Ok(can_id) => can_id,
Err(_) => return Err(CANDumpLogEntryParseError::ParseCanIdError),
};
let data_string = match can_data_splits.get(2).copied() {
Some(data_string) => data_string,
None => return Err(CANDumpLogEntryParseError::MissingCanData),
};
let flag_string = match data_string.get(0..1) {
Some(flag_string) => flag_string,
None => return Err(CANDumpLogEntryParseError::MissingFlagData),
};
let flag = match u8::from_str_radix(flag_string, 16) {
Ok(flag) => flag,
Err(_) => return Err(CANDumpLogEntryParseError::ParseFlagError),
};
let mut data = Vec::new();
for i in 0..(data_string.len() - 1).div(2) {
match u8::from_str_radix(&data_string[2 * i + 1..2 * i + 2 + 1], 16) {
Ok(value) => data.push(value),
Err(_) => return Err(CANDumpLogEntryParseError::ParseCanDataError),
};
}
match CANDumpLogEntry::new(timestamp, interface, can_id, data, Some(flag)) {
Ok(entry) => Ok(entry),
Err(err) => Err(CANDumpLogEntryParseError::ConstructionError(err)),
}
}
_ => Err(CANDumpLogEntryParseError::Unspecified),
};
}
}
impl ToString for CANDumpLogEntry {
fn to_string(&self) -> String {
let data_string = self
.data
.iter()
.map(|x| format!("{:02X}", x))
.collect::<Vec<_>>()
.join("");
return match self.flag {
Some(flag) => {
format!(
"({}) {} {:08X}##{:1X}{}",
self.timestamp, self.interface, self.can_id, flag, data_string
)
}
None => {
format!(
"({}) {} {:08X}#{}",
self.timestamp, self.interface, self.can_id, data_string
)
}
};
}
}
impl CANRead for CANDumpLogEntry {
fn data(&self) -> &[u8] {
&self.data
}
fn dlc(&self) -> usize {
self.data.len()
}
}
pub struct CANDumpLogIterator {
lines: Lines<BufReader<File>>,
}
impl Iterator for CANDumpLogIterator {
type Item = CANDumpLogEntry;
fn next(&mut self) -> Option<Self::Item> {
loop {
let line = self.lines.next();
match line {
Some(Ok(line)) => match line.parse::<CANDumpLogEntry>() {
Ok(entry) => return Some(entry),
Err(_) => continue,
},
Some(Err(_)) => continue,
None => return None,
}
}
}
}
impl IntoIterator for CANDumpLog {
type Item = CANDumpLogEntry;
type IntoIter = CANDumpLogIterator;
fn into_iter(self) -> Self::IntoIter {
CANDumpLogIterator {
lines: io::BufReader::new(self.into_inner()).lines(),
}
}
}