summaryrefslogtreecommitdiff
path: root/src/isotp.rs
blob: c7d3d9c662dab85d09da0d4e522144b7c59e46fa (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
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
use socketcan::CANFrame;

use canstream::*;

use std::collections::{HashMap, VecDeque};

use std::cmp::min;

use std::io;

use tokio;
use tokio::prelude::*;

use futures::sync::mpsc;
use futures::stream::SplitStream;

const DEFAULT_BLOCKS: u8 = 16;

struct IncomingPacket {
    id: u16,
    remaining_bytes: u16,
    content: Vec<u8>,
    block_size: u8,
    blocks_until: u8,
    next_counter: u8,
}

impl IncomingPacket {
    fn new(frame: &CANFrame) -> IncomingPacket {
        let data: &[u8] = frame.data();
        let mut datavec = Vec::new();

        for v in 2..8 {
            datavec.push(data[v]);
        }

        IncomingPacket {
            id: frame.id() as u16,
            remaining_bytes: ((((data[0] as u16) & 0x0f) << 8) | (data[1] as u16)) - 6,
            content: datavec,
            block_size: DEFAULT_BLOCKS,
            blocks_until: 0,
            next_counter: 1,
        }
    }

    fn process_more(&mut self, frame: &CANFrame) -> Result<bool, ()> {
        let data: &[u8] = frame.data();
        if (data[0] & 0x0f) != self.next_counter {
            return Err(());
        }
        let provided = min(7, self.remaining_bytes);
        for v in 1..(provided + 1) {
            self.content.push(data[v as usize]);
        }
        self.remaining_bytes -= provided;
        if self.block_size != 0 {
            self.blocks_until -= 1;
        }
        self.next_counter = (self.next_counter + 1) & 0xF;

        Ok(self.block_size != 0 && self.blocks_until == 0)
    }
}

struct OutgoingPacket {
    queue: VecDeque<CANFrame>,
    block_size: Option<usize>,
}

impl OutgoingPacket {
    fn new(destination: u16, payload: &[u8]) -> OutgoingPacket {
        let mut packets = VecDeque::new();

        if payload.len() < 8 {
            // Single Frame payload, set it up...
            let mut sf_payload = [0; 8];
            sf_payload[0] = payload.len() as u8;
            for v in 0..payload.len() {
                sf_payload[v + 1] = payload[v];
            }
            packets
                .push_back(CANFrame::new(destination as u32, &sf_payload, false, false).unwrap());
        } else {
            // Multi frame payload, set it up...
            let mut ff_payload = [0; 8];
            ff_payload[0] = (0x10 | (payload.len() >> 8)) as u8;
            ff_payload[1] = (payload.len() & 0xFF) as u8;
            for v in 0..6 {
                ff_payload[v + 2] = payload[v];
            }
            packets
                .push_back(CANFrame::new(destination as u32, &ff_payload, false, false).unwrap());
            let mut sent = 6;
            let mut counter = 1;
            while sent < payload.len() {
                let mut cf_payload = [0; 8];
                cf_payload[0] = (0x20 | counter) as u8;
                counter = (counter + 1) & 0xF;
                let this_packet = min(payload.len() - sent, 7);
                for v in 0..this_packet {
                    cf_payload[v + 1] = payload[sent + v];
                }
                sent += this_packet;
                packets.push_back(
                    CANFrame::new(destination as u32, &cf_payload, false, false).unwrap(),
                );
            }
        }

        OutgoingPacket {
            queue: packets,
            block_size: None,
        }
    }

    fn queue_some(&mut self, txqueue: &mut VecDeque<CANFrame>) {
        trace!("Queueing some frames {:?}", self.block_size);
        let mut to_send = self.block_size.unwrap_or(1);
        if to_send == 0 {
            to_send = self.queue.len();
        }
        trace!("Chosing to send {} frames this time", to_send);
        for _ in 0..to_send {
            if let Some(packet) = self.queue.pop_front() {
                txqueue.push_back(packet);
            }
        }
        trace!("There are {} packets left", self.queue.len())
    }

    fn is_finished(&self) -> bool {
        self.queue.len() == 0
    }

    fn set_block_size(&mut self, block_size: u8) {
        self.block_size = Some(block_size as usize);
    }
}

pub struct ISOTP {
    canstream: SplitStream<CANStream>,
    cansink: mpsc::Sender<CANFrame>,
    incoming: HashMap<u16, IncomingPacket>,
    outgoing: HashMap<u16, OutgoingPacket>,
    txqueue: VecDeque<CANFrame>,
}

impl ISOTP {
    pub fn new(interface: &str) -> ISOTP {
        let (sink, stream) = CANStream::from_name(interface).unwrap().split();

        let (sender, receiver) = mpsc::channel(100);

        tokio::spawn(
            receiver
                .map(|f| {
                    trace!("Forwarding to CANStream {:X}", f);
                    f
                })
                .forward(sink.sink_map_err(|_| ()))
                .map(|_| ()),
        );

        ISOTP {
            canstream: stream,
            cansink: sender,
            incoming: HashMap::new(),
            outgoing: HashMap::new(),
            txqueue: VecDeque::new(),
        }
    }

    pub fn send_packet(&mut self, destination: u16, payload: &[u8]) {
        let answerer = destination + 8;
        let mut packet = OutgoingPacket::new(destination, payload);
        trace!("Preparing to send packet...");
        if self.queue_some_outgoing(&mut packet) {
            trace!(
                "There's more to queue, waiting for flow control to {:x}",
                answerer
            );
            self.outgoing.insert(answerer, packet);
        } else {
            trace!("Nothing more to send!");
        }
        self.drain_queue();
    }

    fn drain_queue(&mut self) {
        if self.txqueue.len() > 0 {
            trace!("Draining {} frames from the queue", self.txqueue.len());
            let mut waiter = self.cansink.clone().wait();

            while let Some(frame) = self.txqueue.pop_front() {
                trace!("Draining frame {:X}", frame);
                waiter.send(frame).unwrap();
                waiter.flush().unwrap();
            }
            trace!("Drain complete");
        }
    }

    pub fn handle_frame(&mut self, frame: &CANFrame) -> Option<(u16, Vec<u8>)> {
        let id = frame.id() as u16;
        let data = frame.data();
        match data[0] >> 4 {
            0 => {
                trace!("SingleFrame");
                // Received a SingleFrame frame, return a Vec of the
                // requisite number of bytes...
                let len = (data[0] & 0xf) as usize;
                if len < 1 || len > 7 {
                    return None;
                }
                let sliced = &data[1..len + 1];
                return Some((frame.id() as u16, Vec::from(sliced)));
            }
            1 => {
                trace!("FirstFrame");
                // Received a FirstFrame frame, we need to cancel any
                // ongoing receive for this ID
                if self.incoming.contains_key(&id) {
                    trace!("Removed partial");
                    self.incoming.remove(&id);
                }
                // Now we need to construct an incoming packet
                let mut incoming = IncomingPacket::new(frame);
                // And we need to queue a flow control for it.
                self.queue_flow(&mut incoming);
                // We insert this into the hash
                self.incoming.insert(id, incoming);
                // Finally we return None since we've not completed reception
                self.drain_queue();
                return None;
            }
            2 => {
                trace!("ConsecutiveFrame");
                // Received a ConsecutiveFrame frame, we need to find the
                // incoming which we want, and manipulate it with the incoming
                // frame and hopefully we either succeed in completing packet
                // or we have to send a flow.  Failing both of those, we have
                // to abort the incoming packet.
                let mut ret = None;
                let mut do_flow = false;
                let mut do_delete = false;
                if let Some(packet) = self.incoming.get_mut(&id) {
                    trace!("Found packet");
                    if let Ok(flow) = packet.process_more(frame) {
                        trace!("Processed a frame, no error");
                        if packet.remaining_bytes == 0 {
                            // We have received the packet fully
                            ret = Some((id, packet.content.clone()));
                            do_delete = true;
                        } else if flow {
                            // We probably need to send a flow packet
                            do_flow = true;
                        } else {
                            // We're just processing, return None for now
                            return None;
                        }
                    } else {
                        trace!("Error processing frame");
                        do_delete = true;
                    }
                } else {
                    trace!("Didn't find a packet");
                }
                if do_flow {
                    let mut packet = self.incoming.remove(&id).unwrap();
                    self.queue_flow(&mut packet);
                    self.incoming.insert(id, packet);
                }
                if do_delete {
                    self.incoming.remove(&id);
                }
                self.drain_queue();
                return ret;
            }
            3 => {
                // A FlowControl frame means we need to check if we have an
                // outgoing packet for this, and if we do, we take it out
                // of our map, poke it gently, and put it back if necessary.
                if let Some(mut outpacket) = self.outgoing.remove(&id) {
                    outpacket.set_block_size(data[1]);
                    if self.queue_some_outgoing(&mut outpacket) {
                        self.outgoing.insert(id, outpacket);
                    }
                }
                self.drain_queue();
            }
            _ => {}
        }
        None
    }

    fn queue_flow(&mut self, packet: &mut IncomingPacket) {
        // We queue a flow control packet here
        let frame = CANFrame::new(
            (packet.id as u32) - 8,
            &[0x30, packet.block_size, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00],
            false,
            false,
        ).unwrap();
        self.txqueue.push_back(frame);
        packet.blocks_until = packet.block_size;
    }

    fn queue_some_outgoing(&mut self, packet: &mut OutgoingPacket) -> bool {
        packet.queue_some(&mut self.txqueue);
        !packet.is_finished()
    }
}

impl Stream for ISOTP {
    type Item = (u16, Vec<u8>);
    type Error = io::Error;

    fn poll(&mut self) -> Result<Async<Option<Self::Item>>, Self::Error> {
        match self.canstream.poll()? {
            Async::NotReady => Ok(Async::NotReady),
            Async::Ready(None) => Ok(Async::Ready(None)),
            Async::Ready(Some(frame)) => {
                if let Some(out) = self.handle_frame(&frame) {
                    Ok(Async::Ready(Some(out)))
                } else {
                    // Nothing to do, best to poll ourselves again to get our
                    // readerness back on the epoll queue
                    self.poll()
                }
            }
        }
    }
}

impl Sink for ISOTP {
    type SinkItem = (u16, Vec<u8>);
    type SinkError = ();

    fn start_send(
        &mut self,
        item: Self::SinkItem,
    ) -> Result<AsyncSink<Self::SinkItem>, Self::SinkError> {
        self.send_packet(item.0, &item.1);
        Ok(AsyncSink::Ready)
    }

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