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 #![allow(clippy::empty_line_after_doc_comments)]
16
17 use bytes::Bytes;
18
19 use std::io::{Error, Read};
20
21 /// This module implements control packet parsing for UWB.
22 ///
23 /// UWB Command Interface Specification, UCI Generic Specification
24 /// Version 1.1
25 ///
26 /// 2.3.2 Format of Control Packets
27
28 const UCI_HEADER_SIZE: usize = 4;
29 const UCI_PAYLOAD_LENGTH_FIELD: usize = 3;
30
31 #[derive(Debug)]
32 pub struct Packet {
33 pub payload: Bytes,
34 }
35
36 #[derive(Debug)]
37 pub enum PacketError {
38 IoError(Error),
39 }
40
read_uci_packet<R: Read>(reader: &mut R) -> Result<Packet, PacketError>41 pub fn read_uci_packet<R: Read>(reader: &mut R) -> Result<Packet, PacketError> {
42 // Read the UCI header
43 let mut buffer = vec![0; UCI_HEADER_SIZE];
44 reader.read_exact(&mut buffer[0..]).map_err(PacketError::IoError)?;
45 // Extract the control packet payload length and read
46 let length = buffer[UCI_PAYLOAD_LENGTH_FIELD] as usize + UCI_HEADER_SIZE;
47 buffer.resize(length, 0);
48 reader.read_exact(&mut buffer[UCI_HEADER_SIZE..]).map_err(PacketError::IoError)?;
49 Ok(Packet { payload: Bytes::from(buffer) })
50 }
51