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
use std::time;
use std::fmt;
use std::iter;
use crate::error::Result;
use itertools::Itertools;
#[cfg(feature = "j2534")]
pub mod j2534can;
#[cfg(feature = "j2534")]
pub use self::j2534can::J2534Can;
#[cfg(feature = "socketcan")]
pub mod socketcan;
#[cfg(feature = "socketcan")]
pub use self::socketcan::SocketCan;
#[derive(Debug)]
pub struct Message {
pub id: u32,
pub data: Vec<u8>,
}
impl Default for Message {
fn default() -> Message {
Message {
id: 0,
data: Vec::new(),
}
}
}
impl fmt::Display for Message {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[{:X}] {}", self.id, self.data.iter()
.map(|x| format!("{:X}", x))
.join(" "))?;
Ok(())
}
}
pub trait CanInterfaceIterator {
fn recv_iter(&self, timeout: time::Duration) -> RecvIterator;
}
pub trait CanInterface: CanInterfaceIterator {
fn send(&self, id: u32, message: &[u8]) -> Result<()>;
fn send_msg(&self, message: &Message) -> Result<()> {
self.send(message.id, &message.data)
}
fn recv(&self, timeout: time::Duration) -> Result<Message>;
}
impl<S: Sized + CanInterface> CanInterfaceIterator for S {
fn recv_iter(&self, timeout: time::Duration) -> RecvIterator {
RecvIterator {
interface: self,
timeout
}
}
}
pub struct RecvIterator<'a> {
interface: &'a CanInterface,
timeout: time::Duration,
}
impl<'a> iter::Iterator for RecvIterator<'a> {
type Item = Result<Message>;
fn next(&mut self) -> Option<Self::Item> {
Some(self.interface.recv(self.timeout))
}
}