1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
use alloc::vec::Vec;
use bstr::BStr;
use esp_idf_svc::sys;

use crate::{enums::AdvFlag, utilities::BleUuid};

pub struct BLEAdvertisedData<T>
where
  T: AsRef<[u8]>,
{
  payload: T,
}

impl<T: AsRef<[u8]>> BLEAdvertisedData<T> {
  pub(crate) fn new(payload: T) -> Self {
    Self { payload }
  }

  pub fn payload(&self) -> &[u8] {
    self.payload.as_ref()
  }

  #[allow(clippy::should_implement_trait)]
  pub fn clone(&self) -> BLEAdvertisedData<Vec<u8>> {
    BLEAdvertisedData::<Vec<u8>>::new(self.payload().to_vec())
  }

  /// Get the advertisement flags.
  pub fn adv_flags(&self) -> Option<AdvFlag> {
    let data = self
      .decode()
      .find(|x| x.ty == (sys::BLE_HS_ADV_TYPE_FLAGS as _))?;

    let ad_flag = data.data.first()?;
    AdvFlag::from_bits(*ad_flag)
  }

  pub fn is_advertising_service(&self, uuid: &BleUuid) -> bool {
    self.service_uuids().any(|x| &x == uuid)
  }

  pub fn service_uuids(&self) -> impl Iterator<Item = BleUuid> + '_ {
    ServiceUuidsIter {
      iter: self.decode(),
      current: None,
    }
  }

  pub fn name(&self) -> Option<&BStr> {
    let data = self.decode().find(|x| {
      x.ty == (sys::BLE_HS_ADV_TYPE_COMP_NAME as _)
        || x.ty == (sys::BLE_HS_ADV_TYPE_INCOMP_NAME as _)
    })?;
    Some(BStr::new(data.data))
  }

  pub fn tx_power(&self) -> Option<u8> {
    let data = self
      .decode()
      .find(|x| x.ty == (sys::BLE_HS_ADV_TYPE_TX_PWR_LVL as _))?;

    data.data.first().copied()
  }

  pub fn service_data(&self) -> Option<BLEServiceData> {
    for x in self.decode() {
      match x.ty as u32 {
        sys::BLE_HS_ADV_TYPE_SVC_DATA_UUID16 => {
          if let Some((uuid, service_data)) = x.data.split_at_checked(2) {
            let uuid = BleUuid::from_uuid16(u16::from_le_bytes(uuid.try_into().unwrap()));
            return Some(BLEServiceData { uuid, service_data });
          } else {
            ::log::error!("Length too small for BLE_HS_ADV_TYPE_SVC_DATA_UUID16");
          }
        }
        sys::BLE_HS_ADV_TYPE_SVC_DATA_UUID32 => {
          if let Some((uuid, service_data)) = x.data.split_at_checked(4) {
            let uuid = BleUuid::from_uuid32(u32::from_le_bytes(uuid.try_into().unwrap()));
            return Some(BLEServiceData { uuid, service_data });
          } else {
            ::log::error!("Length too small for BLE_HS_ADV_TYPE_SVC_DATA_UUID32");
          }
        }
        sys::BLE_HS_ADV_TYPE_SVC_DATA_UUID128 => {
          if let Some((uuid, service_data)) = x.data.split_at_checked(16) {
            let uuid = BleUuid::from_uuid128(uuid.try_into().unwrap());
            return Some(BLEServiceData { uuid, service_data });
          } else {
            ::log::error!("Length too small for BLE_HS_ADV_TYPE_SVC_DATA_UUID128");
          }
        }
        _ => {}
      }
    }
    None
  }

  pub fn manufacture_data(&self) -> Option<ManufactureData> {
    let data = self
      .decode()
      .find(|x| x.ty == (sys::BLE_HS_ADV_TYPE_MFG_DATA as _))?;

    let (id, payload) = data.data.split_at_checked(2)?;
    Some(ManufactureData {
      company_identifier: u16::from_le_bytes(id.try_into().unwrap()),
      payload,
    })
  }

  fn decode(&self) -> AdStructureIter<'_> {
    AdStructureIter {
      payload: self.payload(),
    }
  }
}

