1#[derive(Debug, Clone, Default, PartialEq)]
25pub struct Advertisement {
26 pub address: String,
28 pub random_address: bool,
30 pub rssi: i8,
31 pub local_name: Option<String>,
32 pub tx_power: Option<i8>,
33 pub appearance: Option<u16>,
35 pub service_uuids: Vec<String>,
37 pub manufacturer_data: Option<(u16, Vec<u8>)>,
39 pub service_data: Vec<(String, Vec<u8>)>,
41 pub connectable: bool,
43 pub raw: Vec<u8>,
50}
51
52#[cfg(target_os = "linux")]
57use crate::sys::format_address;
58
59#[cfg(not(target_os = "linux"))]
60fn format_address(wire: &[u8; 6]) -> String {
61 let mut out = String::with_capacity(17);
62 for (i, b) in wire.iter().rev().enumerate() {
63 if i > 0 {
64 out.push(':');
65 }
66 out.push_str(&format!("{b:02X}"));
67 }
68 out
69}
70
71mod ad {
73 pub const FLAGS: u8 = 0x01;
74 pub const INCOMPLETE_16: u8 = 0x02;
75 pub const COMPLETE_16: u8 = 0x03;
76 pub const INCOMPLETE_32: u8 = 0x04;
77 pub const COMPLETE_32: u8 = 0x05;
78 pub const INCOMPLETE_128: u8 = 0x06;
79 pub const COMPLETE_128: u8 = 0x07;
80 pub const SHORTENED_NAME: u8 = 0x08;
81 pub const COMPLETE_NAME: u8 = 0x09;
82 pub const TX_POWER: u8 = 0x0A;
83 pub const APPEARANCE: u8 = 0x19;
84 pub const SERVICE_DATA_16: u8 = 0x16;
85 pub const SERVICE_DATA_32: u8 = 0x20;
86 pub const SERVICE_DATA_128: u8 = 0x21;
87 pub const MANUFACTURER_DATA: u8 = 0xFF;
88}
89
90fn canonical_16(value: u16) -> String {
92 format!("0000{value:04x}-0000-1000-8000-00805f9b34fb")
93}
94
95fn canonical_32(value: u32) -> String {
96 format!("{value:08x}-0000-1000-8000-00805f9b34fb")
97}
98
99fn canonical_128(wire: &[u8]) -> Option<String> {
101 if wire.len() != 16 {
102 return None;
103 }
104 let hex: String = wire.iter().rev().map(|b| format!("{b:02x}")).collect();
105 Some(format!(
106 "{}-{}-{}-{}-{}",
107 &hex[0..8],
108 &hex[8..12],
109 &hex[12..16],
110 &hex[16..20],
111 &hex[20..32]
112 ))
113}
114
115pub fn parse_advertising_data(data: &[u8], into: &mut Advertisement) {
121 into.raw.extend_from_slice(data);
124 let mut i = 0;
125 while i < data.len() {
126 let length = data[i] as usize;
127 if length == 0 {
128 break;
129 }
130 if i + 1 + length > data.len() {
132 break;
133 }
134 let ad_type = data[i + 1];
135 let value = &data[i + 2..i + 1 + length];
136
137 match ad_type {
138 ad::FLAGS => {
139 if let Some(flags) = value.first() {
141 into.connectable = flags & 0x03 != 0;
142 }
143 }
144 ad::SHORTENED_NAME | ad::COMPLETE_NAME => {
145 if let Ok(name) = std::str::from_utf8(value) {
146 if ad_type == ad::COMPLETE_NAME || into.local_name.is_none() {
148 into.local_name = Some(name.to_owned());
149 }
150 }
151 }
152 ad::TX_POWER => into.tx_power = value.first().map(|b| *b as i8),
153 ad::INCOMPLETE_16 | ad::COMPLETE_16 => {
154 for pair in value.chunks_exact(2) {
155 into.service_uuids
156 .push(canonical_16(u16::from_le_bytes([pair[0], pair[1]])));
157 }
158 }
159 ad::INCOMPLETE_32 | ad::COMPLETE_32 => {
160 for quad in value.chunks_exact(4) {
161 into.service_uuids.push(canonical_32(u32::from_le_bytes([
162 quad[0], quad[1], quad[2], quad[3],
163 ])));
164 }
165 }
166 ad::INCOMPLETE_128 | ad::COMPLETE_128 => {
167 for block in value.chunks_exact(16) {
168 if let Some(uuid) = canonical_128(block) {
169 into.service_uuids.push(uuid);
170 }
171 }
172 }
173 ad::APPEARANCE => {
174 if value.len() >= 2 {
175 into.appearance = Some(u16::from_le_bytes([value[0], value[1]]));
176 }
177 }
178 ad::MANUFACTURER_DATA => {
179 if value.len() >= 2 {
180 into.manufacturer_data = Some((
181 u16::from_le_bytes([value[0], value[1]]),
182 value[2..].to_vec(),
183 ));
184 }
185 }
186 ad::SERVICE_DATA_16 => {
187 if value.len() >= 2 {
188 into.service_data.push((
189 canonical_16(u16::from_le_bytes([value[0], value[1]])),
190 value[2..].to_vec(),
191 ));
192 }
193 }
194 ad::SERVICE_DATA_32 => {
195 if value.len() >= 4 {
196 into.service_data.push((
197 canonical_32(u32::from_le_bytes([value[0], value[1], value[2], value[3]])),
198 value[4..].to_vec(),
199 ));
200 }
201 }
202 ad::SERVICE_DATA_128 => {
203 if value.len() >= 16 {
204 if let Some(uuid) = canonical_128(&value[..16]) {
205 into.service_data.push((uuid, value[16..].to_vec()));
206 }
207 }
208 }
209 _ => {}
210 }
211 i += 1 + length;
212 }
213}
214
215pub fn parse_advertising_report(body: &[u8]) -> Vec<Advertisement> {
220 let mut out = Vec::new();
221 let Some(&count) = body.first() else {
222 return out;
223 };
224 let mut i = 1;
225 for _ in 0..count {
226 if i + 9 > body.len() {
227 break;
228 }
229 let event_type = body[i];
230 let address_type = body[i + 1];
231 let mut wire = [0u8; 6];
232 wire.copy_from_slice(&body[i + 2..i + 8]);
233 let data_len = body[i + 8] as usize;
234 if i + 9 + data_len + 1 > body.len() {
235 break;
236 }
237 let data = &body[i + 9..i + 9 + data_len];
238 let rssi = body[i + 9 + data_len] as i8;
239
240 let mut advertisement = Advertisement {
241 address: format_address(&wire),
242 random_address: address_type == 0x01 || address_type == 0x03,
243 rssi,
244 connectable: event_type == 0x00 || event_type == 0x01,
246 ..Default::default()
247 };
248 parse_advertising_data(data, &mut advertisement);
249 out.push(advertisement);
250
251 i += 9 + data_len + 1;
252 }
253 out
254}
255
256pub fn parse_extended_advertising_report(body: &[u8]) -> Vec<Advertisement> {
264 const FIXED: usize = 24;
268
269 let mut out = Vec::new();
270 let Some(&count) = body.first() else {
271 return out;
272 };
273 let mut i = 1;
274 for _ in 0..count {
275 if i + FIXED > body.len() {
276 break;
277 }
278 let event_type = u16::from_le_bytes([body[i], body[i + 1]]);
279 let address_type = body[i + 2];
280 let mut wire = [0u8; 6];
281 wire.copy_from_slice(&body[i + 3..i + 9]);
282 let tx_power = body[i + 12] as i8;
283 let rssi = body[i + 13] as i8;
284 let data_len = body[i + FIXED - 1] as usize;
285 if i + FIXED + data_len > body.len() {
286 break;
287 }
288 let data = &body[i + FIXED..i + FIXED + data_len];
289
290 let mut advertisement = Advertisement {
291 address: format_address(&wire),
292 random_address: address_type == 0x01 || address_type == 0x03,
293 rssi,
294 connectable: event_type & 0x0001 != 0,
297 ..Default::default()
298 };
299 parse_advertising_data(data, &mut advertisement);
300 if tx_power != 127 && advertisement.tx_power.is_none() {
303 advertisement.tx_power = Some(tx_power);
304 }
305 out.push(advertisement);
306
307 i += FIXED + data_len;
308 }
309 out
310}
311
312#[cfg(target_os = "linux")]
315mod socket {
316 use super::{parse_advertising_report, parse_extended_advertising_report, Advertisement};
317 use crate::sys::{
318 close, errno, read, socket, write, AF_BLUETOOTH, BTPROTO_HCI, EINTR, SOCK_RAW,
319 };
320 use std::ffi::{c_int, c_long, c_ulong};
321 use std::sync::atomic::{AtomicBool, Ordering};
322 use std::sync::Arc;
323
324 const HCI_CHANNEL_RAW: u16 = 0;
325 const SOL_HCI: c_int = 0;
326 const HCI_FILTER: c_int = 2;
327 const HCI_EVENT_PKT: u8 = 0x04;
328 const EVT_LE_META: u8 = 0x3E;
329 const SUBEVT_LE_ADVERTISING_REPORT: u8 = 0x02;
330 const SUBEVT_LE_EXTENDED_ADVERTISING_REPORT: u8 = 0x0D;
331 const OGF_LE_CTL: u16 = 0x08;
332 const OCF_LE_SET_SCAN_PARAMETERS: u16 = 0x000B;
333 const OCF_LE_SET_SCAN_ENABLE: u16 = 0x000C;
334 const SOL_SOCKET: c_int = 1;
335 const SO_RCVTIMEO: c_int = 20;
336 const EAGAIN: i32 = 11;
338 const POLL_INTERVAL_US: c_long = 100_000;
340
341 #[repr(C)]
345 struct Timeval {
346 tv_sec: c_long,
347 tv_usec: c_long,
348 }
349
350 use crate::sys::{bind, bluetooth_setsockopt};
352 unsafe extern "C" {
353 fn ioctl(fd: c_int, request: c_ulong, ...) -> c_int;
356 }
357
358 #[repr(C, packed)]
359 struct SockAddrHci {
360 family: u16,
361 dev: u16,
362 channel: u16,
363 }
364
365 #[repr(C)]
368 struct HciFilter {
369 type_mask: u32,
370 event_mask: [u32; 2],
371 opcode: u16,
372 }
373
374 pub struct HciSocket {
376 fd: c_int,
377 scanning: AtomicBool,
378 }
379
380 impl Drop for HciSocket {
381 fn drop(&mut self) {
382 if self.scanning.load(Ordering::Acquire) {
383 let _ = self.set_scan_enable(false);
384 }
385 unsafe { close(self.fd) };
386 }
387 }
388
389 #[derive(Debug, Clone, PartialEq, Eq)]
391 pub struct DeviceInfo {
392 pub id: u16,
394 pub name: String,
396 pub address: String,
398 pub powered: bool,
400 }
401
402 const IOC_READ: u32 = 2;
408 const fn ior(kind: u8, number: u8, size: u32) -> u32 {
409 (IOC_READ << 30) | (size << 16) | ((kind as u32) << 8) | number as u32
410 }
411 const HCIGETDEVLIST: u32 = ior(b'H', 210, 4);
413 const HCIGETDEVINFO: u32 = ior(b'H', 211, 4);
415
416 const HCI_UP: u32 = 1 << 0;
418
419 const DEV_INFO_LEN: usize = 128;
422 const DEV_INFO_NAME: usize = 2;
424 const DEV_INFO_BDADDR: usize = 10;
425 const DEV_INFO_FLAGS: usize = 16;
426
427 pub fn devices() -> Result<Vec<DeviceInfo>, String> {
433 let fd = unsafe { socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI) };
436 if fd < 0 {
437 return Err(format!(
438 "could not open an HCI control socket (errno {})",
439 errno()
440 ));
441 }
442 struct Fd(c_int);
443 impl Drop for Fd {
444 fn drop(&mut self) {
445 unsafe { close(self.0) };
446 }
447 }
448 let fd = Fd(fd);
449
450 const MAX: u16 = 16;
455 const REQ: usize = 8;
456 let mut buffer = vec![0u8; 4 + REQ * MAX as usize];
457 buffer[0..2].copy_from_slice(&MAX.to_ne_bytes());
458 let rc = unsafe { ioctl(fd.0, HCIGETDEVLIST as _, buffer.as_mut_ptr()) };
459 if rc < 0 {
460 return Err(format!("HCIGETDEVLIST failed (errno {})", errno()));
461 }
462
463 let count = u16::from_ne_bytes([buffer[0], buffer[1]]).min(MAX);
464 let mut out = Vec::with_capacity(count as usize);
465 for i in 0..count as usize {
466 let at = 4 + i * REQ;
467 let id = u16::from_ne_bytes([buffer[at], buffer[at + 1]]);
468 if let Some(info) = device_info(fd.0, id) {
469 out.push(info);
470 }
471 }
472 out.sort_by_key(|d| d.id);
473 Ok(out)
474 }
475
476 fn device_info(fd: c_int, id: u16) -> Option<DeviceInfo> {
479 let mut buffer = vec![0u8; DEV_INFO_LEN];
480 buffer[0..2].copy_from_slice(&id.to_ne_bytes());
481 let rc = unsafe { ioctl(fd, HCIGETDEVINFO as _, buffer.as_mut_ptr()) };
482 if rc < 0 {
483 return None;
484 }
485
486 let name = &buffer[DEV_INFO_NAME..DEV_INFO_NAME + 8];
487 let name = name.iter().position(|b| *b == 0).unwrap_or(name.len());
488 let name =
489 String::from_utf8_lossy(&buffer[DEV_INFO_NAME..DEV_INFO_NAME + name]).into_owned();
490
491 let flags = u32::from_ne_bytes([
492 buffer[DEV_INFO_FLAGS],
493 buffer[DEV_INFO_FLAGS + 1],
494 buffer[DEV_INFO_FLAGS + 2],
495 buffer[DEV_INFO_FLAGS + 3],
496 ]);
497
498 Some(DeviceInfo {
499 id,
500 name: if name.is_empty() {
501 format!("hci{id}")
502 } else {
503 name
504 },
505 address: format_address(&buffer[DEV_INFO_BDADDR..DEV_INFO_BDADDR + 6]),
506 powered: flags & HCI_UP != 0,
507 })
508 }
509
510 fn format_address(bytes: &[u8]) -> String {
514 bytes
515 .iter()
516 .rev()
517 .map(|b| format!("{b:02X}"))
518 .collect::<Vec<_>>()
519 .join(":")
520 }
521
522 impl HciSocket {
523 pub fn open(device: u16) -> Result<Self, String> {
525 let fd = unsafe { socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI) };
526 if fd < 0 {
527 return Err(format!(
528 "could not open an HCI socket (errno {}); this needs CAP_NET_RAW",
529 errno()
530 ));
531 }
532 let socket = Self {
533 fd,
534 scanning: AtomicBool::new(false),
535 };
536
537 let filter = HciFilter {
539 type_mask: 1 << HCI_EVENT_PKT,
540 event_mask: [0, 1 << (EVT_LE_META - 32)],
541 opcode: 0,
542 };
543 let rc = unsafe {
544 bluetooth_setsockopt(
545 fd,
546 SOL_HCI,
547 HCI_FILTER,
548 (&raw const filter).cast(),
549 std::mem::size_of::<HciFilter>() as u32,
550 )
551 };
552 if rc < 0 {
553 return Err(format!("could not set the HCI filter (errno {})", errno()));
554 }
555
556 let addr = SockAddrHci {
557 family: AF_BLUETOOTH as u16,
558 dev: device,
559 channel: HCI_CHANNEL_RAW,
560 };
561 let len = std::mem::size_of::<SockAddrHci>() as u32;
562 let rc = unsafe { bind(fd, (&raw const addr).cast(), len) };
563 if rc < 0 {
564 return Err(format!(
565 "could not bind hci{device} (errno {}); is the adapter present and up?",
566 errno()
567 ));
568 }
569 Ok(socket)
570 }
571
572 fn command(&self, ogf: u16, ocf: u16, params: &[u8]) -> Result<(), String> {
573 let opcode = (ogf << 10) | ocf;
575 let mut packet = vec![0x01];
576 packet.extend_from_slice(&opcode.to_le_bytes());
577 packet.push(params.len() as u8);
578 packet.extend_from_slice(params);
579
580 let n = unsafe { write(self.fd, packet.as_ptr(), packet.len()) };
581 if n as usize != packet.len() {
582 return Err(format!(
583 "HCI command 0x{opcode:04x} failed (errno {})",
584 errno()
585 ));
586 }
587 Ok(())
588 }
589
590 pub fn set_scan_parameters(&self) -> Result<(), String> {
592 self.command(
595 OGF_LE_CTL,
596 OCF_LE_SET_SCAN_PARAMETERS,
597 &[0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x00],
598 )
599 }
600
601 pub fn set_scan_enable(&self, enable: bool) -> Result<(), String> {
602 self.command(
604 OGF_LE_CTL,
605 OCF_LE_SET_SCAN_ENABLE,
606 &[u8::from(enable), 0x00],
607 )?;
608 self.scanning.store(enable, Ordering::Release);
609 Ok(())
610 }
611
612 pub fn scan(
614 &self,
615 stop: Arc<AtomicBool>,
616 mut on_advertisement: impl FnMut(Advertisement),
617 ) -> Result<(), String> {
618 let timeout = Timeval {
625 tv_sec: 0,
626 tv_usec: POLL_INTERVAL_US,
627 };
628 let rc = unsafe {
629 bluetooth_setsockopt(
630 self.fd,
631 SOL_SOCKET,
632 SO_RCVTIMEO,
633 (&raw const timeout).cast(),
634 std::mem::size_of::<Timeval>() as u32,
635 )
636 };
637 if rc < 0 {
638 return Err(format!(
639 "could not set the HCI receive timeout (errno {})",
640 errno()
641 ));
642 }
643
644 self.set_scan_parameters()?;
645 self.set_scan_enable(true)?;
646
647 let mut buf = [0u8; 260];
648 while !stop.load(Ordering::Acquire) {
649 let n = unsafe { read(self.fd, buf.as_mut_ptr(), buf.len()) };
650 if n < 0 {
651 match errno() {
652 EINTR | EAGAIN => continue,
653 _ => break,
654 }
655 }
656 let packet = &buf[..n as usize];
657 if packet.len() < 4 || packet[0] != HCI_EVENT_PKT || packet[1] != EVT_LE_META {
659 continue;
660 }
661 let body = &packet[3..];
662 let advertisements = match body.first() {
663 Some(&SUBEVT_LE_ADVERTISING_REPORT) => parse_advertising_report(&body[1..]),
664 Some(&SUBEVT_LE_EXTENDED_ADVERTISING_REPORT) => {
665 parse_extended_advertising_report(&body[1..])
666 }
667 _ => continue,
668 };
669 for advertisement in advertisements {
670 on_advertisement(advertisement);
671 }
672 }
673 let _ = self.set_scan_enable(false);
674 Ok(())
675 }
676 }
677}
678
679#[cfg(target_os = "linux")]
680pub use socket::{devices, DeviceInfo, HciSocket};
681
682#[cfg(test)]
683mod tests {
684 use super::*;
685
686 #[test]
687 fn addresses_are_printed_in_written_order() {
688 assert_eq!(
690 format_address(&[0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA]),
691 "AA:BB:CC:DD:EE:FF"
692 );
693 }
694
695 #[test]
696 fn advertising_data_records_parse() {
697 let data = [
698 0x02, 0x01, 0x06, 0x03, 0x03, 0x0D, 0x18, 0x09, 0x09, b'P', b'o', b'l', b'a', b'r', b' ', b'H', b'1', 0x02, 0x0A, 0xF4, ];
703 let mut advertisement = Advertisement::default();
704 parse_advertising_data(&data, &mut advertisement);
705
706 assert_eq!(advertisement.local_name.as_deref(), Some("Polar H1"));
707 assert_eq!(
708 advertisement.service_uuids,
709 vec!["0000180d-0000-1000-8000-00805f9b34fb"]
710 );
711 assert_eq!(advertisement.tx_power, Some(-12));
712 assert!(advertisement.connectable);
713 }
714
715 #[test]
716 fn a_complete_name_wins_over_a_shortened_one() {
717 let data = [
718 0x03, 0x08, b'P', b'o', 0x06, 0x09, b'P', b'o', b'l', b'a', b'r', ];
721 let mut a = Advertisement::default();
722 parse_advertising_data(&data, &mut a);
723 assert_eq!(a.local_name.as_deref(), Some("Polar"));
724 }
725
726 #[test]
727 fn manufacturer_and_service_data_split_their_identifiers() {
728 let data = [
729 0x05, 0xFF, 0x4C, 0x00, 0x02, 0x15, 0x05, 0x16, 0x0F, 0x18, 0x5B, 0x01, ];
732 let mut a = Advertisement::default();
733 parse_advertising_data(&data, &mut a);
734 assert_eq!(a.manufacturer_data, Some((0x004C, vec![0x02, 0x15])));
735 assert_eq!(a.service_data.len(), 1);
736 assert_eq!(a.service_data[0].0, "0000180f-0000-1000-8000-00805f9b34fb");
737 assert_eq!(a.service_data[0].1, vec![0x5B, 0x01]);
738 }
739
740 #[test]
741 fn a_128_bit_service_uuid_is_reversed() {
742 let mut data = vec![0x11, 0x07];
743 data.extend_from_slice(&[
745 0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, 0x93, 0xF3, 0xA3, 0xB5, 0x01, 0x00,
746 0x40, 0x6E,
747 ]);
748 let mut a = Advertisement::default();
749 parse_advertising_data(&data, &mut a);
750 assert_eq!(
751 a.service_uuids,
752 vec!["6e400001-b5a3-f393-e0a9-e50e24dcca9e"]
753 );
754 }
755
756 #[test]
757 fn a_zero_length_record_terminates_the_payload() {
758 let data = [0x02, 0x01, 0x06, 0x00, 0xFF, 0xFF, 0xFF];
760 let mut a = Advertisement::default();
761 parse_advertising_data(&data, &mut a);
762 assert!(
763 a.manufacturer_data.is_none(),
764 "padding was decoded as a record"
765 );
766 }
767
768 #[test]
769 fn a_record_longer_than_the_payload_is_dropped() {
770 let data = [0x20, 0x09, b'x'];
772 let mut a = Advertisement::default();
773 parse_advertising_data(&data, &mut a);
774 assert_eq!(a.local_name, None);
775 }
776
777 #[test]
778 fn an_advertising_report_decodes() {
779 let mut body = vec![
780 0x01, 0x00, 0x00, 0xFF, 0xEE, 0xDD, 0xCC, 0xBB, 0xAA, 0x05, 0x02, 0x01, 0x06, 0x00, 0x00,
786 ];
787 body.push(0xC5); let reports = parse_advertising_report(&body);
789 assert_eq!(reports.len(), 1);
790 assert_eq!(reports[0].address, "AA:BB:CC:DD:EE:FF");
791 assert_eq!(reports[0].rssi, -59);
792 assert!(reports[0].connectable);
793 assert!(!reports[0].random_address);
794 }
795
796 #[test]
797 fn a_truncated_report_stops_rather_than_over_reading() {
798 let body = [0x02, 0x00, 0x00, 1, 2, 3, 4, 5, 6, 0x00, 0xC5];
800 let reports = parse_advertising_report(&body);
801 assert_eq!(reports.len(), 1);
802 assert!(parse_advertising_report(&[]).is_empty());
803 assert!(parse_advertising_report(&[0x01, 0x00]).is_empty());
804 }
805
806 #[test]
810 fn extended_advertising_reports_parse() {
811 let mut body = vec![0x01]; body.extend_from_slice(&0x0013u16.to_le_bytes()); body.push(0x00); body.extend_from_slice(&[0x01, 0x02, 0x03, 0x04, 0x05, 0x06]); body.push(0x01); body.push(0x01); body.push(0x00); body.push(0xF4u8); body.push(0xC0u8); body.extend_from_slice(&0u16.to_le_bytes()); body.push(0x00); body.extend_from_slice(&[0u8; 6]); let data = [
824 0x03, 0x03, 0x0D, 0x18, 0x06, 0x09, b'P', b'o', b'l', b'a', b'r', ];
827 body.push(data.len() as u8);
828 body.extend_from_slice(&data);
829
830 let reports = parse_extended_advertising_report(&body);
831 assert_eq!(reports.len(), 1);
832 let a = &reports[0];
833 assert_eq!(a.address, "06:05:04:03:02:01");
834 assert_eq!(a.rssi, -64);
835 assert_eq!(a.tx_power, Some(-12));
836 assert!(a.connectable);
837 assert_eq!(a.local_name.as_deref(), Some("Polar"));
838 assert_eq!(
839 a.service_uuids,
840 vec!["0000180d-0000-1000-8000-00805f9b34fb"]
841 );
842 }
843
844 #[test]
845 fn a_truncated_extended_report_is_dropped_not_guessed() {
846 assert!(parse_extended_advertising_report(&[0x01, 0x13, 0x00, 0x00]).is_empty());
848 assert!(parse_extended_advertising_report(&[]).is_empty());
849 }
850
851 #[test]
852 fn a_non_connectable_extended_report_says_so() {
853 let mut body = vec![0x01];
854 body.extend_from_slice(&0x0012u16.to_le_bytes()); body.push(0x01); body.extend_from_slice(&[0u8; 6]);
857 body.extend_from_slice(&[0x01, 0x01, 0x00, 127, 0xC0]);
858 body.extend_from_slice(&0u16.to_le_bytes());
859 body.push(0x00);
860 body.extend_from_slice(&[0u8; 6]);
861 body.push(0);
862 let reports = parse_extended_advertising_report(&body);
863 assert_eq!(reports.len(), 1);
864 assert!(!reports[0].connectable);
865 assert!(reports[0].random_address);
866 assert_eq!(reports[0].tx_power, None);
868 }
869}