summaryrefslogtreecommitdiff
path: root/src/canstream.rs
blob: 14517970835c5d00c46817b2b28262cb7ba4e2a0 (plain)
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
use std::io;
use std::os::unix::io::AsRawFd;

use mio::{Poll, PollOpt, Ready, Token};
use mio::event::Evented;
use mio::unix::EventedFd;

use socketcan::{CANFrame, CANSocket, CANSocketOpenError, ShouldRetry};

use tokio::reactor::PollEvented2;
use tokio::prelude::*;

pub struct EventableCANSocket {
    socket: CANSocket,
}

impl EventableCANSocket {
    fn new(socket: CANSocket) -> EventableCANSocket {
        socket.set_nonblocking(true).unwrap();
        EventableCANSocket { socket: socket }
    }

    pub fn from_interfacename(ifname: &str) -> Result<EventableCANSocket, CANSocketOpenError> {
        Ok(EventableCANSocket::new(CANSocket::open(ifname)?))
    }

    pub fn get_ref(&self) -> &CANSocket {
        &self.socket
    }
}

impl Evented for EventableCANSocket {
    fn register(
        &self,
        poll: &Poll,
        token: Token,
        interest: Ready,
        opts: PollOpt,
    ) -> io::Result<()> {
        EventedFd(&self.socket.as_raw_fd()).register(poll, token, interest, opts)
    }

    fn reregister(
        &self,
        poll: &Poll,
        token: Token,
        interest: Ready,
        opts: PollOpt,
    ) -> io::Result<()> {
        EventedFd(&self.socket.as_raw_fd()).reregister(poll, token, interest, opts)
    }

    fn deregister(&self, poll: &Poll) -> io::Result<()> {
        EventedFd(&self.socket.as_raw_fd()).deregister(poll)
    }
}

pub struct CANStream {
    socket: PollEvented2<EventableCANSocket>,
    flushed: bool,
    pending_frame: Option<CANFrame>,
}

impl CANStream {
    pub fn new(socket: EventableCANSocket) -> CANStream {
        let pollsock = PollEvented2::new(socket);
        CANStream {
            socket: pollsock,
            flushed: true,
            pending_frame: None,
        }
    }

    pub fn from_name(ifname: &str) -> Result<CANStream, CANSocketOpenError> {
        let sock = EventableCANSocket::from_interfacename(ifname)?;
        Ok(CANStream::new(sock))
    }
}

impl Stream for CANStream {
    type Item = CANFrame;
    type Error = io::Error;

    fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> {
        // We shouldn't be woken unless we're ready, but just in case, let's
        // ensure...

        let readiness = match self.socket.poll_read_ready(Ready::readable())? {
            Async::NotReady => return Ok(Async::NotReady),
            Async::Ready(r) => r,
        };

        if !readiness.is_readable() {
            return Ok(Async::NotReady);
        }

        // Okay, we're readable, so let's have a go at reading...
        let frame = match self.socket.get_ref().get_ref().read_frame() {
            Ok(f) => f,
            Err(e) => {
                if e.should_retry() {
                    return Ok(Async::NotReady);
                } else {
                    warn!("Unable to cope with error: {:?}", e);
                    return Err(e);
                }
            }
        };

        Ok(Async::Ready(Some(frame)))
    }
}

impl Sink for CANStream {
    type SinkItem = CANFrame;
    type SinkError = io::Error;

    fn start_send(
        &mut self,
        item: Self::SinkItem,
    ) -> Result<AsyncSink<Self::SinkItem>, Self::SinkError> {
        if !self.flushed {
            match self.poll_complete()? {
                Async::Ready(()) => {}
                Async::NotReady => return Ok(AsyncSink::NotReady(item)),
            }
        }
        self.pending_frame = Some(item);
        self.flushed = false;
        Ok(AsyncSink::Ready)
    }

    fn poll_complete(&mut self) -> Result<Async<()>, Self::SinkError> {
        if self.flushed {
            return Ok(Async::Ready(()));
        }

        let readiness = match self.socket.poll_write_ready()? {
            Async::NotReady => return Ok(Async::NotReady),
            Async::Ready(r) => r,
        };

        if !readiness.is_writable() {
            return Ok(Async::NotReady);
        }
        match self.socket
            .get_ref()
            .get_ref()
            .write_frame(&self.pending_frame.unwrap())
        {
            Ok(()) => {
                self.pending_frame = None;
            }
            Err(e) => {
                if !e.should_retry() {
                    return Err(e);
                }
            }
        }

        if self.pending_frame.is_none() {
            self.flushed = true;
            Ok(Async::Ready(()))
        } else {
            Ok(Async::NotReady)
        }
    }
}