use std::fmt;
use std::str::FromStr;
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct BluetoothAddress([u8; 6]);
impl BluetoothAddress {
pub const fn from_octets(octets: [u8; 6]) -> Self {
Self(octets)
}
pub const fn octets(self) -> [u8; 6] {
self.0
}
pub fn as_str(&self) -> String {
self.to_string()
}
}
impl fmt::Debug for BluetoothAddress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("BluetoothAddress")
.field(&self.to_string())
.finish()
}
}
impl fmt::Display for BluetoothAddress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (index, octet) in self.0.iter().enumerate() {
if index != 0 {
f.write_str(":")?;
}
write!(f, "{octet:02X}")?;
}
Ok(())
}
}
impl FromStr for BluetoothAddress {
type Err = ClassicAddressError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let parts: Vec<_> = value.split(':').collect();
if parts.len() != 6 {
return Err(ClassicAddressError::WrongOctetCount);
}
let mut octets = [0; 6];
for (index, part) in parts.iter().enumerate() {
if part.len() != 2 {
return Err(ClassicAddressError::InvalidOctet);
}
octets[index] =
u8::from_str_radix(part, 16).map_err(|_| ClassicAddressError::InvalidOctet)?;
}
Ok(Self(octets))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClassicAddressError {
WrongOctetCount,
InvalidOctet,
}
impl fmt::Display for ClassicAddressError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::WrongOctetCount => f.write_str("a Bluetooth address needs six octets"),
Self::InvalidOctet => f.write_str("a Bluetooth address octet must be two hex digits"),
}
}
}
impl std::error::Error for ClassicAddressError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct ClassOfDevice {
pub service_class: u16,
pub major_device: u8,
pub minor_device: u8,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClassicDevice {
pub address: Option<BluetoothAddress>,
pub name: Option<String>,
pub class_of_device: Option<ClassOfDevice>,
pub bonded: bool,
pub authenticated: bool,
pub connected: bool,
}
impl ClassOfDevice {
pub const fn from_raw(raw: u32) -> Self {
Self {
service_class: ((raw >> 13) & 0x07ff) as u16,
major_device: ((raw >> 8) & 0x1f) as u8,
minor_device: ((raw >> 2) & 0x3f) as u8,
}
}
pub const fn raw(self) -> u32 {
((self.service_class as u32 & 0x07ff) << 13)
| ((self.major_device as u32 & 0x1f) << 8)
| ((self.minor_device as u32 & 0x3f) << 2)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct RfcommChannel(u8);
impl RfcommChannel {
pub const fn new(channel: u8) -> Option<Self> {
if channel == 0 || channel > 30 {
None
} else {
Some(Self(channel))
}
}
pub const fn get(self) -> u8 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ClassicPsm(u16);
impl ClassicPsm {
pub const fn new(psm: u16) -> Option<Self> {
if psm == 0 || psm & 0x0101 != 0x0001 {
None
} else {
Some(Self(psm))
}
}
pub const fn get(self) -> u16 {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClassicSecurity {
None,
Authentication,
Encryption,
SecureEncryption,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn addresses_round_trip_in_written_order() {
let address: BluetoothAddress = "AA:bb:01:02:03:FF".parse().unwrap();
assert_eq!(address.octets(), [0xAA, 0xBB, 1, 2, 3, 0xFF]);
assert_eq!(address.to_string(), "AA:BB:01:02:03:FF");
}
#[test]
fn malformed_addresses_are_rejected() {
assert!("AA:BB:CC:DD:EE".parse::<BluetoothAddress>().is_err());
assert!("AA:BB:CC:DD:EE:GG".parse::<BluetoothAddress>().is_err());
assert!("A:BB:CC:DD:EE:FF".parse::<BluetoothAddress>().is_err());
}
#[test]
fn class_of_device_round_trips() {
let class = ClassOfDevice {
service_class: 0x123,
major_device: 0x12,
minor_device: 0x21,
};
assert_eq!(ClassOfDevice::from_raw(class.raw()), class);
}
#[test]
fn endpoint_ranges_are_checked() {
assert_eq!(RfcommChannel::new(1).unwrap().get(), 1);
assert!(RfcommChannel::new(0).is_none());
assert!(RfcommChannel::new(31).is_none());
assert!(ClassicPsm::new(0x1002).is_none());
assert_eq!(ClassicPsm::new(0x1003).unwrap().get(), 0x1003);
}
}