aboutsummaryrefslogtreecommitdiffstats
path: root/src/kiss.rs
blob: e9f4703f284b3718b9f00a31bb05403850c3aa2f (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
// Taken from ax25-rs, which is
// SPDX-License-Identifier: Apache-2.0
use std::io;
use std::io::{Read, Write};

const FEND: u8 = 0xC0;
const FESC: u8 = 0xDB;
const TFEND: u8 = 0xDC;
const TFESC: u8 = 0xDD;

pub struct KissDecoder<'a> {
    stream: &'a mut Read,
    buffer: Vec<u8>
}

impl<'a> KissDecoder<'a> {
    pub fn new<T>(stream: &'a mut T) -> io::Result<KissDecoder>
        where T: Read
    {
        Ok(KissDecoder {
            stream: stream,
            buffer: Vec::new()
        })
    }

    pub fn receive_frame(&mut self) -> io::Result<Vec<u8>> {
        loop {
            if let Some(frame) = make_frame_from_buffer(&mut self.buffer) {
                return Ok(frame);
            }
            let mut buf = vec![0u8; 1024];
            let n_bytes = self.stream.read(&mut buf)?;
            self.buffer.extend(buf.iter().take(n_bytes));
        }
    }
}

pub struct KissEncoder<'a> {
    stream: &'a mut Write,
}

impl<'a> KissEncoder<'a> {
    pub fn new<T>(stream: &'a mut T) -> io::Result<KissEncoder>
        where T: Write
    {
        Ok(KissEncoder {
            stream: stream,
        })
    }

    pub fn send_frame(&mut self, frame: &[u8]) -> io::Result<()> {
        // 0x00 is the KISS command byte, which is two nibbles
        // port = 0
        // command = 0 (all following bytes are a data frame to transmit)
        self.stream.write(&[FEND, 0x00])?;
        self.stream.write(frame)?;
        self.stream.write(&[FEND])?;
        self.stream.flush()?;
        Ok(())
    }
}

fn make_frame_from_buffer(buffer: &mut Vec<u8>) -> Option<Vec<u8>> {
    let mut possible_frame = Vec::new();

    enum Scan {
        LookingForStartMarker,
        Data,
        Escaped
    }
    let mut state = Scan::LookingForStartMarker;
    let mut final_idx = 0;

    // Check for possible frame read-only until we know we have a complete frame
    // If we take one out, clear out buffer up to the final index
    for (idx, &c) in buffer.iter().enumerate() {
        match state {
            Scan::LookingForStartMarker => {
                if c == FEND {
                    state = Scan::Data;
                }
            },
            Scan::Data => {
                if c == FEND {
                    if !possible_frame.is_empty() {
                        // Successfully read a non-zero-length frame
                        final_idx = idx;
                        break;
                    }
                } else if c == FESC {
                    state = Scan::Escaped;
                } else {
                    possible_frame.push(c);
                }
            },
            Scan::Escaped => {
                if c == TFEND {
                    possible_frame.push(FEND);
                } else if c == TFESC {
                    possible_frame.push(FESC);
                } else if c == FEND {
                    if !possible_frame.is_empty() {
                        // Successfully read a non-zero-length frame
                        final_idx = idx;
                        break;
                    }
                }
                state = Scan::Data;
            }
        }
    }

    match final_idx {
        0 => None,
        n => {
            // Draining up to "n" will leave the final FEND in place
            // This way we can use it as the start marker for the next frame
            buffer.drain(0..n);
            Some(possible_frame)
        }
    }
}

#[test]
fn test_normal_frame() {
    let mut rx = vec![FEND, 0x01, 0x02, FEND];
    assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02]));
    assert_eq!(rx, vec![FEND]);
}

#[test]
fn test_trailing_data() {
    let mut rx = vec![FEND, 0x01, 0x02, FEND, 0x03, 0x04];
    assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02]));
    assert_eq!(rx, vec![FEND, 0x03, 0x04]);
}

#[test]
fn test_leading_data() {
    let mut rx = vec![0x03, 0x04, FEND, 0x01, 0x02, FEND];
    assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02]));
    assert_eq!(rx, vec![FEND]);
}

#[test]
fn test_consecutive_marker() {
    let mut rx = vec![FEND, FEND, FEND, 0x01, 0x02, FEND];
    assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02]));
    assert_eq!(rx, vec![FEND]);
}

#[test]
fn test_escapes() {
    let mut rx = vec![FEND, 0x01, FESC, TFESC, 0x02, FESC, TFEND, 0x03, FEND];
    assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, FESC, 0x02, FEND, 0x03]));
    assert_eq!(rx, vec![FEND]);
}

#[test]
fn test_incorrect_escape_skipped() {
    let mut rx = vec![FEND, 0x01, FESC, 0x04, TFESC /* passes normally without leading FESC */, 0x02, FEND];
    assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, TFESC, 0x02]));
    assert_eq!(rx, vec![FEND]);
}

#[test]
fn test_two_frames_single_fend() {
    let mut rx = vec![FEND, 0x01, 0x02, FEND, 0x03, 0x04, FEND];
    assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02]));
    assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x03, 0x04]));
    assert_eq!(rx, vec![FEND]);
}

#[test]
fn test_two_frames_double_fend() {
    let mut rx = vec![FEND, 0x01, 0x02, FEND, FEND, 0x03, 0x04, FEND];
    assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x01, 0x02]));
    assert_eq!(make_frame_from_buffer(&mut rx), Some(vec![0x03, 0x04]));
    assert_eq!(rx, vec![FEND]);
}