Krolyxon
Commit 4f7552f

Branches

Refs →

budctlcratesbudctl-coresrcbt.rs

171 lines · 5.1 KB · Rust

1//! Bluetooth addresses and UUIDs.
2
3use std::fmt;
4use std::str::FromStr;
5
6use serde::{Serialize, Serializer};
7
8use crate::error::{Error, Result};
9
10/// A Bluetooth device address, kept in the order people write it (`AA:BB:CC:DD:EE:FF`).
11#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
12pub struct BdAddr([u8; 6]);
13
14impl BdAddr {
15 /// An address from its bytes, in the order people write it.
16 pub const fn new(bytes: [u8; 6]) -> Self {
17 BdAddr(bytes)
18 }
19
20 /// The address as the kernel's `bdaddr_t` stores it: reversed.
21 /// Spec: transport.md#sockets
22 pub(crate) fn kernel_order(self) -> [u8; 6] {
23 let mut bytes = self.0;
24 bytes.reverse();
25 bytes
26 }
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct AddrParseError(String);
31
32impl fmt::Display for AddrParseError {
33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 write!(f, "{:?} is not a Bluetooth address like AA:BB:CC:DD:EE:FF", self.0)
35 }
36}
37
38impl std::error::Error for AddrParseError {}
39
40impl FromStr for BdAddr {
41 type Err = AddrParseError;
42
43 fn from_str(text: &str) -> std::result::Result<Self, Self::Err> {
44 let error = || AddrParseError(text.to_owned());
45 let mut bytes = [0u8; 6];
46 let mut parts = text.split(':');
47 for byte in &mut bytes {
48 let part = parts.next().ok_or_else(error)?;
49 if part.len() != 2 {
50 return Err(error());
51 }
52 *byte = u8::from_str_radix(part, 16).map_err(|_| error())?;
53 }
54 if parts.next().is_some() {
55 return Err(error());
56 }
57 Ok(BdAddr(bytes))
58 }
59}
60
61impl fmt::Display for BdAddr {
62 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63 let [a, b, c, d, e, g] = self.0;
64 write!(f, "{a:02X}:{b:02X}:{c:02X}:{d:02X}:{e:02X}:{g:02X}")
65 }
66}
67
68impl Serialize for BdAddr {
69 fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
70 serializer.collect_str(self)
71 }
72}
73
74/// A 128-bit Bluetooth UUID.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub struct Uuid(u128);
77
78/// `00000000-0000-1000-8000-00805F9B34FB`; short UUIDs are offsets into it.
79/// Spec: transport.md#sdp-data-elements
80const BASE_UUID: u128 = 0x0000_0000_0000_1000_8000_0080_5F9B_34FB;
81
82impl Uuid {
83 pub const fn from_u128(value: u128) -> Self {
84 Uuid(value)
85 }
86
87 /// A 16- or 32-bit UUID, expanded with the Bluetooth base UUID.
88 pub const fn from_u32(short: u32) -> Self {
89 Uuid(BASE_UUID | ((short as u128) << 96))
90 }
91
92 /// RFCOMM's protocol UUID (`0x0003`).
93 /// Spec: transport.md#sdp-rfcomm-channel
94 pub const RFCOMM: Uuid = Uuid::from_u32(0x0003);
95
96 pub fn to_be_bytes(self) -> [u8; 16] {
97 self.0.to_be_bytes()
98 }
99
100 /// A UUID as SDP encodes it: 2, 4 or 16 big-endian bytes.
101 /// Spec: transport.md#sdp-data-elements
102 pub(crate) fn from_sdp(bytes: &[u8]) -> Result<Self> {
103 match *bytes {
104 [a, b] => Ok(Uuid::from_u32(u32::from(u16::from_be_bytes([a, b])))),
105 [a, b, c, d] => Ok(Uuid::from_u32(u32::from_be_bytes([a, b, c, d]))),
106 _ => {
107 let long: [u8; 16] = bytes
108 .try_into()
109 .map_err(|_| Error::Protocol(format!("SDP UUID of {} bytes", bytes.len())))?;
110 Ok(Uuid(u128::from_be_bytes(long)))
111 }
112 }
113 }
114}
115
116impl fmt::Display for Uuid {
117 /// Lowercase and hyphenated, as BlueZ writes it.
118 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
119 let hex = format!("{:032x}", self.0);
120 let part = |range: std::ops::Range<usize>| hex.get(range).unwrap_or_default();
121 write!(
122 f,
123 "{}-{}-{}-{}-{}",
124 part(0..8),
125 part(8..12),
126 part(12..16),
127 part(16..20),
128 part(20..32)
129 )
130 }
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136
137 #[test]
138 fn address_round_trip_and_kernel_order() {
139 let addr: BdAddr = "AA:bb:CC:01:02:03".parse().unwrap();
140 assert_eq!(addr.to_string(), "AA:BB:CC:01:02:03");
141 assert_eq!(addr.kernel_order(), [0x03, 0x02, 0x01, 0xCC, 0xBB, 0xAA]);
142 }
143
144 #[test]
145 fn bad_addresses_are_rejected() {
146 for text in [
147 "",
148 "AA:BB:CC:DD:EE",
149 "AA:BB:CC:DD:EE:FF:00",
150 "AA:BB:CC:DD:EE:F",
151 "GG:BB:CC:DD:EE:FF",
152 ] {
153 assert!(text.parse::<BdAddr>().is_err(), "{text}");
154 }
155 }
156
157 #[test]
158 fn uuid_display_matches_bluez() {
159 let uuid = Uuid::from_u128(0x0000_079A_D102_11E1_9B23_0002_5B00_A5A5);
160 assert_eq!(uuid.to_string(), "0000079a-d102-11e1-9b23-00025b00a5a5");
161 assert_eq!(Uuid::RFCOMM.to_string(), "00000003-0000-1000-8000-00805f9b34fb");
162 }
163
164 #[test]
165 fn short_sdp_uuids_expand_with_the_base() {
166 assert_eq!(Uuid::from_sdp(&[0x00, 0x03]).unwrap(), Uuid::RFCOMM);
167 assert_eq!(Uuid::from_sdp(&[0x00, 0x00, 0x00, 0x03]).unwrap(), Uuid::RFCOMM);
168 assert_eq!(Uuid::from_sdp(&Uuid::RFCOMM.to_be_bytes()).unwrap(), Uuid::RFCOMM);
169 assert!(Uuid::from_sdp(&[1, 2, 3]).is_err());
170 }
171}