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
use crate::{Error, ReadWrite};
use core::convert::TryFrom;

use scroll::{ctx, Pread, Pwrite, LE};

impl From<scroll::Error> for Error {
    fn from(_err: scroll::Error) -> Self {
        Error::Parse
    }
}

impl From<core::str::Utf8Error> for Error {
    fn from(_err: core::str::Utf8Error) -> Self {
        Error::Parse
    }
}

impl From<std::io::Error> for Error {
    fn from(_err: std::io::Error) -> Self {
        Error::Arguments
    }
}

#[derive(Debug, PartialEq)]
pub(crate) struct CommandResponse {
    ///arbitrary number set by the host, for example as sequence number. The response should repeat the tag.
    pub(crate) tag: u16,
    pub(crate) status: CommandResponseStatus, //    uint8_t status;
    ///additional information In case of non-zero status
    pub(crate) status_info: u8, // optional?
    ///LE bytes
    pub(crate) data: Vec<u8>,
}

#[derive(Debug, PartialEq)]
pub(crate) enum CommandResponseStatus {
    //command understood and executed correctly
    Success = 0x00,
    //command not understood
    ParseError = 0x01,
    //command execution error
    ExecutionError = 0x02,
}

impl TryFrom<u8> for CommandResponseStatus {
    type Error = Error;

    fn try_from(val: u8) -> Result<Self, Self::Error> {
        match val {
            0 => Ok(CommandResponseStatus::Success),
            1 => Ok(CommandResponseStatus::ParseError),
            2 => Ok(CommandResponseStatus::ExecutionError),
            _ => Err(Error::Parse),
        }
    }
}

#[derive(Debug, PartialEq)]
enum PacketType {
    //Inner packet of a command message
    Inner = 0,
    //Final packet of a command message
    Final = 1,
    //Serial stdout
    StdOut = 2,
    //Serial stderr
    Stderr = 3,
}

impl TryFrom<u8> for PacketType {
    type Error = Error;

    fn try_from(val: u8) -> Result<Self, Self::Error> {
        match val {
            0 => Ok(PacketType::Inner),
            1 => Ok(PacketType::Final),
            2 => Ok(PacketType::StdOut),
            3 => Ok(PacketType::Stderr),
            _ => Err(Error::Parse),
        }
    }
}

// doesnt know what the data is supposed to be decoded as
// thats linked via the seq number outside, so we cant decode here
impl<'a> ctx::TryFromCtx<'a, scroll::Endian> for CommandResponse {
    type Error = Error;
    fn try_from_ctx(this: &'a [u8], le: scroll::Endian) -> Result<(Self, usize), Self::Error> {
        if this.len() < 4 {
            return Err(Error::Parse);
        }

        let mut offset = 0;
        let tag = this.gread_with::<u16>(&mut offset, le)?;
        let status: u8 = this.gread_with::<u8>(&mut offset, le)?;
        let status = CommandResponseStatus::try_from(status)?;
        let status_info = this.gread_with::<u8>(&mut offset, le)?;

        Ok((
            CommandResponse {
                tag,
                status,
                status_info,
                data: this[offset..].to_vec(),
            },
            offset,
        ))
    }
}

#[derive(Debug)]
pub(crate) struct Command {
    ///Command ID
    id: u32,
    ///arbitrary number set by the host, for example as sequence number. The response should repeat the tag.
    tag: u16,
    ///reserved bytes in the command should be sent as zero and ignored by the device
    _reserved0: u8,
    ///reserved bytes in the command should be sent as zero and ignored by the device
    _reserved1: u8,
    ///LE bytes
    data: Vec<u8>,
}
impl Command {
    pub(crate) fn new(id: u32, tag: u16, data: Vec<u8>) -> Self {
        Self {
            id,
            tag,
            _reserved0: 0,
            _reserved1: 0,
            data,
        }
    }
}

