esp32_nimble/
ble_address.rs1use esp_idf_svc::sys::*;
2use num_enum::TryFromPrimitive;
3
4#[derive(PartialEq, Eq, TryFromPrimitive)]
6#[repr(u8)]
7pub enum BLEAddressType {
8 Public = BLE_ADDR_PUBLIC as _,
9 Random = BLE_ADDR_RANDOM as _,
10 PublicID = BLE_ADDR_PUBLIC_ID as _,
11 RandomID = BLE_ADDR_RANDOM_ID as _,
12}
13
14#[repr(transparent)]
15#[derive(Copy, Clone)]
16pub struct BLEAddress {
17 pub(crate) value: ble_addr_t,
18}
19
20impl BLEAddress {
21 pub fn from_le_bytes(val: [u8; 6], addr_type: BLEAddressType) -> Self {
22 Self {
23 value: ble_addr_t {
24 val,
25 type_: addr_type as _,
26 },
27 }
28 }
29
30 pub fn from_be_bytes(mut val: [u8; 6], addr_type: BLEAddressType) -> Self {
31 val.reverse();
32 Self::from_le_bytes(val, addr_type)
33 }
34
35 pub fn from_str(input: &str, addr_type: BLEAddressType) -> Option<Self> {
36 let mut val = [0u8; 6];
37
38 let mut nth = 0;
39 for byte in input.split([':', '-']) {
40 if nth == 6 {
41 return None;
42 }
43
44 val[nth] = u8::from_str_radix(byte, 16).ok()?;
45
46 nth += 1;
47 }
48
49 if nth != 6 {
50 return None;
51 }
52
53 Some(Self::from_be_bytes(val, addr_type))
54 }
55
56 pub fn as_le_bytes(&self) -> [u8; 6] {
58 self.value.val
59 }
60
61 pub fn as_be_bytes(&self) -> [u8; 6] {
62 let mut bytes = self.value.val;
63 bytes.reverse();
64 bytes
65 }
66
67 pub fn addr_type(&self) -> BLEAddressType {
69 BLEAddressType::try_from(self.value.type_).unwrap()
70 }
71}
72
73impl From<ble_addr_t> for BLEAddress {
74 fn from(value: ble_addr_t) -> Self {
75 Self { value }
76 }
77}
78
79impl From<BLEAddress> for ble_addr_t {
80 fn from(value: BLEAddress) -> Self {
81 value.value
82 }
83}
84
85impl core::fmt::Display for BLEAddress {
86 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
87 write!(
88 f,
89 "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}",
90 self.value.val[5],
91 self.value.val[4],
92 self.value.val[3],
93 self.value.val[2],
94 self.value.val[1],
95 self.value.val[0]
96 )
97 }
98}
99
100impl core::fmt::Debug for BLEAddress {
101 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
102 let type_str = match self.value.type_ as _ {
103 BLE_ADDR_RANDOM => "(random)",
104 BLE_ADDR_PUBLIC_ID => "(publicID)",
105 BLE_ADDR_RANDOM_ID => "(randomID)",
106 _ => "",
107 };
108 write!(f, "{self}{type_str}")
109 }
110}
111
112impl PartialEq for BLEAddress {
113 fn eq(&self, other: &Self) -> bool {
114 self.value.val == other.value.val
115 }
116}
117
118impl Eq for BLEAddress {}