vex-cdc 0.1.1

Implementation of the VEX Robotics CDC communication protocol in Rust.
Documentation
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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
//! Internal filesystem access packets.

use core::str;

use alloc::vec::Vec;

use crate::{
    Decode, DecodeError, DecodeWithLength, Encode, FixedString, Version,
    cdc::{CdcReplyPacket, cmds::USER_CDC},
    cdc2::{
        Cdc2Ack, Cdc2CommandPacket, Cdc2ReplyPacket,
        ecmds::{
            FILE_CLEANUP, FILE_CTRL, FILE_DIR, FILE_DIR_ENTRY, FILE_ERASE, FILE_EXIT, FILE_FORMAT,
            FILE_GET_INFO, FILE_INIT, FILE_LINK, FILE_LOAD, FILE_READ, FILE_SET_INFO,
            FILE_USER_STAT, FILE_WRITE,
        },
    },
    decode::DecodeErrorKind,
};

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[repr(u8)]
pub enum FileTransferOperation {
    /// Write (upload) a file.
    Write = 1,

    /// Read (download) a file.
    Read = 2,
}

#[repr(u8)]
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum FileInitOption {
    None = 0,
    Overwrite = 1,
}

#[repr(u8)]
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum FileTransferTarget {
    Ddr = 0,
    Qspi = 1,
    Cbuf = 2,
    Vbuf = 3,
    Ddrc = 4,
    Ddre = 5,
    Flash = 6,
    Radio = 7,
    A1 = 13,
    B1 = 14,
    B2 = 15,
}

#[repr(u8)]
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum FileVendor {
    User = 1,
    Sys = 15,
    Dev1 = 16,
    Dev2 = 24,
    Dev3 = 32,
    Dev4 = 40,
    Dev5 = 48,
    Dev6 = 56,
    VexVm = 64,
    Vex = 240,
    Undefined = 241,
}
impl Decode for FileVendor {
    fn decode(data: &mut &[u8]) -> Result<Self, DecodeError> {
        match u8::decode(data)? {
            1 => Ok(Self::User),
            15 => Ok(Self::Sys),
            16 => Ok(Self::Dev1),
            24 => Ok(Self::Dev2),
            32 => Ok(Self::Dev3),
            40 => Ok(Self::Dev4),
            48 => Ok(Self::Dev5),
            56 => Ok(Self::Dev6),
            64 => Ok(Self::VexVm),
            240 => Ok(Self::Vex),
            241 => Ok(Self::Undefined),
            v => Err(DecodeError::new::<Self>(DecodeErrorKind::UnexpectedByte {
                name: "FileVendor",
                value: v,
                expected: &[
                    0x01, 0x0F, 0x10, 0x18, 0x20, 0x28, 0x30, 0x38, 0x40, 0xF0, 0xF1,
                ],
            })),
        }
    }
}

#[repr(u8)]
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum FileLoadAction {
    Run = 0,
    Stop = 128,
}

#[derive(Default, Debug, Clone, Copy, Eq, PartialEq)]
#[repr(u8)]
pub enum ExtensionType {
    /// Regular unencrypted file.
    #[default]
    Binary = 0x0,

    /// A file which depends on a VM.
    ///
    /// This is the file type used for VEXCode Python bin uploads, since they need the
    /// Python VM to function.
    Vm = 0x61,

    /// File's contents is encrypted.
    EncryptedBinary = 0x73,
}