///Transmit a Command, command.data should already have been LE converted
pub(crate) fn xmit(cmd: Command, d: &impl ReadWrite) -> Result<(), Error> {
    log::debug!("{:?}", cmd);

    //Packets are up to 64 bytes long + first byte is Report ID,
    let buffer = &mut [0_u8; 65];

    // Report ID at 0, hardcoded to 0, header at 1 filled in later, so start at 2
    let mut offset = 2;

    //command struct is 8 bytes
    buffer.gwrite_with(cmd.id, &mut offset, LE)?;
    buffer.gwrite_with(cmd.tag, &mut offset, LE)?;
    buffer.gwrite_with(cmd._reserved0, &mut offset, LE)?;
    buffer.gwrite_with(cmd._reserved1, &mut offset, LE)?;

    //copy up to the first 55 bytes
    let mut count = if cmd.data.len() > 55 {
        55
    } else {
        cmd.data.len()
    };
    buffer.gwrite(&cmd.data[..count], &mut offset)?;

    //subtract header from offset for packet size
    if count == cmd.data.len() {
        buffer[1] = (PacketType::Final as u8) << 6 | (offset - 2) as u8;
        log::debug!("tx: {:02X?}", &buffer[..offset]);

        return d.hf2_write(&buffer[..offset]).map(|_| ());
    } else {
        buffer[1] = (PacketType::Inner as u8) << 6 | (offset - 2) as u8;
        log::debug!("tx: {:02X?}", &buffer[..offset]);

        d.hf2_write(&buffer[..offset])?;
    }

    //send the rest in chunks up to 63
    for chunk in cmd.data[count..].chunks(63) {
        count += chunk.len();

        if count == cmd.data.len() {
            buffer[1] = (PacketType::Final as u8) << 6 | chunk.len() as u8;
        } else {
            buffer[1] = (PacketType::Inner as u8) << 6 | chunk.len() as u8;
        }

        buffer[2..(chunk.len() + 2)].copy_from_slice(chunk);

        log::debug!("tx: {:02X?}", &buffer[..(chunk.len() + 2)]);
        d.hf2_write(&buffer[..(chunk.len() + 2)])?;
    }
    Ok(())
}

