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
extern crate nb;
use byteorder::{ByteOrder, LittleEndian};
const PACKET_TYPE_HCI_COMMAND: u8 = 0x01;
const PACKET_TYPE_HCI_EVENT: u8 = 0x04;
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum Error<E, VE> {
BadPacketType(u8),
BLE(crate::event::Error<VE>),
Comm(E),
}
#[derive(Clone, Debug)]
pub enum Packet<Vendor>
where
Vendor: crate::event::VendorEvent,
{
Event(crate::Event<Vendor>),
}
pub struct CommandHeader {
opcode: crate::opcode::Opcode,
param_len: u8,
}
pub trait Hci<E, Vendor, VE>: super::Hci<E> {
fn read(&mut self) -> nb::Result<Packet<Vendor>, Error<E, VE>>
where
Vendor: crate::event::VendorEvent<Error = VE>;
}
impl super::HciHeader for CommandHeader {
const HEADER_LENGTH: usize = 4;
fn new(opcode: crate::opcode::Opcode, param_len: usize) -> CommandHeader {
CommandHeader {
opcode,
param_len: param_len as u8,
}
}
fn copy_into_slice(&self, buffer: &mut [u8]) {
buffer[0] = PACKET_TYPE_HCI_COMMAND;
LittleEndian::write_u16(&mut buffer[1..=2], self.opcode.0);
buffer[3] = self.param_len;
}
}
fn rewrap_error<E, VE>(e: nb::Error<E>) -> nb::Error<Error<E, VE>> {
match e {
nb::Error::WouldBlock => nb::Error::WouldBlock,
nb::Error::Other(err) => nb::Error::Other(Error::Comm(err)),
}
}
fn read_event<E, T, Vendor, VE>(
controller: &mut T,
) -> nb::Result<crate::Event<Vendor>, Error<E, VE>>
where
T: crate::Controller<Error = E>,
Vendor: crate::event::VendorEvent<Error = VE>,
{
const MAX_EVENT_LENGTH: usize = 255;
const PACKET_HEADER_LENGTH: usize = 1;
const EVENT_PACKET_HEADER_LENGTH: usize = 3;
const PARAM_LEN_BYTE: usize = 2;
let param_len = controller.peek(PARAM_LEN_BYTE).map_err(rewrap_error)? as usize;
let mut buf = [0; MAX_EVENT_LENGTH + EVENT_PACKET_HEADER_LENGTH];
controller
.read_into(&mut buf[..EVENT_PACKET_HEADER_LENGTH + param_len])
.map_err(rewrap_error)?;
crate::event::Event::new(crate::event::Packet(
&buf[PACKET_HEADER_LENGTH..EVENT_PACKET_HEADER_LENGTH + param_len],
))
.map_err(|e| nb::Error::Other(Error::BLE(e)))
}
impl<E, Vendor, VE, T> Hci<E, Vendor, VE> for T
where
T: crate::Controller<Error = E, Header = CommandHeader>,
{
fn read(&mut self) -> nb::Result<Packet<Vendor>, Error<E, VE>>
where
Vendor: crate::event::VendorEvent<Error = VE>,
{
match self.peek(0).map_err(rewrap_error)? {
PACKET_TYPE_HCI_EVENT => Ok(Packet::Event(read_event(self)?)),
x => Err(nb::Error::Other(Error::BadPacketType(x))),
}
}
}