impl Decode for ExtensionType {
    fn decode(data: &mut &[u8]) -> Result<Self, DecodeError> {
        Ok(match u8::decode(data)? {
            0x0 => Self::Binary,
            0x61 => Self::Vm,
            0x73 => Self::EncryptedBinary,
            unknown => {
                return Err(DecodeError::new::<Self>(DecodeErrorKind::UnexpectedByte {
                    name: "ExtensionType",
                    value: unknown,
                    expected: &[0x0],
                }));
            }
        })
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct FileMetadata {
    pub extension: FixedString<3>,
    pub extension_type: ExtensionType,
    pub timestamp: i32,
    pub version: Version,
}

impl Encode for FileMetadata {
    fn size(&self) -> usize {
        12
    }

    fn encode(&self, data: &mut [u8]) {
        data[..self.extension.len()].copy_from_slice(self.extension.as_bytes());
        data[3] = self.extension_type as _;
        self.timestamp.encode(&mut data[4..]);
        self.version.encode(&mut data[8..]);
    }
}

impl Decode for FileMetadata {
    fn decode(data: &mut &[u8]) -> Result<Self, DecodeError> {
        Ok(Self {
            // SAFETY: length is guaranteed to be less than 4.
            extension: unsafe {
                FixedString::new_unchecked(
                    str::from_utf8(&<[u8; 3]>::decode(data)?)
                        .map_err(|e| DecodeError::new::<Self>(e.into()))?,
                )
            },
            extension_type: Decode::decode(data).unwrap(),
            timestamp: i32::decode(data)?,
            version: Version::decode(data)?,
        })
    }
}

/// Start uploading or downloading file from the device
pub type FileTransferInitializePacket =
    Cdc2CommandPacket<USER_CDC, FILE_INIT, FileTransferInitializePayload>;
pub type FileTransferInitializeReplyPacket =
    Cdc2ReplyPacket<USER_CDC, FILE_INIT, FileTransferInitializeReplyPayload>;

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct FileTransferInitializePayload {
    pub operation: FileTransferOperation,
    pub target: FileTransferTarget,
    pub vendor: FileVendor,
    pub options: FileInitOption,
    pub file_size: u32,
    pub load_address: u32,
    pub write_file_crc: u32,
    pub metadata: FileMetadata,
    pub file_name: FixedString<23>,
}

impl Encode for FileTransferInitializePayload {
    fn size(&self) -> usize {
        28 + self.file_name.size()
    }

    fn encode(&self, data: &mut [u8]) {
        [
            self.operation as u8,
            self.target as u8,
            self.vendor as u8,
            self.options as u8,
        ]
        .encode(data);
        self.file_size.encode(&mut data[4..]);
        self.load_address.encode(&mut data[8..]);
        self.write_file_crc.encode(&mut data[12..]);
        self.metadata.encode(&mut data[16..]);
        self.file_name.encode(&mut data[28..]);
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct FileTransferInitializeReplyPayload {
    /// The amount of receive data (in bytes) that can be sent in every packet.
    pub window_size: u16,

    /// In read operation, the device returns the target file size (in bytes).
    ///
    /// In write operation, the device returns the value 3145728.
    pub file_size: u32,

    /// In read operation, the device returns the CRC value of the target file.
    ///
    /// In write operation, the device returns the same CRC value as the previous packets.
    pub file_crc: u32,
}

impl Decode for FileTransferInitializeReplyPayload {
    fn decode(data: &mut &[u8]) -> Result<Self, DecodeError> {
        let window_size = u16::decode(data)?;
        let file_size = u32::decode(data)?;
        // Convert from big endian
        let file_crc = u32::decode(data)?.swap_bytes();
        Ok(Self {
            window_size,
            file_size,
            file_crc,
        })
    }
}

/// Finish uploading or downloading file from the device
pub type FileTransferExitPacket = Cdc2CommandPacket<USER_CDC, FILE_EXIT, FileExitAction>;
pub type FileTransferExitReplyPacket = Cdc2ReplyPacket<USER_CDC, FILE_EXIT, ()>;

/// The action to run when a file transfer is completed.
#[repr(u8)]
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum FileExitAction {
    DoNothing = 0,
    RunProgram = 1,
    Halt = 2,
    ShowRunScreen = 3,
}
impl Encode for FileExitAction {
    fn size(&self) -> usize {
        1
    }
    fn encode(&self, data: &mut [u8]) {
        data[0] = *self as _;
    }
}
/// Write to the brain
pub type FileDataWritePacket = Cdc2CommandPacket<USER_CDC, FILE_WRITE, FileDataWritePayload>;
pub type FileDataWriteReplyPacket = Cdc2ReplyPacket<USER_CDC, FILE_WRITE, ()>;

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct FileDataWritePayload {
    /// Memory address to write to.
    pub address: i32,

    /// A sequence of bytes to write. Must be 4-byte aligned.
    pub chunk_data: Vec<u8>,
}
impl Encode for FileDataWritePayload {
    fn size(&self) -> usize {
        4 + self.chunk_data.len()
    }

    fn encode(&self, data: &mut [u8]) {
        self.address.encode(data);
        self.chunk_data.encode(&mut data[4..]);
    }
}

/// Read from the brain
pub type FileDataReadPacket = Cdc2CommandPacket<USER_CDC, FILE_READ, FileDataReadPayload>;
/// Returns the file content. This packet doesn't have an ack if the data is available.
pub type FileDataReadReplyPacket = CdcReplyPacket<USER_CDC, FileDataReadReplyPayload>;

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct FileDataReadPayload {
    /// Memory address to read from.
    pub address: u32,

    /// Number of bytes to read (4-byte aligned).
    pub size: u16,
}
impl Encode for FileDataReadPayload {
    fn size(&self) -> usize {
        6
    }

    fn encode(&self, data: &mut [u8]) {
        self.address.encode(data);
        self.size.encode(&mut data[4..]);
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum FileDataReadReplyContents {
    Ack { address: u32, data: Vec<u8> },
    Nack(Cdc2Ack),
}

impl Decode for FileDataReadReplyContents {
    fn decode(data: &mut &[u8]) -> Result<Self, DecodeError> {
        if data.len() == 1 {
            Ok(Self::Nack(Cdc2Ack::decode(data)?))
        } else {
            let address = u32::decode(data)?;
            let chunk_data = Vec::decode_with_len(data, data.len())?;

            Ok(Self::Ack {
                address,
                data: chunk_data,
            })
        }
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct FileDataReadReplyPayload {
    pub contents: FileDataReadReplyContents,
    pub crc: u16,
}
impl Decode for FileDataReadReplyPayload {
    fn decode(data: &mut &[u8]) -> Result<Self, DecodeError> {
        let ecmd = u8::decode(data)?;
        if ecmd != FILE_READ {
            return Err(DecodeError::new::<Self>(DecodeErrorKind::UnexpectedByte {
                name: "ecmd",
                value: ecmd,
                expected: &[FILE_READ],
            }));
        }

        let contents = FileDataReadReplyContents::decode(
            &mut data
                .get(..data.len() - 2)
                .ok_or_else(|| DecodeError::new::<Self>(DecodeErrorKind::UnexpectedEnd))?,
        )?;
        *data = &data[data.len() - 2..];

        let crc = u16::decode(data)?.swap_bytes();

        Ok(Self { contents, crc })
    }
}
impl FileDataReadReplyPayload {
    pub fn unwrap(self) -> Result<(u32, Vec<u8>), Cdc2Ack> {
        match self.contents {
            FileDataReadReplyContents::Ack { address, data } => Ok((address, data)),
            FileDataReadReplyContents::Nack(nack) => Err(nack),
        }
    }
}

/// File linking means allowing one file to be loaded after another file first (its parent).
///
/// This is used in PROS for the hot/cold linking.
pub type FileLinkPacket = Cdc2CommandPacket<USER_CDC, FILE_LINK, FileLinkPayload>;
pub type FileLinkReplyPacket = Cdc2ReplyPacket<USER_CDC, FILE_LINK, ()>;

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct FileLinkPayload {
    pub vendor: FileVendor,
    /// 0 = default. (RESEARCH NEEDED)
    pub reserved: u8,
    pub required_file: FixedString<23>,
}
impl Encode for FileLinkPayload {
    fn size(&self) -> usize {
        2 + self.required_file.size()
    }

    fn encode(&self, data: &mut [u8]) {
        data[0] = self.vendor as _;
        data[1] = self.reserved;
        self.required_file.encode(&mut data[2..]);
    }
}

pub type DirectoryFileCountPacket =
    Cdc2CommandPacket<USER_CDC, FILE_DIR, DirectoryFileCountPayload>;
pub type DirectoryFileCountReplyPacket = Cdc2ReplyPacket<USER_CDC, FILE_DIR, u16>;

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct DirectoryFileCountPayload {
    pub vendor: FileVendor,
    /// Unused as of VEXos 1.1.5
    pub reserved: u8,
}
impl Encode for DirectoryFileCountPayload {
    fn size(&self) -> usize {
        2
    }
    fn encode(&self, data: &mut [u8]) {
        data[0] = self.vendor as _;
        data[1] = self.reserved;
    }
}

pub type DirectoryEntryPacket = Cdc2CommandPacket<USER_CDC, FILE_DIR_ENTRY, DirectoryEntryPayload>;
pub type DirectoryEntryReplyPacket =
    Cdc2ReplyPacket<USER_CDC, FILE_DIR_ENTRY, DirectoryEntryReplyPayload>;

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct DirectoryEntryPayload {
    pub file_index: u8,
    pub reserved: u8,
}
impl Encode for DirectoryEntryPayload {
    fn size(&self) -> usize {
        2
    }

    fn encode(&self, data: &mut [u8]) {
        data[0] = self.file_index;
        data[1] = self.reserved;
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DirectoryEntryReplyPayload {
    pub file_index: u8,
    pub size: u32,

    /// The storage entry address of the file.
    pub load_address: u32,
    pub crc: u32,

    pub metadata: Option<FileMetadata>,
    pub file_name: FixedString<23>,
}

impl Decode for DirectoryEntryReplyPayload {
    fn decode(data: &mut &[u8]) -> Result<Self, DecodeError> {
        let file_index = u8::decode(data)?;
        let size = u32::decode(data)?;
        let load_address = u32::decode(data)?;
        let crc = u32::decode(data)?;

        let metadata = if data.get(0) == Some(&255) {
            let _ = <[u8; 12]>::decode(data);
            None
        } else {
            Some(FileMetadata::decode(data)?)
        };

        let file_name = FixedString::<23>::decode(data)?;

        Ok(Self {
            file_index,
            size,
            load_address,
            crc,
            metadata,
            file_name,
        })
    }
}

/// Run a binrary file on the brain or stop the program running on the brain.
pub type FileLoadActionPacket = Cdc2CommandPacket<USER_CDC, FILE_LOAD, FileLoadActionPayload>;
pub type FileLoadActionReplyPacket = Cdc2ReplyPacket<USER_CDC, FILE_LOAD, ()>;

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct FileLoadActionPayload {
    pub vendor: FileVendor,
    pub action: FileLoadAction,
    pub file_name: FixedString<23>,
}
impl Encode for FileLoadActionPayload {
    fn size(&self) -> usize {
        2 + self.file_name.size()
    }

    fn encode(&self, data: &mut [u8]) {
        data[0] = self.vendor as _;
        data[1] = self.action as _;
        self.file_name.encode(&mut data[2..]);
    }
}
pub type FileMetadataPacket = Cdc2CommandPacket<USER_CDC, FILE_GET_INFO, FileMetadataPayload>;
pub type FileMetadataReplyPacket =
    Cdc2ReplyPacket<USER_CDC, FILE_GET_INFO, Option<FileMetadataReplyPayload>>;

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct FileMetadataPayload {
    pub vendor: FileVendor,
    /// Unused as of VEXos 1.1.5
    pub reserved: u8,
    pub file_name: FixedString<23>,
}
impl Encode for FileMetadataPayload {
    fn size(&self) -> usize {
        2 + self.file_name.size()
    }

    fn encode(&self, data: &mut [u8]) {
        data[0] = self.vendor as _;
        data[1] = self.reserved as _;
        self.file_name.encode(&mut data[2..]);
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct FileMetadataReplyPayload {
    /// RESEARCH NEEDED: Unknown what this is if there is no link to the file.
    pub linked_vendor: Option<FileVendor>,
    pub size: u32,
    /// The storage entry address of the file.
    pub load_address: u32,
    pub crc32: u32,
    pub metadata: FileMetadata,
}
impl Decode for Option<FileMetadataReplyPayload> {
    fn decode(data: &mut &[u8]) -> Result<Self, DecodeError> {
        let maybe_vid = u8::decode(data).unwrap();

        let linked_vendor = match maybe_vid {
            // 0 is returned if there is no linked file.
            0 => None,
            // 255 is returned if no file was found.
            // In this case, the rest of the packet will be empty, so
            // we return None for the whole packet.
            255 => return Ok(None),
            vid => Some(FileVendor::decode(&mut [vid].as_slice())?),
        };

        let size = u32::decode(data)?;

        // This happens when we try to read a system file from the
        // `/vex_/*` VID. In this case, all of bytes after the vendor
        // will be returned as 0xff or 0x0, making this packet useless,
        // so we'll return `None` here.
        if size == 0xFFFFFFFF {
            return Ok(None);
        }

        let load_address = u32::decode(data)?;
        let crc32 = u32::decode(data)?;
        let metadata = FileMetadata::decode(data)?;

        Ok(Some(FileMetadataReplyPayload {
            linked_vendor,
            size,
            load_address,
            crc32,
            metadata,
        }))
    }
}

pub type FileMetadataSetPacket = Cdc2CommandPacket<USER_CDC, FILE_SET_INFO, FileMetadataSetPayload>;
pub type FileMetadataSetReplyPacket = Cdc2ReplyPacket<USER_CDC, FILE_SET_INFO, ()>;

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct FileMetadataSetPayload {
    pub vendor: FileVendor,
    /// 0 = default. (RESEARCH NEEDED)
    pub options: u8,
    /// The storage entry address of the file.
    pub load_address: u32,
    pub metadata: FileMetadata,
    pub file_name: FixedString<23>,
}
impl Encode for FileMetadataSetPayload {
    fn size(&self) -> usize {
        18 + self.file_name.size()
    }

    fn encode(&self, data: &mut [u8]) {
        data[0] = self.vendor as _;
        data[1] = self.options as _;
        self.load_address.encode(&mut data[2..]);
        self.metadata.encode(&mut data[6..]);
        self.file_name.encode(&mut data[18..]);
    }
}

pub type FileErasePacket = Cdc2CommandPacket<USER_CDC, FILE_ERASE, FileErasePayload>;
pub type FileEraseReplyPacket = Cdc2ReplyPacket<USER_CDC, FILE_ERASE, ()>;

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct FileErasePayload {
    pub vendor: FileVendor,
    /// Unused as of VEXos 1.1.5
    pub reserved: u8,
    pub file_name: FixedString<23>,
}
impl Encode for FileErasePayload {
    fn size(&self) -> usize {
        2 + self.file_name.size()
    }

    fn encode(&self, data: &mut [u8]) {
        data[0] = self.vendor as _;
        data[1] = self.reserved as _;
        self.file_name.encode(&mut data[2..]);
    }
}

pub type FileCleanUpPacket = Cdc2CommandPacket<USER_CDC, FILE_CLEANUP, ()>;
pub type FileCleanUpReplyPacket = Cdc2ReplyPacket<USER_CDC, FILE_CLEANUP, FileCleanUpReplyPayload>;

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct FileCleanUpReplyPayload {
    count: u16,
}

impl Decode for FileCleanUpReplyPayload {
    fn decode(data: &mut &[u8]) -> Result<Self, DecodeError> {
        Ok(Self {
            count: Decode::decode(data)?,
        })
    }
}

/// Same as "File Clear Up", but takes longer
pub type FileFormatPacket = Cdc2CommandPacket<USER_CDC, FILE_FORMAT, FileFormatConfirmation>;
pub type FileFormatReplyPacket = Cdc2CommandPacket<USER_CDC, FILE_FORMAT, ()>;

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct FileFormatConfirmation {
    /// Must be [0x44, 0x43, 0x42, 0x41].
    pub confirmation_code: [u8; 4],
}

impl FileFormatConfirmation {
    pub const FORMAT_CODE: [u8; 4] = [0x44, 0x43, 0x42, 0x41];

    pub const fn new() -> Self {
        Self {
            confirmation_code: Self::FORMAT_CODE,
        }
    }
}

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

impl Encode for FileFormatConfirmation {
    fn size(&self) -> usize {
        4
    }

    fn encode(&self, data: &mut [u8]) {
        self.confirmation_code.encode(data)
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum FileControlGroup {
    Radio(RadioChannel),
}

impl Encode for FileControlGroup {
    fn size(&self) -> usize {
        if matches!(self, Self::Radio(_)) { 2 } else { 0 }
    }

    fn encode(&self, data: &mut [u8]) {
        #[allow(irrefutable_let_patterns)] // may change in the future
        if let Self::Radio(channel) = self {
            data[0] = 0x01;
            data[1] = *channel as _;
        }
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[repr(u8)]
pub enum RadioChannel {
    // NOTE: There's probably a secret third channel for matches, but that's not known.
    /// Used when controlling the robot outside of a competition match.
    Pit = 0x00,

    /// Used when wirelessly uploading or downloading data to/from the V5 Brain.
    ///
    /// Higher radio bandwidth for file transfer purposes.
    Download = 0x01,
}

pub type FileControlPacket = Cdc2CommandPacket<USER_CDC, FILE_CTRL, FileControlGroup>;
pub type FileControlReplyPacket = Cdc2ReplyPacket<USER_CDC, FILE_CTRL, ()>;

pub type ProgramStatusPacket = Cdc2CommandPacket<USER_CDC, FILE_USER_STAT, ProgramStatusPayload>;
pub type ProgramStatusReplyPacket =
    Cdc2ReplyPacket<USER_CDC, FILE_USER_STAT, ProgramStatusReplyPayload>;

#[derive(Debug, Clone, Eq, PartialEq)]
pub struct ProgramStatusPayload {
    pub vendor: FileVendor,
    /// Unused as of VEXos 1.1.5
    pub reserved: u8,
    /// The bin file name.
    pub file_name: FixedString<23>,
}
impl Encode for ProgramStatusPayload {
    fn size(&self) -> usize {
        2 + self.file_name.size()
    }

    fn encode(&self, data: &mut [u8]) {
        data[0] = self.vendor as _;
        data[1] = self.reserved;

        self.file_name.encode(&mut data[2..]);
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct ProgramStatusReplyPayload {
    /// A zero-based slot number.
    pub slot: u8,

    /// A zero-based slot number, always same as Slot.
    pub requested_slot: u8,
}