//! Talking to the `bt` service: scanning, connecting, GATT. Messages are a //! kind byte, then the body; the service tells every client what happens. use alloc::string::String; use alloc::vec::Vec; use pinnacle_bt::gatt::{Characteristic, Service, Uuid}; use pinnacle_bt::hci::Address; use pinnacle_rt::{Channel, Received}; // Client → service. /// Start scanning for devices (no body). pub const SCAN: u8 = 1; /// Stop scanning. pub const STOP: u8 = 2; /// Connect (body: the address, 6 bytes). pub const CONNECT: u8 = 3; /// Disconnect (body: the connection, u16). pub const DISCONNECT: u8 = 4; /// Ask for a peer's services (body: the connection). pub const DISCOVER: u8 = 5; /// Read a value (body: connection u16, handle u16). pub const READ: u8 = 6; /// Write a value (body: connection, handle, the value). pub const WRITE: u8 = 7; /// Notifications on or off (body: connection, the client configuration /// handle, on u8). pub const SUBSCRIBE: u8 = 8; /// Ask for the devices found so far (answered with DEVICES). pub const DEVICES: u8 = 9; /// Ask for the state (answered with STATE). pub const STATE: u8 = 10; /// Pair with a connected device (body: the connection). pub const PAIR: u8 = 11; /// The person's answer to ASK (body: the connection, yes u8). pub const CONFIRM: u8 = 12; /// Forget a paired device (body: its address). pub const FORGET: u8 = 13; /// Ask for the paired devices (answered with BONDS_ARE). pub const BONDS: u8 = 14; // Service → client. /// ready u8, this device's address (6), its name. pub const STATE_IS: u8 = 0x80; /// A device found, or its name learnt: address (6), rssi i8, name. pub const DEVICE: u8 = 0x81; /// Every device found: count u8, then per device address (6), rssi i8, /// name length u8, name. pub const DEVICES_ARE: u8 = 0x82; /// connection u16, address (6), central u8. pub const CONNECTED: u8 = 0x83; /// connection u16, address (6). pub const DISCONNECTED: u8 = 0x84; /// connection u16, then the services ([`services_from`]). pub const SERVICES: u8 = 0x85; /// connection u16, handle u16, error u8 (0: the value follows). pub const VALUE: u8 = 0x86; /// connection u16, handle u16, ok u8. pub const WRITTEN: u8 = 0x87; /// connection u16, handle u16, the value. pub const NOTIFIED: u8 = 0x88; /// Pairing asks the person: connection u16, address (6), then the number /// to compare as u32, or nothing (may it pair?). pub const ASK: u8 = 0x89; /// connection u16, address (6), compared u8. pub const PAIRED: u8 = 0x8a; /// connection u16, address (6), reason u8 (`pinnacle_bt::smp`). pub const PAIR_FAILED: u8 = 0x8b; /// The link is encrypted: connection u16, address (6). pub const ENCRYPTED: u8 = 0x8c; /// A paired device refused the key kept: connection u16, address (6). pub const KEY_REFUSED: u8 = 0x8d; /// The paired devices: count u8, then per device address (6), compared /// u8, name length u8, name. pub const BONDS_ARE: u8 = 0x8e; /// Pairing by passkey: connection u16, address (6), then the passkey as /// u32 for the person to type on the device (a keyboard), or nothing (it /// shows one to type here). CONFIRM with no cancels. pub const PASSKEY: u8 = 0x8f; /// A paired keyboard's keys go to the app in front, or stopped: connection /// u16, address (6), on u8. pub const KEYBOARD: u8 = 0x90; pub fn message(kind: u8, body: &[u8]) -> Vec { let mut m = alloc::vec![kind]; m.extend_from_slice(body); m } fn u16_at(b: &[u8], at: usize) -> Option { Some(u16::from_le_bytes([*b.get(at)?, *b.get(at + 1)?])) } fn address_at(b: &[u8], at: usize) -> Option
{ Some(Address(b.get(at..at + 6)?.try_into().ok()?)) } /// A device as the service lists it. #[derive(Clone, PartialEq, Eq, Debug)] pub struct Device { pub address: Address, pub rssi: i8, pub name: Option, } impl Device { /// The name, or the address for a device that gave none. pub fn label(&self) -> String { self.name.clone().unwrap_or_else(|| self.address.text()) } } /// Services, as SERVICES carries them: per service the UUID (length byte, /// bytes), handle, end, and its characteristics (count, then each: UUID, /// properties, value handle, configuration handle or 0). pub fn services_bytes(services: &[Service]) -> Vec { let mut out = alloc::vec![services.len() as u8]; let uuid = |out: &mut Vec, u: &Uuid| { let b = u.bytes(); out.push(b.len() as u8); out.extend_from_slice(&b); }; for s in services { uuid(&mut out, &s.uuid); out.extend_from_slice(&s.handle.to_le_bytes()); out.extend_from_slice(&s.end.to_le_bytes()); out.push(s.characteristics.len() as u8); for c in &s.characteristics { uuid(&mut out, &c.uuid); out.push(c.properties); out.extend_from_slice(&c.handle.to_le_bytes()); out.extend_from_slice(&c.configuration.unwrap_or(0).to_le_bytes()); } } out } pub fn services_from(b: &[u8]) -> Option> { let mut at = 0; let take_uuid = |at: &mut usize| -> Option { let len = *b.get(*at)? as usize; let u = Uuid::parse(b.get(*at + 1..*at + 1 + len)?)?; *at += 1 + len; Some(u) }; let count = *b.first()? as usize; at += 1; let mut services = Vec::with_capacity(count); for _ in 0..count { let uuid = take_uuid(&mut at)?; let handle = u16_at(b, at)?; let end = u16_at(b, at + 2)?; let chars = *b.get(at + 4)? as usize; at += 5; let mut characteristics = Vec::with_capacity(chars); for _ in 0..chars { let uuid = take_uuid(&mut at)?; let properties = *b.get(at)?; let handle = u16_at(b, at + 1)?; let configuration = u16_at(b, at + 3)?; at += 5; characteristics.push(Characteristic { uuid, properties, handle, configuration: (configuration != 0).then_some(configuration), value: Vec::new(), }); } services.push(Service { uuid, handle, end, characteristics, }); } Some(services) } /// A device paired with, as the service lists it. #[derive(Clone, PartialEq, Eq, Debug)] pub struct Paired { pub address: Address, /// Numbers were compared at pairing (not, for a device without a display). pub compared: bool, pub name: Option, } impl Paired { pub fn label(&self) -> String { self.name.clone().unwrap_or_else(|| self.address.text()) } } /// A paired device's bytes, as BONDS_ARE carries one. pub fn paired_bytes(p: &Paired) -> Vec { let mut out = p.address.0.to_vec(); out.push(u8::from(p.compared)); let name = p.name.as_deref().unwrap_or("").as_bytes(); let len = name.len().min(255); out.push(len as u8); out.extend_from_slice(&name[..len]); out } fn paired_at(b: &[u8], at: usize) -> Option<(Paired, usize)> { let address = address_at(b, at)?; let compared = *b.get(at + 6)? != 0; let len = *b.get(at + 7)? as usize; let name = b.get(at + 8..at + 8 + len)?; let name = (!name.is_empty()).then(|| String::from_utf8_lossy(name).into_owned()); Some(( Paired { address, compared, name, }, at + 8 + len, )) } /// What the service said. #[derive(Clone, PartialEq, Eq, Debug)] pub enum Said { State { ready: bool, address: Address, name: String, }, Device(Device), Devices(Vec), Connected { connection: u16, address: Address, central: bool, }, Disconnected { connection: u16, address: Address, }, Services { connection: u16, services: Vec, }, Value { connection: u16, handle: u16, value: Result, u8>, }, Written { connection: u16, handle: u16, ok: bool, }, Notified { connection: u16, handle: u16, value: Vec, }, Ask { connection: u16, address: Address, code: Option, }, Paired { connection: u16, address: Address, compared: bool, }, PairFailed { connection: u16, address: Address, reason: u8, }, Encrypted { connection: u16, address: Address, }, KeyRefused { connection: u16, address: Address, }, Bonds(Vec), Passkey { connection: u16, address: Address, passkey: Option, }, Keyboard { connection: u16, address: Address, on: bool, }, } fn device_at(b: &[u8], at: usize) -> Option<(Device, usize)> { let address = address_at(b, at)?; let rssi = *b.get(at + 6)? as i8; let len = *b.get(at + 7)? as usize; let name = b.get(at + 8..at + 8 + len)?; let name = (!name.is_empty()).then(|| String::from_utf8_lossy(name).into_owned()); Some((Device { address, rssi, name }, at + 8 + len)) } pub fn parse(m: &[u8]) -> Option { let body = m.get(1..)?; Some(match *m.first()? { STATE_IS => Said::State { ready: *body.first()? != 0, address: address_at(body, 1)?, name: String::from_utf8_lossy(body.get(7..)?).into_owned(), }, DEVICE => Said::Device(device_at(body, 0)?.0), DEVICES_ARE => { let count = *body.first()? as usize; let mut at = 1; let mut devices = Vec::with_capacity(count); for _ in 0..count { let (device, next) = device_at(body, at)?; devices.push(device); at = next; } Said::Devices(devices) } CONNECTED => Said::Connected { connection: u16_at(body, 0)?, address: address_at(body, 2)?, central: *body.get(8)? != 0, }, DISCONNECTED => Said::Disconnected { connection: u16_at(body, 0)?, address: address_at(body, 2)?, }, SERVICES => Said::Services { connection: u16_at(body, 0)?, services: services_from(body.get(2..)?)?, }, VALUE => Said::Value { connection: u16_at(body, 0)?, handle: u16_at(body, 2)?, value: match *body.get(4)? { 0 => Ok(body[5..].to_vec()), error => Err(error), }, }, WRITTEN => Said::Written { connection: u16_at(body, 0)?, handle: u16_at(body, 2)?, ok: *body.get(4)? != 0, }, NOTIFIED => Said::Notified { connection: u16_at(body, 0)?, handle: u16_at(body, 2)?, value: body.get(4..)?.to_vec(), }, ASK => Said::Ask { connection: u16_at(body, 0)?, address: address_at(body, 2)?, code: body.get(8..12).map(|c| u32::from_le_bytes(c.try_into().unwrap())), }, PAIRED => Said::Paired { connection: u16_at(body, 0)?, address: address_at(body, 2)?, compared: *body.get(8)? != 0, }, PAIR_FAILED => Said::PairFailed { connection: u16_at(body, 0)?, address: address_at(body, 2)?, reason: *body.get(8)?, }, ENCRYPTED => Said::Encrypted { connection: u16_at(body, 0)?, address: address_at(body, 2)?, }, KEY_REFUSED => Said::KeyRefused { connection: u16_at(body, 0)?, address: address_at(body, 2)?, }, BONDS_ARE => { let count = *body.first()? as usize; let mut at = 1; let mut all = Vec::with_capacity(count); for _ in 0..count { let (p, next) = paired_at(body, at)?; all.push(p); at = next; } Said::Bonds(all) } PASSKEY => Said::Passkey { connection: u16_at(body, 0)?, address: address_at(body, 2)?, passkey: body.get(8..12).map(|c| u32::from_le_bytes(c.try_into().unwrap())), }, KEYBOARD => Said::Keyboard { connection: u16_at(body, 0)?, address: address_at(body, 2)?, on: *body.get(8)? != 0, }, _ => return None, }) } /// A device's bytes, as DEVICE and DEVICES carry one. pub fn device_bytes(address: Address, rssi: i8, name: Option<&str>) -> Vec { let mut out = address.0.to_vec(); out.push(rssi as u8); let name = name.unwrap_or("").as_bytes(); out.push(name.len().min(255) as u8); out.extend_from_slice(&name[..name.len().min(255)]); out } /// A connection to the `bt` service. pub struct Client { channel: Channel, } impl Client { /// Connects, waiting up to `ms` for the service to be there. pub fn connect(ms: u64) -> Option { let until = pinnacle_rt::time() + ms; loop { if let Some(channel) = pinnacle_rt::connect("bt") { return Some(Client { channel }); } if pinnacle_rt::time() >= until { return None; } pinnacle_rt::sleep(50); } } pub fn channel(&self) -> &Channel { &self.channel } pub fn send(&self, kind: u8, body: &[u8]) { self.channel.send(&message(kind, body), Vec::new()); } pub fn scan(&self) { self.send(SCAN, &[]); } pub fn stop(&self) { self.send(STOP, &[]); } pub fn connect_to(&self, address: Address) { self.send(CONNECT, &address.0); } pub fn disconnect(&self, connection: u16) { self.send(DISCONNECT, &connection.to_le_bytes()); } pub fn discover(&self, connection: u16) { self.send(DISCOVER, &connection.to_le_bytes()); } pub fn read(&self, connection: u16, handle: u16) { let mut b = connection.to_le_bytes().to_vec(); b.extend_from_slice(&handle.to_le_bytes()); self.send(READ, &b); } pub fn write(&self, connection: u16, handle: u16, value: &[u8]) { let mut b = connection.to_le_bytes().to_vec(); b.extend_from_slice(&handle.to_le_bytes()); b.extend_from_slice(value); self.send(WRITE, &b); } pub fn subscribe(&self, connection: u16, configuration: u16, on: bool) { let mut b = connection.to_le_bytes().to_vec(); b.extend_from_slice(&configuration.to_le_bytes()); b.push(u8::from(on)); self.send(SUBSCRIBE, &b); } pub fn ask_devices(&self) { self.send(DEVICES, &[]); } pub fn ask_state(&self) { self.send(STATE, &[]); } pub fn pair(&self, connection: u16) { self.send(PAIR, &connection.to_le_bytes()); } pub fn confirm(&self, connection: u16, yes: bool) { let mut b = connection.to_le_bytes().to_vec(); b.push(u8::from(yes)); self.send(CONFIRM, &b); } pub fn forget(&self, address: Address) { self.send(FORGET, &address.0); } pub fn ask_bonds(&self) { self.send(BONDS, &[]); } /// Waits for the service's next word, until `deadline` (ms since boot). pub fn next(&self, deadline: Option) -> Option { let mut buffer = alloc::vec![0u8; pinnacle_rt::abi::MAX_MESSAGE]; match pinnacle_rt::receive(&[&self.channel], &mut buffer, deadline) { Received::Message { len, .. } => parse(&buffer[..len]), _ => None, } } }