impl<T: AsRef<[u8]>> core::fmt::Debug for BLEAdvertisedData<T> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    let mut f = f.debug_struct("BLEAdvertisedData");

    #[cfg(feature = "debug")]
    f.field("types", &self.decode().map(|x| x.ty).collect::<Vec<_>>());

    if let Some(adv_flags) = self.adv_flags() {
      f.field("adv_flags", &adv_flags);
    }
    if let Some(name) = self.name() {
      f.field("name", &name);
    }
    if let Some(tx_power) = self.tx_power() {
      f.field("tx_power", &tx_power);
    }
    if let Some(manufacture_data) = self.manufacture_data() {
      f.field("manufacture_data", &manufacture_data);
    }
    let service_uuids: Vec<BleUuid> = self.service_uuids().collect();
    if !service_uuids.is_empty() {
      f.field("service_uuids", &service_uuids);
    }
    if let Some(service_data) = self.service_data() {
      f.field("service_data", &service_data);
    }
    f.finish()
  }
}

#[derive(Debug, Copy, Clone)]
pub struct BLEServiceData<'a> {
  pub uuid: BleUuid,
  pub service_data: &'a [u8],
}

#[derive(Debug, Copy, Clone)]
pub struct ManufactureData<'a> {
  pub company_identifier: u16,
  pub payload: &'a [u8],
}

struct AdData<'d> {
  ty: u8,
  data: &'d [u8],
}

struct AdStructureIter<'d> {
  payload: &'d [u8],
}

impl<'d> Iterator for AdStructureIter<'d> {
  type Item = AdData<'d>;

  fn next(&mut self) -> Option<Self::Item> {
    let length = (*self.payload.first()?) as usize;
    let (data, next_payload) = self.payload.split_at_checked(1 + length)?;
    self.payload = next_payload;
    if length == 0 {
      return None;
    }
    return Some(AdData {
      ty: unsafe { *data.get_unchecked(1) },
      data: data.get(2..(length + 1)).unwrap(),
    });
  }
}

struct ServiceUuidsIter<'d> {
  iter: AdStructureIter<'d>,
  current: Option<AdData<'d>>,
}

impl<'d> Iterator for ServiceUuidsIter<'d> {
  type Item = BleUuid;

  fn next(&mut self) -> Option<Self::Item> {
    if self.current.is_none() {
      loop {
        self.current = self.iter.next();
        if let Some(current) = &self.current {
          if matches!(
            current.ty as u32,
            sys::BLE_HS_ADV_TYPE_INCOMP_UUIDS16
              | sys::BLE_HS_ADV_TYPE_COMP_UUIDS16
              | sys::BLE_HS_ADV_TYPE_INCOMP_UUIDS32
              | sys::BLE_HS_ADV_TYPE_COMP_UUIDS32
              | sys::BLE_HS_ADV_TYPE_INCOMP_UUIDS128
              | sys::BLE_HS_ADV_TYPE_COMP_UUIDS128
          ) {
            break;
          }
        } else {
          return None;
        }
      }
    }

    let current = self.current.as_mut().unwrap();
    match current.ty as u32 {
      sys::BLE_HS_ADV_TYPE_INCOMP_UUIDS16 | sys::BLE_HS_ADV_TYPE_COMP_UUIDS16 => {
        if let Some((uuid, next)) = current.data.split_at_checked(2) {
          current.data = next;
          Some(BleUuid::from_uuid16(u16::from_le_bytes(
            uuid.try_into().unwrap(),
          )))
        } else {
          self.current = None;
          self.next()
        }
      }
      sys::BLE_HS_ADV_TYPE_INCOMP_UUIDS32 | sys::BLE_HS_ADV_TYPE_COMP_UUIDS32 => {
        if let Some((uuid, next)) = current.data.split_at_checked(4) {
          current.data = next;
          Some(BleUuid::from_uuid32(u32::from_le_bytes(
            uuid.try_into().unwrap(),
          )))
        } else {
          self.current = None;
          self.next()
        }
      }
      sys::BLE_HS_ADV_TYPE_INCOMP_UUIDS128 | sys::BLE_HS_ADV_TYPE_COMP_UUIDS128 => {
        if let Ok(data) = current.data.try_into() {
          self.current = None;
          Some(BleUuid::Uuid128(data))
        } else {
          self.current = None;
          self.next()
        }
      }
      _ => unreachable!(),
    }
  }
}