protoflight 0.1.3

Protoflight flight controller.
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
use super::crc_dvb_s2::CrcDvbS2;

#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub enum MspVersion {
    #[default]
    V1,
    V2overV1,
    V2,
}

#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub enum MspPacketType {
    #[default]
    Command,
    Reply,
}

/*
#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub enum MspStreamState {
    #[default]
    Idle,
    MspPacket,
    CliActive,
    CliCmd,
}

#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub enum MspPendingSystemRequest {
    #[default]
    None,
    BootloaderRom,
    Cli,
    BootloaderFlash,
}

#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub struct MspStreamHeaderV2 {
    pub flags: u8,
    pub cmd: u16,
    pub size: u16,
}

#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub struct MspStreamPacketWithHeader {
    pub hdr_buf: [u8; 16],
    pub crc_buf: [u8; 2],
    //const uint8_t* data_ptr;
    pub data_len: u16,
    pub crc_len: u16,
    pub hrd_len: u16,
    pub checksum: u8,
}

impl MspStreamPacketWithHeader {
    const HDR_LEN: u8 = 3;
}
*/

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MspStream {
    //pending_request: MspPendingSystemRequest,
    //stream_state: MspStreamState,
    packet_state: MspPacketState,
    packet_type: MspPacketType,
    msp_version: MspVersion,
    pub cmd_msp: u16,
    pub offset: u16,
    pub data_size: u16,
    pub cmd_flags: u8,
    pub checksum1: u8,
    pub checksum2: u8,
}

#[allow(unused)]
impl MspStream {
    const JUMBO_FRAME_SIZE_LIMIT: usize = 255;

    const MSP_EVALUATE_NON_MSP_DATA: u8 = 0;
    const MSP_SKIP_NON_MSP_DATA: u8 = 1;
    const MSP_HEADER_LENGTH: usize = 3;

    const MSP_MAX_HEADER_SIZE: usize = 9;
}

impl MspStream {
    pub const fn new() -> Self {
        Self {
            //pending_request: MspPendingSystemRequest::None,
            //stream_state: MspStreamState::Idle,
            packet_state: MspPacketState::Idle,
            packet_type: MspPacketType::Command,
            msp_version: MspVersion::V1,
            cmd_msp: 0,
            offset: 0,
            data_size: 0,
            cmd_flags: 0,
            checksum1: 0,
            checksum2: 0,
        }
    }
}

