bluetooth_hci/host/
uart.rs1extern crate nb;
4
5use byteorder::{ByteOrder, LittleEndian};
6
7const PACKET_TYPE_HCI_COMMAND: u8 = 0x01;
8const PACKET_TYPE_HCI_EVENT: u8 = 0x04;
11
12#[derive(Copy, Clone, Debug, PartialEq)]
16pub enum Error<E, VE> {
17 BadPacketType(u8),
20 BLE(crate::event::Error<VE>),
22 Comm(E),
24}
25
26#[derive(Clone, Debug)]
28pub enum Packet<Vendor>
29where
30 Vendor: crate::event::VendorEvent,
31{
32 Event(crate::Event<Vendor>),
37}
38
39pub struct CommandHeader {
41 opcode: crate::opcode::Opcode,
42 param_len: u8,
43}
44
45pub trait Hci<E, Vendor, VE>: super::Hci<E> {
54 fn read(&mut self) -> nb::Result<Packet<Vendor>, Error<E, VE>>
69 where
70 Vendor: crate::event::VendorEvent<Error = VE>;
71}
72
73impl super::HciHeader for CommandHeader {
74 const HEADER_LENGTH: usize = 4;
75
76 fn new(opcode: crate::opcode::Opcode, param_len: usize) -> CommandHeader {
77 CommandHeader {
78 opcode,
79 param_len: param_len as u8,
80 }
81 }
82
83 fn copy_into_slice(&self, buffer: &mut [u8]) {
84 buffer[0] = PACKET_TYPE_HCI_COMMAND;
85 LittleEndian::write_u16(&mut buffer[1..=2], self.opcode.0);
86 buffer[3] = self.param_len;
87 }
88}
89
90fn rewrap_error<E, VE>(e: nb::Error<E>) -> nb::Error<Error<E, VE>> {
91 match e {
92 nb::Error::WouldBlock => nb::Error::WouldBlock,
93 nb::Error::Other(err) => nb::Error::Other(Error::Comm(err)),
94 }
95}
96
97fn read_event<E, T, Vendor, VE>(
98 controller: &mut T,
99) -> nb::Result<crate::Event<Vendor>, Error<E, VE>>
100where
101 T: crate::Controller<Error = E>,
102 Vendor: crate::event::VendorEvent<Error = VE>,
103{
104 const MAX_EVENT_LENGTH: usize = 255;
105 const PACKET_HEADER_LENGTH: usize = 1;
106 const EVENT_PACKET_HEADER_LENGTH: usize = 3;
107 const PARAM_LEN_BYTE: usize = 2;
108
109 let param_len = controller.peek(PARAM_LEN_BYTE).map_err(rewrap_error)? as usize;
110
111 let mut buf = [0; MAX_EVENT_LENGTH + EVENT_PACKET_HEADER_LENGTH];
112 controller
113 .read_into(&mut buf[..EVENT_PACKET_HEADER_LENGTH + param_len])
114 .map_err(rewrap_error)?;
115
116 crate::event::Event::new(crate::event::Packet(
117 &buf[PACKET_HEADER_LENGTH..EVENT_PACKET_HEADER_LENGTH + param_len],
118 ))
119 .map_err(|e| nb::Error::Other(Error::BLE(e)))
120}
121
122impl<E, Vendor, VE, T> Hci<E, Vendor, VE> for T
123where
124 T: crate::Controller<Error = E, Header = CommandHeader>,
125{
126 fn read(&mut self) -> nb::Result<Packet<Vendor>, Error<E, VE>>
127 where
128 Vendor: crate::event::VendorEvent<Error = VE>,
129 {
130 match self.peek(0).map_err(rewrap_error)? {
131 PACKET_TYPE_HCI_EVENT => Ok(Packet::Event(read_event(self)?)),
132 x => Err(nb::Error::Other(Error::BadPacketType(x))),
133 }
134 }
135}