///Receive a CommandResponse, CommandResponse.data is not interpreted in any way.
pub(crate) fn rx(d: &impl ReadWrite) -> Result<CommandResponse, Error> {
    let mut bitsnbytes: Vec<u8> = vec![];

    let buffer = &mut [0_u8; 64];
    let mut retries = 5;

    // keep reading until Final packet
    'outer: while {
        let count = d.hf2_read(buffer)?;

        log::debug!("rx count: {:?}", count);

        if count < 1 {
            if retries <= 0 {
                return Err(Error::Parse);
            } else {
                retries -= 1;
                continue 'outer;
            }
        }

        let ptype = PacketType::try_from(buffer[0] >> 6)?;

        log::debug!("rx ptype: {:?}", ptype);

        let len: usize = (buffer[0] & 0x3F) as usize;

        log::debug!("rx len: {:?}", len);

        if len >= count {
            return Err(Error::Parse);
        }

        log::debug!(
            "rx header: {:02X?} data: {:02X?}",
            &buffer[0],
            &buffer[1..(len + 1)]
        );

        //skip the header byte and strip excess bytes remote is allowed to send
        bitsnbytes.extend_from_slice(&buffer[1..(len + 1)]);

        //funky do while notation
        ptype == PacketType::Inner
    } {}

    let resp = bitsnbytes.as_slice().pread_with(0, LE)?;

    log::debug!("{:?}", resp);

    Ok(resp)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[allow(dead_code)]
    pub struct MyMock<R, W>
    where
        R: Fn() -> Vec<u8>,
        W: Fn(&[u8]) -> usize,
    {
        pub reader: R,
        pub writer: W,
    }

    impl<R, W> ReadWrite for MyMock<R, W>
    where
        R: Fn() -> Vec<u8>,
        W: Fn(&[u8]) -> usize,
    {
        fn hf2_write(&self, data: &[u8]) -> Result<usize, Error> {
            let len = (&self.writer)(data);

            Ok(len)
        }
        fn hf2_read(&self, buf: &mut [u8]) -> Result<usize, Error> {
            let data = (self.reader)();

            for (i, val) in data.iter().enumerate() {
                buf[i] = *val
            }

            Ok(data.len())
        }
    }

    #[test]
    fn send_fragmented() {
        let data: Vec<Vec<u8>> = vec![
            vec![
                0x00, 0x3f, 0x06, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00,
                0x00, 0x00, 0x03, 0x20, 0xd7, 0x5e, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x51, 0x5f,
                0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00,
            ],
            vec![
                0x00, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00,
                0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d,
                0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00,
                0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d,
                0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f,
            ],
            vec![
                0x00, 0x3f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f,
                0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00,
                0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f,
                0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00,
                0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d,
            ],
            vec![
                0x00, 0x3f, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d,
                0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00,
                0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d,
                0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00,
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            ],
            vec![
                0x00, 0x50, 0x00, 0x00, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00, 0x4d, 0x5f, 0x00, 0x00,
                0x4d, 0x5f, 0x00, 0x00,
            ],
        ];

        let le_page: Vec<u8> = vec![
            0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x03, 0x20, 0xD7, 0x5E, 0x00, 0x00, 0x4D, 0x5F,
            0x00, 0x00, 0x51, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00,
            0x4D, 0x5F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F,
            0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00,
            0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F,
            0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00,
            0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F,
            0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00,
            0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F,
            0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00,
            0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F,
            0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00,
            0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F,
            0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00,
            0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00,
            0x4D, 0x5F, 0x00, 0x00, 0x4D, 0x5F, 0x00, 0x00,
        ];

        let writer = |v: &[u8]| -> usize {
            static mut I: usize = 0;

            let res: &Vec<u8> = unsafe {
                let res = &data[I];
                I += 1;
                res
            };

            assert_eq!(res.as_slice(), v);

            v.len()
        };

        let mock = MyMock {
            reader: || vec![],
            writer,
        };

        let command = Command::new(0x0006, 4, le_page);

        xmit(command, &mock).unwrap();
    }

    #[test]
    fn receive_fragmented() {
        let data: Vec<Vec<u8>> = vec![
            vec![
                0x3F, 0x04, 0x00, 0x00, 0x00, 0x55, 0x46, 0x32, 0x20, 0x42, 0x6F, 0x6F, 0x74, 0x6C,
                0x6F, 0x61, 0x64, 0x65, 0x72, 0x20, 0x76, 0x33, 0x2E, 0x36, 0x2E, 0x30, 0x20, 0x53,
                0x46, 0x48, 0x57, 0x52, 0x4F, 0x0D, 0x0A, 0x4D, 0x6F, 0x64, 0x65, 0x6C, 0x3A, 0x20,
                0x50, 0x79, 0x47, 0x61, 0x6D, 0x65, 0x72, 0x0D, 0x0A, 0x42, 0x6F, 0x61, 0x72, 0x64,
                0x2D, 0x49, 0x44, 0x3A, 0x20, 0x53, 0x41, 0x4D,
            ],
            vec![
                0x54, 0x44, 0x35, 0x31, 0x4A, 0x31, 0x39, 0x41, 0x2D, 0x50, 0x79, 0x47, 0x61, 0x6D,
                0x65, 0x72, 0x2D, 0x4D, 0x34, 0x0D, 0x0A,
            ],
        ];

        let result: Vec<u8> = vec![
            0x55, 0x46, 0x32, 0x20, 0x42, 0x6F, 0x6F, 0x74, 0x6C, 0x6F, 0x61, 0x64, 0x65, 0x72,
            0x20, 0x76, 0x33, 0x2E, 0x36, 0x2E, 0x30, 0x20, 0x53, 0x46, 0x48, 0x57, 0x52, 0x4F,
            0x0D, 0x0A, 0x4D, 0x6F, 0x64, 0x65, 0x6C, 0x3A, 0x20, 0x50, 0x79, 0x47, 0x61, 0x6D,
            0x65, 0x72, 0x0D, 0x0A, 0x42, 0x6F, 0x61, 0x72, 0x64, 0x2D, 0x49, 0x44, 0x3A, 0x20,
            0x53, 0x41, 0x4D, 0x44, 0x35, 0x31, 0x4A, 0x31, 0x39, 0x41, 0x2D, 0x50, 0x79, 0x47,
            0x61, 0x6D, 0x65, 0x72, 0x2D, 0x4D, 0x34, 0x0D, 0x0A,
        ];

        let reader = || -> Vec<u8> {
            static mut I: usize = 0;

            let res: &Vec<u8> = unsafe {
                let res = &data[I];
                I += 1;
                res
            };

            res.to_vec()
        };

        let mock = MyMock {
            reader,
            writer: |_v| 0,
        };

        let response = CommandResponse {
            tag: 0x0004,
            status: CommandResponseStatus::Success,
            status_info: 0x00,
            data: result.to_vec(),
        };

        let rsp = rx(&mock).unwrap();
        assert_eq!(rsp, response);
    }
}