impl Default for MspStream {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub enum MspPacketState {
    #[default]
    Idle,
    HeaderM,
    HeaderX,
    HeaderV1 {
        offset: usize,
        checksum: u8,
    },
    PayloadV1 {
        len: usize,
        cmd: u8,
        offset: usize,
        checksum: u8,
    },
    HeaderV2 {
        version: MspVersion,
        offset: usize,
        checksum1: u8, // For V2-over-V1
        checksum2: u8, // CRC8
    },
    PayloadV2 {
        version: MspVersion,
        len: usize,
        cmd: u16,
        flags: u8,
        offset: usize,
        checksum1: u8,
        checksum2: u8,
    },
    ChecksumV1 {
        checksum: u8,
    },
    ChecksumV2 {
        version: MspVersion,
        checksum1: u8,
        checksum2: u8,
    },
    CommandReceived,
}

impl MspStream {
    #[allow(clippy::too_many_lines)]
    #[allow(unused)]
    pub fn process_received_packet_data(&mut self, buf: &mut [u8], c: u8) {
        // We take the state out to mutate it, then put it back.
        // This is a common Rust idiom for state machines.
        self.packet_state = match core::mem::take(&mut self.packet_state) {
            MspPacketState::Idle | MspPacketState::CommandReceived => match c {
                b'M' => MspPacketState::HeaderM,
                b'X' => MspPacketState::HeaderX,
                _ => MspPacketState::Idle,
            },
            MspPacketState::HeaderM => match c {
                b'<' | b'>' => {
                    self.packet_type = if c == b'<' { MspPacketType::Command } else { MspPacketType::Reply };
                    MspPacketState::HeaderV1 { offset: 0, checksum: 0 }
                }
                _ => MspPacketState::Idle,
            },
            MspPacketState::HeaderX => match c {
                b'<' | b'>' => {
                    self.packet_type = if c == b'<' { MspPacketType::Command } else { MspPacketType::Reply };
                    MspPacketState::HeaderV2 { version: MspVersion::V2, offset: 0, checksum1: 0, checksum2: 0 }
                }
                _ => MspPacketState::Idle,
            },
            MspPacketState::HeaderV1 { mut offset, mut checksum } => {
                buf[offset] = c;
                checksum ^= c;
                offset += 1;
                if offset == 2 {
                    // Size and Cmd byte
                    let size = buf[0] as usize;
                    let cmd = buf[1];
                    if size > buf.len() {
                        MspPacketState::Idle
                    } else if cmd == 255 {
                        // V2_FRAME_ID
                        MspPacketState::HeaderV2 {
                            version: MspVersion::V2overV1,
                            offset: 2,
                            checksum1: checksum,
                            checksum2: 0,
                        }
                    } else if size > 0 {
                        MspPacketState::PayloadV1 { len: size, cmd, offset: 0, checksum }
                    } else {
                        MspPacketState::ChecksumV1 { checksum }
                    }
                } else {
                    MspPacketState::HeaderV1 { offset, checksum }
                }
            }
            MspPacketState::PayloadV1 { len, cmd, mut offset, mut checksum } => {
                buf[offset] = c;
                checksum ^= c;
                offset += 1;
                if offset == len {
                    self.cmd_msp = u16::from(cmd);
                    MspPacketState::ChecksumV1 { checksum }
                } else {
                    MspPacketState::PayloadV1 { len, cmd, offset, checksum }
                }
            }
            MspPacketState::HeaderV2 { version, mut offset, mut checksum1, mut checksum2 } => {
                buf[offset] = c;
                if version == MspVersion::V2overV1 {
                    checksum1 ^= c;
                }
                checksum2 = CrcDvbS2::update(checksum2, c);
                offset += 1;

                // Header size is 5 bytes.
                // V2Native: offset 0..5 (ends at 5)
                // V2overV1: offset 2..7 (ends at 7)
                //let header_len = 5;
                let start_index = if version == MspVersion::V2overV1 { 2 } else { 0 };
                let header_end = start_index + 5;

                if offset == header_end {
                    // Use the start_index to find the V2 fields
                    if start_index + 4 > buf.len() {
                        MspPacketState::Idle
                    } else {
                        let flags = buf[start_index];
                        let cmd = u16::from_le_bytes([buf[start_index + 1], buf[start_index + 2]]);
                        let size = u16::from_le_bytes([buf[start_index + 3], buf[start_index + 4]]) as usize;
                        if size > buf.len() {
                            MspPacketState::Idle
                        } else {
                            MspPacketState::PayloadV2 {
                                version,
                                len: size,
                                cmd,
                                flags,
                                offset: 0, // Reset to 0 to start filling payload
                                checksum1,
                                checksum2,
                            }
                        }
                    }
                } else {
                    MspPacketState::HeaderV2 { version, offset, checksum1, checksum2 }
                }
            }
            MspPacketState::PayloadV2 { version, len, cmd, flags, mut offset, mut checksum1, mut checksum2 } => {
                buf[offset] = c;
                if version == MspVersion::V2overV1 {
                    checksum1 ^= c;
                }
                checksum2 = CrcDvbS2::update(checksum2, c);
                offset += 1;
                if offset == len {
                    self.cmd_msp = cmd;
                    self.cmd_flags = flags;
                    MspPacketState::ChecksumV2 { version, checksum1, checksum2 }
                } else {
                    MspPacketState::PayloadV2 { version, len, cmd, flags, offset, checksum1, checksum2 }
                }
            }
            MspPacketState::ChecksumV1 { checksum } => {
                self.checksum1 = checksum;
                if checksum == c { MspPacketState::CommandReceived } else { MspPacketState::Idle }
            }
            MspPacketState::ChecksumV2 { version, mut checksum1, checksum2 } => {
                self.checksum2 = checksum2;
                if version == MspVersion::V2overV1 {
                    // V2 over V1 has an extra CRC step
                    if checksum2 == c {
                        // XOR the CRC byte into the V1 sum before moving to the final check
                        checksum1 ^= c;
                        MspPacketState::ChecksumV1 { checksum: checksum1 }
                    } else {
                        MspPacketState::Idle
                    }
                } else {
                    if checksum2 == c { MspPacketState::CommandReceived } else { MspPacketState::Idle }
                }
            }
        }
    }

