git clone https://garage44.eu/jeroen/pinnacle.git.. /bt/src/hci.rs
//! HCI: the commands a host sends its controller and the events and ACL
//! data that come back, framed as H4 (UART transport: one byte saying
//! which, then the packet).
use alloc::vec::Vec;
/// A device address, as it is sent: least significant byte first.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Hash)]
pub struct Address(pub [u8; 6]);
impl Address {
/// "aa:bb:cc:dd:ee:ff", most significant byte first, as people write it.
pub fn text(&self) -> alloc::string::String {
let b = self.0;
alloc::format!(
"{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}",
b[5],
b[4],
b[3],
b[2],
b[1],
b[0]
)
}
}
pub const H4_COMMAND: u8 = 1;
pub const H4_ACL: u8 = 2;
pub const H4_EVENT: u8 = 4;
// Opcodes: OGF << 10 | OCF.
pub const RESET: u16 = 0x0c03;
pub const SET_EVENT_MASK: u16 = 0x0c01;
pub const READ_BD_ADDR: u16 = 0x1009;
pub const DISCONNECT: u16 = 0x0406;
pub const LE_SET_EVENT_MASK: u16 = 0x2001;
pub const LE_READ_BUFFER_SIZE: u16 = 0x2002;
pub const LE_SET_ADVERTISING_PARAMETERS: u16 = 0x2006;
pub const LE_SET_ADVERTISING_DATA: u16 = 0x2008;
pub const LE_SET_ADVERTISE_ENABLE: u16 = 0x200a;
pub const LE_SET_SCAN_PARAMETERS: u16 = 0x200b;
pub const LE_SET_SCAN_ENABLE: u16 = 0x200c;
pub const LE_CREATE_CONNECTION: u16 = 0x200d;
pub const LE_CREATE_CONNECTION_CANCEL: u16 = 0x200e;
pub const LE_START_ENCRYPTION: u16 = 0x2019;
pub const LE_LONG_TERM_KEY_REQUEST_REPLY: u16 = 0x201a;
pub const LE_LONG_TERM_KEY_REQUEST_NEGATIVE_REPLY: u16 = 0x201b;
// Events.
pub const EVT_DISCONNECTION_COMPLETE: u8 = 0x05;
pub const EVT_ENCRYPTION_CHANGE: u8 = 0x08;
pub const EVT_COMMAND_COMPLETE: u8 = 0x0e;
pub const EVT_COMMAND_STATUS: u8 = 0x0f;
pub const EVT_NUMBER_OF_COMPLETED_PACKETS: u8 = 0x13;
pub const EVT_LE_META: u8 = 0x3e;
pub const LE_CONNECTION_COMPLETE: u8 = 0x01;
pub const LE_ADVERTISING_REPORT: u8 = 0x02;
pub const LE_LONG_TERM_KEY_REQUEST: u8 = 0x05;
/// The status every command answers with when it went well.
pub const SUCCESS: u8 = 0;
/// Disconnection reasons.
pub const REASON_REMOTE_USER: u8 = 0x13;
pub const REASON_LOCAL_HOST: u8 = 0x16;
/// The link's integrity check failed: the two sides' keys differ.
pub const REASON_MIC_FAILURE: u8 = 0x3d;
/// The peer has no key for this link (it forgot the pairing).
pub const KEY_MISSING: u8 = 0x06;
/// Advertising data types.
pub const AD_FLAGS: u8 = 0x01;
pub const AD_UUIDS_16: u8 = 0x03;
pub const AD_UUIDS_128: u8 = 0x07;
pub const AD_SHORT_NAME: u8 = 0x08;
pub const AD_COMPLETE_NAME: u8 = 0x09;
/// One packet, as H4 frames it.
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Packet {
Command {
opcode: u16,
parameters: Vec<u8>,
},
/// ACL data: the connection handle, whether this continues an earlier
/// fragment, and the bytes.
Acl {
handle: u16,
continuing: bool,
data: Vec<u8>,
},
Event {
code: u8,
parameters: Vec<u8>,
},
}
impl Packet {
pub fn to_h4(&self) -> Vec<u8> {
let mut out = Vec::new();
match self {
Packet::Command { opcode, parameters } => {
out.push(H4_COMMAND);
out.extend_from_slice(&opcode.to_le_bytes());
out.push(parameters.len() as u8);
out.extend_from_slice(parameters);
}
Packet::Acl {
handle,
continuing,
data,
} => {
out.push(H4_ACL);
let flags = if *continuing { 0b01 } else { 0b00 };
out.extend_from_slice(&((handle & 0x0fff) | flags << 12).to_le_bytes());
out.extend_from_slice(&(data.len() as u16).to_le_bytes());
out.extend_from_slice(data);
}
Packet::Event { code, parameters } => {
out.push(H4_EVENT);
out.push(*code);
out.push(parameters.len() as u8);
out.extend_from_slice(parameters);
}
}
out
}
}
/// Takes H4 packets out of a stream of bytes, as they complete.
#[derive(Default)]
pub struct Framer {
buffer: Vec<u8>,
}
impl Framer {
pub fn push(&mut self, bytes: &[u8]) {
self.buffer.extend_from_slice(bytes);
}
/// The next whole packet, if the bytes so far hold one. A byte that
/// starts no known packet is skipped.
pub fn packet(&mut self) -> Option<Packet> {
loop {
let b = &self.buffer;
let (needed, packet) = match *b.first()? {
H4_COMMAND if b.len() >= 4 => {
let len = 4 + b[3] as usize;
(
len,
(b.len() >= len).then(|| Packet::Command {
opcode: u16::from_le_bytes([b[1], b[2]]),
parameters: b[4..len].to_vec(),
}),
)
}
H4_ACL if b.len() >= 5 => {
let len = 5 + u16::from_le_bytes([b[3], b[4]]) as usize;
let word = u16::from_le_bytes([b[1], b[2]]);
(
len,
(b.len() >= len).then(|| Packet::Acl {
handle: word & 0x0fff,
continuing: (word >> 12) & 0b11 == 0b01,
data: b[5..len].to_vec(),
}),
)
}
H4_EVENT if b.len() >= 3 => {
let len = 3 + b[2] as usize;
(
len,
(b.len() >= len).then(|| Packet::Event {
code: b[1],
parameters: b[3..len].to_vec(),
}),
)
}
H4_COMMAND | H4_ACL | H4_EVENT => return None,
_ => {
self.buffer.remove(0);
continue;
}
};
let packet = packet?;
self.buffer.drain(..needed);
return Some(packet);
}
}
}
/// The advertising data structures in `data`: (type, bytes).
pub fn ad_structures(data: &[u8]) -> impl Iterator<Item = (u8, &[u8])> {
let mut at = 0;
core::iter::from_fn(move || {
let len = *data.get(at)? as usize;
if len == 0 || at + 1 + len > data.len() {
return None;
}
let kind = data[at + 1];
let body = &data[at + 2..at + 1 + len];
at += 1 + len;
Some((kind, body))
})
}
/// The name in advertising data, complete or short.
pub fn ad_name(data: &[u8]) -> Option<&str> {
let mut short = None;
for (kind, body) in ad_structures(data) {
match kind {
AD_COMPLETE_NAME => return core::str::from_utf8(body).ok(),
AD_SHORT_NAME => short = core::str::from_utf8(body).ok(),
_ => {}
}
}
short
}
/// Advertising data: general discoverable, LE only, and the name, cut to
/// what fits the 31 bytes.
pub fn advertising_data(name: &str) -> Vec<u8> {
let mut out = alloc::vec![2, AD_FLAGS, 0x06];
let room = 31 - out.len() - 2;
let mut name = name;
let mut kind = AD_COMPLETE_NAME;
if name.len() > room {
let mut cut = room;
while !name.is_char_boundary(cut) {
cut -= 1;
}
name = &name[..cut];
kind = AD_SHORT_NAME;
}
out.push(name.len() as u8 + 1);
out.push(kind);
out.extend_from_slice(name.as_bytes());
out
}