aranet_core/util.rs
1//! Utility functions for aranet-core.
2//!
3//! This module contains shared utility functions used across the crate.
4
5use btleplug::api::PeripheralProperties;
6use btleplug::platform::PeripheralId;
7
8/// Format a peripheral ID as a string.
9///
10/// On macOS, peripheral IDs are UUIDs. On other platforms, they may be
11/// MAC addresses or other formats. This function extracts the useful
12/// identifier string.
13///
14/// # Example
15///
16/// ```ignore
17/// use aranet_core::util::format_peripheral_id;
18///
19/// let id = peripheral.id();
20/// let formatted = format_peripheral_id(&id);
21/// println!("Device: {}", formatted);
22/// ```
23pub fn format_peripheral_id(id: &PeripheralId) -> String {
24 format!("{:?}", id)
25 .trim_start_matches("PeripheralId(")
26 .trim_end_matches(')')
27 .to_string()
28}
29
30/// Create an identifier string from an address and peripheral ID.
31///
32/// On macOS where addresses are 00:00:00:00:00:00, uses the peripheral ID.
33/// On other platforms, uses the Bluetooth address.
34pub fn create_identifier(address: &str, peripheral_id: &PeripheralId) -> String {
35 if address == "00:00:00:00:00:00" {
36 format_peripheral_id(peripheral_id)
37 } else {
38 address.to_string()
39 }
40}
41
42/// Whether a peripheral that has advertised no name is named by btleplug's
43/// `local_name`. Only on macOS, where `local_name` is then CoreBluetooth's own
44/// name for the peripheral (btleplug 0.13.5
45/// `src/corebluetooth/internal.rs:1003-1008`). On Linux it is then BlueZ's
46/// `Alias` (`src/bluez/peripheral.rs:155`), which for a device BlueZ has no
47/// name for is a name the user chose, or else the address with dashes. On
48/// Windows a connect sets it to the system's name for the device
49/// (`src/winrtble/peripheral.rs:523-531`). aranet has never used either as a
50/// sensor's name.
51const UNADVERTISED_NAME_IS_LOCAL_NAME: bool = cfg!(target_os = "macos");
52
53/// The name of a peripheral as aranet uses it: the name aranet shows, matches
54/// a device query against and detects the sensor type from.
55///
56/// It is the name the device advertises, which btleplug reports as
57/// `advertisement_name`. On macOS only, a peripheral that has advertised no
58/// name gets the name CoreBluetooth holds for it, which btleplug reports as
59/// `local_name`.
60///
61/// Call this function and do not read either field yourself.
62/// `advertisement_name` alone leaves a macOS peripheral that has advertised
63/// no name without one. `local_name` means something different on each
64/// operating system in btleplug 0.13.5 (the files named below are that
65/// version's):
66///
67/// - **Linux:** BlueZ's `Alias` (`src/bluez/peripheral.rs:155`): the name the
68/// user gave the device, else the device's own name, else its address with
69/// dashes, such as `60-C0-BF-48-CB-8D` (BlueZ 5.82 `src/device.c:959-980`).
70/// Read as a name, it would take a renamed sensor's Aranet name away, and
71/// with it the sensor type that is detected from the name, and it would
72/// give a name to a device that has none. `advertisement_name` is BlueZ's
73/// `Name` (`src/bluez/peripheral.rs:156`), which is what `local_name` was
74/// in btleplug 0.11.8.
75/// - **Windows:** the advertised name, until a connect replaces it with the
76/// system's name for the device (`src/winrtble/peripheral.rs:523-531`).
77/// `advertisement_name` is the name from the last advertisement that carried
78/// one (`src/winrtble/peripheral.rs:173-180`), which is what `local_name`
79/// was in btleplug 0.11.8.
80/// - **macOS:** the advertised name once one has been heard, and until then
81/// the name CoreBluetooth holds for the peripheral
82/// (`src/corebluetooth/internal.rs:1003-1008`,
83/// `src/corebluetooth/peripheral.rs:221-235`). On macOS this function
84/// returns what `local_name` holds.
85///
86/// # Example
87///
88/// ```
89/// use aranet_core::peripheral_name;
90/// use btleplug::api::PeripheralProperties;
91///
92/// // A sensor as BlueZ reports it after the user has renamed it "Kitchen".
93/// let properties = PeripheralProperties {
94/// local_name: Some("Kitchen".to_string()),
95/// advertisement_name: Some("Aranet4 12345".to_string()),
96/// ..Default::default()
97/// };
98/// assert_eq!(peripheral_name(&properties), Some("Aranet4 12345"));
99/// ```
100pub fn peripheral_name(properties: &PeripheralProperties) -> Option<&str> {
101 name_from(properties, UNADVERTISED_NAME_IS_LOCAL_NAME)
102}
103
104/// `peripheral_name` with the choice that depends on the operating system as a
105/// parameter, so that one host can test every rule: the advertised name, or,
106/// if there is none and `or_local_name` is set, `local_name`.
107fn name_from(properties: &PeripheralProperties, or_local_name: bool) -> Option<&str> {
108 let advertised = properties.advertisement_name.as_deref();
109 if or_local_name {
110 advertised.or(properties.local_name.as_deref())
111 } else {
112 advertised
113 }
114}
115
116#[cfg(test)]
117mod tests {
118 // Note: `test_create_identifier_with_valid_address` and
119 // `test_create_identifier_with_zero_address` don't call `create_identifier`
120 // or `format_peripheral_id`. Both functions take btleplug's PeripheralId,
121 // and a test that runs on every platform can't make one. btleplug 0.13.5
122 // makes one from a UUID on macOS (`src/corebluetooth/peripheral.rs:672`)
123 // and from a BDAddr on Windows (`src/winrtble/peripheral.rs:732`), but on
124 // Linux only from a bluez_async::DeviceId (`src/bluez/peripheral.rs:358`).
125 // aranet-core can't name that type: btleplug doesn't re-export bluez-async,
126 // and aranet-core doesn't depend on it directly. So the two tests only
127 // compare an address with the all-zero one, as `create_identifier` does.
128 #[allow(unused_imports)]
129 use super::*;
130
131 #[test]
132 fn test_create_identifier_with_valid_address() {
133 // No PeripheralId here (see the note on PeripheralId in this module),
134 // so this only compares the address with the all-zero one.
135 let address = "AA:BB:CC:DD:EE:FF";
136 // When address is valid, it should be used directly
137 assert_ne!(address, "00:00:00:00:00:00");
138 }
139
140 #[test]
141 fn test_create_identifier_with_zero_address() {
142 let address = "00:00:00:00:00:00";
143 assert_eq!(address, "00:00:00:00:00:00");
144 }
145}
146
147#[cfg(test)]
148mod peripheral_name_tests {
149 use super::*;
150
151 use std::path::{Path, PathBuf};
152
153 use aranet_types::DeviceType;
154
155 /// What `name_from` is given on Linux and Windows.
156 const ADVERTISED_NAME_ONLY: bool = false;
157 /// What `name_from` is given on macOS.
158 const OR_LOCAL_NAME: bool = true;
159
160 /// Properties that carry nothing but the two names.
161 fn named(local_name: Option<&str>, advertisement_name: Option<&str>) -> PeripheralProperties {
162 PeripheralProperties {
163 local_name: local_name.map(str::to_owned),
164 advertisement_name: advertisement_name.map(str::to_owned),
165 ..Default::default()
166 }
167 }
168
169 #[test]
170 fn bluez_alias_does_not_replace_the_sensors_name() {
171 // BlueZ, for a sensor the user has renamed: `local_name` is the alias
172 // and `advertisement_name` is BlueZ's `Name`.
173 let properties = named(Some("Kitchen"), Some("Aranet2 2751B"));
174 let name = name_from(&properties, ADVERTISED_NAME_ONLY);
175 assert_eq!(name, Some("Aranet2 2751B"));
176 // The sensor type is detected from the name, and a sensor without a
177 // type is read and parsed as an Aranet4.
178 assert_eq!(
179 name.and_then(DeviceType::from_name),
180 Some(DeviceType::Aranet2)
181 );
182 }
183
184 #[test]
185 fn bluez_device_without_a_name_has_none() {
186 // BlueZ, for a device it has no name for: the alias is the address
187 // with dashes.
188 let properties = named(Some("60-C0-BF-48-CB-8D"), None);
189 assert_eq!(name_from(&properties, ADVERTISED_NAME_ONLY), None);
190 }
191
192 #[test]
193 fn winrt_connect_does_not_change_the_name() {
194 // WinRT after a connect: `local_name` is the system's name for the
195 // device.
196 let connected = named(Some("Bedroom sensor"), Some("Aranet4 17C3C"));
197 assert_eq!(
198 name_from(&connected, ADVERTISED_NAME_ONLY),
199 Some("Aranet4 17C3C")
200 );
201 // A device that never advertised a name stays without one.
202 let never_named = named(Some("Bedroom sensor"), None);
203 assert_eq!(name_from(&never_named, ADVERTISED_NAME_ONLY), None);
204 }
205
206 #[test]
207 fn corebluetooth_uses_the_advertised_name() {
208 // CoreBluetooth once a name has been advertised: both fields hold it.
209 let properties = named(Some("Aranet4 1A2B3"), Some("Aranet4 1A2B3"));
210 assert_eq!(name_from(&properties, OR_LOCAL_NAME), Some("Aranet4 1A2B3"));
211 }
212
213 #[test]
214 fn corebluetooth_falls_back_to_the_systems_name() {
215 // CoreBluetooth before any name has been advertised: `local_name` is
216 // its own name for the peripheral.
217 let properties = named(Some("Kitchen"), None);
218 assert_eq!(name_from(&properties, OR_LOCAL_NAME), Some("Kitchen"));
219 }
220
221 #[test]
222 fn corebluetooth_peripheral_without_a_name_has_none() {
223 let properties = named(None, None);
224 assert_eq!(name_from(&properties, OR_LOCAL_NAME), None);
225 }
226
227 #[test]
228 fn an_advertised_name_wins_over_local_name() {
229 // CoreBluetooth never reports two different names (btleplug 0.13.5
230 // `src/corebluetooth/peripheral.rs:221-235`). This pins the order of
231 // the rule: `local_name` is used only when no name was advertised.
232 let properties = named(Some("Kitchen"), Some("Aranet2 2751B"));
233 assert_eq!(name_from(&properties, OR_LOCAL_NAME), Some("Aranet2 2751B"));
234 }
235
236 /// The one test of `UNADVERTISED_NAME_IS_LOCAL_NAME`. Every other test
237 /// passes the rule to `name_from` itself, so without this one the constant
238 /// could be `true` on Linux, which makes a BlueZ alias a sensor's name
239 /// again, with every other test passing. CI runs it on macOS, Linux and
240 /// Windows.
241 #[test]
242 fn peripheral_name_uses_local_name_only_on_macos() {
243 let properties = named(Some("Kitchen"), None);
244 let expected = cfg!(target_os = "macos").then_some("Kitchen");
245 assert_eq!(peripheral_name(&properties), expected);
246 }
247
248 /// Every `.rs` file under `dir`, at any depth.
249 fn rust_files(dir: &Path, found: &mut Vec<PathBuf>) {
250 for entry in std::fs::read_dir(dir).expect("read a source directory") {
251 let path = entry.expect("read a directory entry").path();
252 if path.is_dir() {
253 rust_files(&path, found);
254 } else if path.extension().is_some_and(|extension| extension == "rs") {
255 found.push(path);
256 }
257 }
258 }
259
260 /// Guard: in aranet-core only `name_from` (this file) reads btleplug's
261 /// `local_name` and `advertisement_name`.
262 ///
263 /// Six places in the crate need a peripheral's name: the scan
264 /// (`process_peripheral` and `is_aranet_device`), the device lookup
265 /// (`search_known_peripherals`), the connect
266 /// (`Device::from_peripheral_with_config`) and the passive monitor, twice.
267 /// Five of them take a real btleplug peripheral and cannot be unit-tested,
268 /// so no other test would notice if one of them read a field itself. A
269 /// site that read `local_name` would name a sensor on Linux by its BlueZ
270 /// alias, and the sensor would lose its type. A site that read
271 /// `advertisement_name` directly would pass every other test and lose the
272 /// system's name on macOS for a sensor that has not advertised one.
273 ///
274 /// So this test reads the source files. It fails on either field's name
275 /// after a dot, in code or in a comment, in any file but this one. A
276 /// struct literal that sets the fields has no dot before their names and
277 /// passes: the test double of a peripheral (`link/fake.rs`) sets them
278 /// that way.
279 ///
280 /// Two kinds of read get past it. A pattern that takes a field out of
281 /// the struct (`PeripheralProperties { local_name, .. }`) has no dot
282 /// before the name. And this file is skipped as a whole, so a second read
283 /// in it, outside `name_from`, passes too. There is neither today, and
284 /// only a review keeps it so.
285 ///
286 /// It searches `src` only. The `discover_services` example and the
287 /// hardware tests' `known_peripheral` take the name from `peripheral_name`
288 /// too, but they are outside `src`, and this test does not read them.
289 #[test]
290 fn only_peripheral_name_reads_the_name_fields() {
291 // Each in two halves, so that a text search of the crate for them
292 // finds only the two reads in `name_from`. The test itself does not
293 // need the split: it skips this file.
294 let field_reads = [
295 [".local", "_name"].concat(),
296 [".advertisement", "_name"].concat(),
297 ];
298 let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
299 // The one file that may read the fields: `name_from` is above.
300 let exempt = Path::new("util.rs");
301
302 let mut files = Vec::new();
303 rust_files(&src, &mut files);
304 files.sort();
305
306 let mut exempt_seen = false;
307 let mut reads = Vec::new();
308 for file in &files {
309 let relative = file.strip_prefix(&src).expect("a path under src");
310 if relative == exempt {
311 exempt_seen = true;
312 continue;
313 }
314 let text = std::fs::read_to_string(file).expect("read a source file");
315 for (index, line) in text.lines().enumerate() {
316 if field_reads.iter().any(|field| line.contains(field)) {
317 reads.push(format!(
318 "{}:{}: {}",
319 relative.display(),
320 index + 1,
321 line.trim()
322 ));
323 }
324 }
325 }
326
327 assert!(
328 exempt_seen,
329 "util.rs is not under {}; if it was renamed, rename it here too",
330 src.display()
331 );
332 assert!(
333 reads.is_empty(),
334 "these lines read `local_name` or `advertisement_name`; use `peripheral_name`:\n{}",
335 reads.join("\n")
336 );
337 }
338}