    #[allow(unused)]
    pub fn serialize_packet(
        version: MspVersion,
        packet_type: MspPacketType,
        cmd: u16,
        flags: u8,
        payload: &[u8],
        dst: &mut [u8], // caller provided buffer
    ) -> Result<usize, MspError> {
        let mut offset = 0;

        // Helper to push bytes safely into fixed slice
        let push = |b: u8, dst: &mut [u8], offset: &mut usize| -> Result<(), MspError> {
            if *offset >= dst.len() {
                return Err(MspError::BufferTooSmall);
            }
            dst[*offset] = b;
            *offset += 1;
            Ok(())
        };

        match version {
            MspVersion::V1 => {
                push(b'$', dst, &mut offset)?;
                push(b'M', dst, &mut offset)?;
                push(if packet_type == MspPacketType::Command { b'<' } else { b'>' }, dst, &mut offset)?;

                #[allow(clippy::cast_possible_truncation)]
                let size = payload.len() as u8;
                push(size, dst, &mut offset)?;

                #[allow(clippy::cast_possible_truncation)]
                let cmd_u8 = cmd as u8;
                push(cmd_u8, dst, &mut offset)?;

                let mut checksum = size ^ cmd_u8;
                for &byte in payload {
                    push(byte, dst, &mut offset)?;
                    checksum ^= byte;
                }
                push(checksum, dst, &mut offset)?;
            }

            MspVersion::V2 => {
                push(b'$', dst, &mut offset)?;
                push(b'X', dst, &mut offset)?;
                push(if packet_type == MspPacketType::Command { b'<' } else { b'>' }, dst, &mut offset)?;

                let mut crc = 0u8;
                #[allow(clippy::cast_possible_truncation)]
                let size = payload.len() as u16;

                // Nested helper to push and update CRC
                let push_v2 = |b: u8, dst: &mut [u8], offset: &mut usize, crc: &mut u8| -> Result<(), MspError> {
                    push(b, dst, offset)?;
                    *crc = CrcDvbS2::update(*crc, b);
                    Ok(())
                };

                push_v2(flags, dst, &mut offset, &mut crc)?;

                let cmd_bytes = cmd.to_be_bytes();
                push_v2(cmd_bytes[0], dst, &mut offset, &mut crc)?;
                push_v2(cmd_bytes[1], dst, &mut offset, &mut crc)?;

                let size_bytes = size.to_be_bytes();
                push_v2(size_bytes[0], dst, &mut offset, &mut crc)?;
                push_v2(size_bytes[1], dst, &mut offset, &mut crc)?;

                for &byte in payload {
                    push_v2(byte, dst, &mut offset, &mut crc)?;
                }
                push(crc, dst, &mut offset)?;
            }

            MspVersion::V2overV1 => {
                push(b'$', dst, &mut offset)?;
                push(b'M', dst, &mut offset)?;
                push(if packet_type == MspPacketType::Command { b'<' } else { b'>' }, dst, &mut offset)?;

                let v2_payload_len = 5 + payload.len() + 1; // Hdr(5) + Data + CRC(1)
                #[allow(clippy::cast_possible_truncation)]
                let v1_size = v2_payload_len as u8;
                let v1_cmd = 255u8;
                let mut xor = v1_size ^ v1_cmd;

                push(v1_size, dst, &mut offset)?;
                push(v1_cmd, dst, &mut offset)?;

                let mut crc = 0u8;
                #[allow(clippy::cast_possible_truncation)]
                let size_v2 = payload.len() as u16;

                let push_v2_over_v1 =
                    |b: u8, dst: &mut [u8], off: &mut usize, c: &mut u8, x: &mut u8| -> Result<(), MspError> {
                        push(b, dst, off)?;
                        *c = CrcDvbS2::update(*c, b);
                        *x ^= b;
                        Ok(())
                    };

                push_v2_over_v1(flags, dst, &mut offset, &mut crc, &mut xor)?;
                push_v2_over_v1((cmd & 0xFF) as u8, dst, &mut offset, &mut crc, &mut xor)?;
                push_v2_over_v1((cmd >> 8) as u8, dst, &mut offset, &mut crc, &mut xor)?;
                push_v2_over_v1((size_v2 & 0xFF) as u8, dst, &mut offset, &mut crc, &mut xor)?;
                push_v2_over_v1((size_v2 >> 8) as u8, dst, &mut offset, &mut crc, &mut xor)?;

                for &byte in payload {
                    push_v2_over_v1(byte, dst, &mut offset, &mut crc, &mut xor)?;
                }

                push(crc, dst, &mut offset)?;
                xor ^= crc;
                push(xor, dst, &mut offset)?;
            }
        }

        Ok(offset) // Return number of bytes written
    }
}

#[derive(Clone, Copy, Default, Debug, PartialEq)]
pub enum MspError {
    #[default]
    BufferTooSmall,
}

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

