Krolyxon
Commit 4c49f6c

Branches

Refs →

budctlcratesbudctl-coresrcbt.rs

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