1 // Copyright 2023 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 use std::io::{Error, Read};
16
17 /// This module implements control packet parsing for UWB.
18 ///
19 /// UWB Command Interface Specification, UCI Generic Specification
20 /// Version 1.1
21 ///
22 /// 2.3.2 Format of Control Packets
23
24 const UCI_HEADER_SIZE: usize = 4;
25 const UCI_PAYLOAD_LENGTH_FIELD: usize = 3;
26
27 #[derive(Debug)]
28 pub struct Packet {
29 pub payload: Vec<u8>,
30 }
31
32 #[derive(Debug)]
33 pub enum PacketError {
34 IoError(Error),
35 }
36
read_uci_packet<R: Read>(reader: &mut R) -> Result<Packet, PacketError>37 pub fn read_uci_packet<R: Read>(reader: &mut R) -> Result<Packet, PacketError> {
38 // Read the UCI header
39 let mut buffer = vec![0; UCI_HEADER_SIZE];
40 reader.read_exact(&mut buffer[0..]).map_err(PacketError::IoError)?;
41 // Extract the control packet payload length and read
42 let length = buffer[UCI_PAYLOAD_LENGTH_FIELD] as usize + UCI_HEADER_SIZE;
43 buffer.resize(length, 0);
44 reader.read_exact(&mut buffer[UCI_HEADER_SIZE..]).map_err(PacketError::IoError)?;
45 Ok(Packet { payload: buffer })
46 }
47