    fn _is_normal<T: Sized + Send + Sync + Unpin>() {}
    fn is_full<T: Sized + Send + Sync + Unpin + Copy + Clone + Default + PartialEq>() {}

    #[test]
    fn normal_types() {
        is_full::<MspVersion>();
        is_full::<MspPacketType>();
        is_full::<MspStream>();
        is_full::<MspPacketState>();
        is_full::<MspError>();
    }
}
#[allow(clippy::expect_used)]
#[cfg(test)]
mod tests {
    use super::*;

    const INBUF_SIZE: usize = 192;
    #[test]
    fn test_msp_v1_parsing() {
        let mut buf = [0u8; INBUF_SIZE];
        let mut stream = MspStream::new();
        let packet: [u8; 7] = [
            b'M', b'<', 2,   // Size
            100, // Cmd
            1, 2,   // Payload
            101, // XOR
        ];

        for &byte in &packet {
            stream.process_received_packet_data(&mut buf, byte);
        }

        assert!(matches!(stream.packet_state, MspPacketState::CommandReceived));
        assert_eq!(stream.cmd_msp, 100);
        assert_eq!(&buf[0..2], &[1, 2]);
    }
    #[test]
    fn test_msp_v2_native_parsing() {
        let mut buf = [0u8; INBUF_SIZE];
        let mut stream = MspStream::new();
        let packet: [u8; 10] = [
            b'X', b'<', 0, // Flags
            2, 1, // Cmd (0x0102)
            2, 0, // Size (2)
            0xAA, 0xBB, // Payload
            19,   // CRC8
        ];

        for &byte in &packet {
            stream.process_received_packet_data(&mut buf, byte);
        }

        assert_eq!(MspPacketState::CommandReceived, stream.packet_state);
        assert_eq!(19, stream.checksum2);
        assert_eq!(stream.cmd_msp, 0x0102);
        assert_eq!(stream.cmd_flags, 0);
        assert_eq!(&buf[0..2], &[0xAA, 0xBB]);
    }
    #[test]
    fn test_msp_v2_over_v1_parsing() {
        let mut buf = [0u8; INBUF_SIZE];
        let mut stream = MspStream::new();

        // Crafted Packet: V2 Command 0x0102, Flags 0, Payload [0xAA, 0xBB]
        // Encapsulated in V1 (Cmd 255)
        let packet: [u8; 13] = [
            b'M', b'<', // Header
            8,    // V1 Size (5 byte V2 hdr + 2 byte payload + 1 byte V2 CRC)
            255,  // V1 Cmd (V2_FRAME_ID)
            0,    // V2 Flags
            2, 1, // V2 Cmd (0x0102, Little Endian)
            2, 0, // V2 Payload Size (2, Little Endian)
            0xAA, 0xBB, // V2 Payload
            19,   // V2 CRC8 (CRC-8/DVB-S2)
            244,  // V1 XOR Checksum
        ];

        for (i, &byte) in packet.iter().enumerate() {
            stream.process_received_packet_data(&mut buf, byte);

            if i < packet.len() - 1 {
                // Ensure we haven't reset to Idle prematurely
                assert!(
                    !matches!(stream.packet_state, MspPacketState::Idle),
                    "State machine reset to Idle at byte index {i}",
                );
            }
        }

        // Final Verification
        assert_eq!(stream.packet_state, MspPacketState::CommandReceived);
        assert_eq!(244, stream.checksum1);
        assert_eq!(19, stream.checksum2);
        assert_eq!(stream.cmd_msp, 0x0102);
        assert_eq!(stream.cmd_flags, 0);
        assert_eq!(&buf[0..2], &[0xAA, 0xBB]);
    }
    #[test]
    fn test_serialize_msp_v1_request() {
        let mut buf = [0u8; 32];

        // Example: MSP_IDENT (Cmd 100) request with no payload
        let size = MspStream::serialize_packet(
            MspVersion::V1,
            MspPacketType::Command,
            100,
            0,
            &[], // Empty payload
            &mut buf,
        )
        .expect("Serialization failed");

        // Expected: $M< (3) + Size (0) + Cmd (100) + XOR (100)
        // Checksum: 0 ^ 100 = 100
        let expected = [b'$', b'M', b'<', 0, 100, 100];
        assert_eq!(&buf[..size], &expected);
    }

    #[test]
    fn test_serialize_msp_v1_with_payload() {
        let mut buf = [0u8; 32];

        // Example: Command 100 with payload [1, 2]
        let payload = [1, 2];
        let size = MspStream::serialize_packet(MspVersion::V1, MspPacketType::Command, 100, 0, &payload, &mut buf)
            .expect("Serialization failed");

        // Expected: $M< (3) + Size (2) + Cmd (100) + Payload (1, 2) + XOR
        // Checksum: 2 ^ 100 ^ 1 ^ 2 = 101
        let expected = [b'$', b'M', b'<', 2, 100, 1, 2, 101];
        assert_eq!(&buf[..size], &expected);
    }
    #[test]
    fn test_serialize_v2_over_v1() {
        let mut buf = [0u8; 64];
        let payload = [0xAA, 0xBB];

        let size = MspStream::serialize_packet(
            MspVersion::V2overV1,
            MspPacketType::Command,
            0x0102, // Cmd
            0,      // Flags
            &payload,
            &mut buf,
        )
        .expect("Serialization failed");

        // Breakdown of the expected 13 bytes:
        // [0..3]   Header: $M<
        // [3]      V1 Size: 8
        // [4]      V1 Cmd: 255
        // [5..10]  V2 Header: 0, 2, 1, 2, 0 (Flags, CmdL, CmdH, SizeL, SizeH)
        // [10..12] V2 Payload: 0xAA, 0xBB
        // [12]     V2 CRC8: 19
        // [13]     V1 XOR: 244
        let expected = [
            b'$', b'M', b'<', 8, 255, // V1 Wrapper
            0, 2, 1, 2, 0, // V2 Header
            0xAA, 0xBB, // V2 Data
            19,   // V2 CRC
            244,  // V1 XOR
        ];

        assert_eq!(size, 14); // 3 (hdr) + 11 (data/checksums) = 14 total bytes
        assert_eq!(&buf[..size], &expected);
    }
}