mirror of
https://github.com/ratspeak/rsReticulum
synced 2026-11-22 23:10:33 +00:00
ble: Apple BLE no longer leaks each write, notification, and scan; move to objc2 0.6
This commit is contained in:
1 parent
5dadbd44bd
commit
7631c75afd
9 files changed
+295
-348
No files matched your search
Generated
+11
-59
@@ -182,22 +182,13 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
|
||||
dependencies = [
|
||||
"objc2 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -272,9 +263,9 @@ dependencies = [
|
||||
"futures",
|
||||
"jni 0.22.4",
|
||||
"log",
|
||||
"objc2 0.6.5",
|
||||
"objc2-core-bluetooth 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
"once_cell",
|
||||
"static_assertions",
|
||||
"thiserror 2.0.21",
|
||||
@@ -1445,22 +1436,6 @@ dependencies = [
|
||||
"libm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc-sys"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
|
||||
dependencies = [
|
||||
"objc-sys",
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.6.5"
|
||||
@@ -1470,17 +1445,6 @@ dependencies = [
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-bluetooth"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2 0.5.2",
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-bluetooth"
|
||||
version = "0.3.2"
|
||||
@@ -1488,8 +1452,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "79b30b9eacc37434a61377866f68b27acef9fa5496f25cc9ca8b2549032e0394"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2",
|
||||
"objc2-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1498,18 +1462,6 @@ version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.5.1",
|
||||
"libc",
|
||||
"objc2 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.3.2"
|
||||
@@ -1517,8 +1469,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
"block2",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1930,9 +1882,9 @@ dependencies = [
|
||||
"libc",
|
||||
"md-5",
|
||||
"mio",
|
||||
"objc2 0.5.2",
|
||||
"objc2-core-bluetooth 0.2.2",
|
||||
"objc2-foundation 0.2.2",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
"rand 0.8.5",
|
||||
"rns-crypto",
|
||||
"rns-identity",
|
||||
|
||||
Generated
+11
-59
@@ -79,22 +79,13 @@ dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
|
||||
dependencies = [
|
||||
"objc2 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
|
||||
dependencies = [
|
||||
"objc2 0.6.5",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -169,9 +160,9 @@ dependencies = [
|
||||
"futures",
|
||||
"jni 0.22.4",
|
||||
"log",
|
||||
"objc2 0.6.5",
|
||||
"objc2-core-bluetooth 0.3.2",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
"once_cell",
|
||||
"static_assertions",
|
||||
"thiserror 2.0.20",
|
||||
@@ -994,22 +985,6 @@ dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc-sys"
|
||||
version = "0.3.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
|
||||
dependencies = [
|
||||
"objc-sys",
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.6.5"
|
||||
@@ -1019,17 +994,6 @@ dependencies = [
|
||||
"objc2-encode",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-bluetooth"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2 0.5.2",
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-core-bluetooth"
|
||||
version = "0.3.2"
|
||||
@@ -1037,8 +1001,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "79b30b9eacc37434a61377866f68b27acef9fa5496f25cc9ca8b2549032e0394"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"objc2 0.6.5",
|
||||
"objc2-foundation 0.3.2",
|
||||
"objc2",
|
||||
"objc2-foundation",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1047,18 +1011,6 @@ version = "4.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.5.1",
|
||||
"libc",
|
||||
"objc2 0.5.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "objc2-foundation"
|
||||
version = "0.3.2"
|
||||
@@ -1066,8 +1018,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
|
||||
dependencies = [
|
||||
"bitflags 2.13.2",
|
||||
"block2 0.6.2",
|
||||
"objc2 0.6.5",
|
||||
"block2",
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1305,9 +1257,9 @@ dependencies = [
|
||||
"libc",
|
||||
"md-5",
|
||||
"mio",
|
||||
"objc2 0.5.2",
|
||||
"objc2-core-bluetooth 0.2.2",
|
||||
"objc2-foundation 0.2.2",
|
||||
"objc2",
|
||||
"objc2-core-bluetooth",
|
||||
"objc2-foundation",
|
||||
"rand",
|
||||
"rns-crypto",
|
||||
"rns-identity",
|
||||
|
||||
@@ -803,7 +803,7 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": "cfg(any(target_os = \"ios\", target_os = \"macos\"))",
|
||||
"requirement": "^0.5",
|
||||
"requirement": "^0.6",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"features": [],
|
||||
@@ -814,12 +814,14 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": "cfg(any(target_os = \"ios\", target_os = \"macos\"))",
|
||||
"requirement": "^0.2",
|
||||
"requirement": "^0.3",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
"CBAdvertisementData",
|
||||
"CBCentralManagerConstants"
|
||||
"CBCentralManagerConstants",
|
||||
"CBPeripheralManagerConstants",
|
||||
"std"
|
||||
],
|
||||
"sourceKind": "registry"
|
||||
},
|
||||
@@ -828,11 +830,12 @@
|
||||
"rename": null,
|
||||
"kind": null,
|
||||
"target": "cfg(any(target_os = \"ios\", target_os = \"macos\"))",
|
||||
"requirement": "^0.2",
|
||||
"requirement": "^0.3",
|
||||
"optional": false,
|
||||
"defaultFeatures": true,
|
||||
"defaultFeatures": false,
|
||||
"features": [
|
||||
"NSString"
|
||||
"NSString",
|
||||
"std"
|
||||
],
|
||||
"sourceKind": "registry"
|
||||
},
|
||||
|
||||
@@ -45,9 +45,9 @@ md-5 = { workspace = true }
|
||||
# CB*RestoreIdentifierKey, etc.) instead of re-declaring their literal
|
||||
# values, which Apple is free to change.
|
||||
[target.'cfg(any(target_os = "ios", target_os = "macos"))'.dependencies]
|
||||
objc2 = "0.5"
|
||||
objc2-foundation = { version = "0.2", features = ["NSString"] }
|
||||
objc2-core-bluetooth = { version = "0.2", features = ["CBAdvertisementData", "CBCentralManagerConstants"] }
|
||||
objc2 = "0.6"
|
||||
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSString"] }
|
||||
objc2-core-bluetooth = { version = "0.3", default-features = false, features = ["std", "CBAdvertisementData", "CBCentralManagerConstants", "CBPeripheralManagerConstants"] }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
//! Owned Objective-C values for the Apple BLE modules. Their calls run on Tokio
|
||||
//! workers and other threads with no autorelease pool, where an autoreleased
|
||||
//! object lives until the thread exits.
|
||||
|
||||
use objc2::msg_send;
|
||||
use objc2::rc::{Allocated, Retained};
|
||||
use objc2::runtime::{AnyClass, AnyObject};
|
||||
use objc2_foundation::NSString;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// `UUIDWithString:` autoreleases, so call this inside `autoreleasepool`.
|
||||
pub(crate) fn cbuuid(uuid: &Uuid) -> Retained<AnyObject> {
|
||||
let s = NSString::from_str(&uuid.to_string());
|
||||
let cls = AnyClass::get(c"CBUUID").expect("CBUUID must exist at runtime");
|
||||
unsafe { msg_send![cls, UUIDWithString: &*s] }
|
||||
}
|
||||
|
||||
/// A copy of `bytes`, never autoreleased.
|
||||
pub(crate) fn nsdata(bytes: &[u8]) -> Retained<AnyObject> {
|
||||
let cls = AnyClass::get(c"NSData").expect("NSData must exist at runtime");
|
||||
unsafe {
|
||||
let obj: Allocated<AnyObject> = msg_send![cls, alloc];
|
||||
msg_send![obj,
|
||||
initWithBytes: bytes.as_ptr().cast::<std::ffi::c_void>(),
|
||||
length: bytes.len()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Never autoreleased; the array retains each element.
|
||||
pub(crate) fn nsarray(objects: &[&AnyObject]) -> Retained<AnyObject> {
|
||||
let cls = AnyClass::get(c"NSArray").expect("NSArray must exist at runtime");
|
||||
let ptrs: Vec<*const AnyObject> = objects.iter().map(|o| *o as *const AnyObject).collect();
|
||||
unsafe {
|
||||
let obj: Allocated<AnyObject> = msg_send![cls, alloc];
|
||||
msg_send![obj, initWithObjects: ptrs.as_ptr(), count: ptrs.len()]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use objc2::rc::{Weak, autoreleasepool};
|
||||
|
||||
/// Runs `make` on a thread with no autorelease pool, drops what it returns,
|
||||
/// and reports whether every returned object was freed. A stray retain or
|
||||
/// an autorelease outside `make`'s own pool keeps the object alive.
|
||||
pub(crate) fn freed_on_drop<F>(make: F) -> bool
|
||||
where
|
||||
F: FnOnce() -> Vec<Retained<AnyObject>> + Send + 'static,
|
||||
{
|
||||
std::thread::spawn(move || {
|
||||
let weak: Vec<Weak<AnyObject>> = {
|
||||
let objs = make();
|
||||
let weak: Vec<_> = objs.iter().map(Weak::from_retained).collect();
|
||||
// A class without weak-reference support would pass vacuously.
|
||||
assert!(weak.iter().all(|w| w.load().is_some()));
|
||||
weak
|
||||
};
|
||||
weak.iter().all(|w| w.load().is_none())
|
||||
})
|
||||
.join()
|
||||
.expect("probe thread")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_sees_an_autoreleased_object() {
|
||||
assert!(!freed_on_drop(|| {
|
||||
let cls = AnyClass::get(c"NSData").unwrap();
|
||||
let bytes = [0xCDu8; 300];
|
||||
unsafe {
|
||||
let raw: *mut AnyObject = msg_send![cls,
|
||||
dataWithBytes: bytes.as_ptr().cast::<std::ffi::c_void>(),
|
||||
length: bytes.len()];
|
||||
vec![Retained::retain(raw).unwrap()]
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nsdata_and_nsarray_are_never_autoreleased() {
|
||||
assert!(freed_on_drop(|| {
|
||||
let data = nsdata(&[0xAB; 300]);
|
||||
let arr = nsarray(&[&data]);
|
||||
vec![data, arr]
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cbuuid_holds_no_extra_retain() {
|
||||
assert!(freed_on_drop(|| {
|
||||
autoreleasepool(|_| vec![cbuuid(&crate::ble_peer::RATSPEAK_SERVICE_UUID)])
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use crate::ble_central_lifecycle::{
|
||||
CentralEvent, CentralLifecycle, CentralState, DiscoveryEvent, classify_protocol,
|
||||
};
|
||||
use crate::ble_peer::{COLUMBA_SERVICE_UUID, RATSPEAK_SERVICE_UUID};
|
||||
use objc2::rc::autoreleasepool;
|
||||
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
|
||||
use objc2::{msg_send, sel};
|
||||
use objc2_core_bluetooth::{
|
||||
@@ -144,7 +145,7 @@ pub async fn start_scan(
|
||||
let delegate_raw: *mut AnyObject = msg_send![delegate_cls, alloc];
|
||||
let delegate_raw: *mut AnyObject = msg_send![delegate_raw, init];
|
||||
|
||||
let Some(mgr_cls) = AnyClass::get("CBCentralManager") else {
|
||||
let Some(mgr_cls) = AnyClass::get(c"CBCentralManager") else {
|
||||
tracing::error!("Apple BLE Central: CBCentralManager class not found");
|
||||
return;
|
||||
};
|
||||
@@ -216,12 +217,12 @@ pub async fn stop_scan() -> Result<(), String> {
|
||||
}
|
||||
};
|
||||
|
||||
unsafe {
|
||||
// We do NOT release the manager — the next start_scan reuses it.
|
||||
// Per-cycle release on macOS triggers CBManagerStateUnsupported.
|
||||
// `teardown_central` does the full release on interface shutdown.
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![&*mgr_ptr, stopScan];
|
||||
}
|
||||
});
|
||||
|
||||
finalize_stop();
|
||||
Ok(())
|
||||
@@ -286,8 +287,8 @@ pub fn central_manager_ptr() -> Option<*mut AnyObject> {
|
||||
|
||||
fn get_delegate_class() -> &'static AnyClass {
|
||||
DELEGATE_CLASS.get_or_init(|| {
|
||||
let superclass = AnyClass::get("NSObject").expect("NSObject must exist");
|
||||
let mut builder = ClassBuilder::new("RatspeakBleCentralDelegate", superclass)
|
||||
let superclass = AnyClass::get(c"NSObject").expect("NSObject must exist");
|
||||
let mut builder = ClassBuilder::new(c"RatspeakBleCentralDelegate", superclass)
|
||||
.expect("ClassBuilder for central delegate must succeed");
|
||||
|
||||
extern "C" fn did_update_state(
|
||||
@@ -720,23 +721,14 @@ unsafe fn scan_with_manager(mgr_raw: *mut AnyObject) -> Result<(), String> {
|
||||
.map_err(|e| format!("scan_services lock poisoned: {e}"))?
|
||||
.clone();
|
||||
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let uuids: Vec<_> = services.iter().map(crate::apple_objc::cbuuid).collect();
|
||||
let refs: Vec<&AnyObject> = uuids.iter().map(|u| &**u).collect();
|
||||
// nil filter = scan all.
|
||||
let svc_arr: *mut AnyObject = if services.is_empty() {
|
||||
std::ptr::null_mut()
|
||||
} else {
|
||||
let arr_cls = AnyClass::get("NSArray").ok_or("NSArray not found")?;
|
||||
let mut raw_ptrs: Vec<*const AnyObject> = Vec::with_capacity(services.len());
|
||||
for u in &services {
|
||||
raw_ptrs.push(cbuuid(u) as *const AnyObject);
|
||||
}
|
||||
msg_send![arr_cls,
|
||||
arrayWithObjects: raw_ptrs.as_ptr(),
|
||||
count: raw_ptrs.len()]
|
||||
};
|
||||
let svc_arr = (!refs.is_empty()).then(|| crate::apple_objc::nsarray(&refs));
|
||||
|
||||
let number_cls = AnyClass::get("NSNumber").ok_or("NSNumber not found")?;
|
||||
let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?;
|
||||
let number_cls = AnyClass::get(c"NSNumber").ok_or("NSNumber not found")?;
|
||||
let dict_cls = AnyClass::get(c"NSDictionary").ok_or("NSDictionary not found")?;
|
||||
let yes: *mut AnyObject = msg_send![number_cls, numberWithBool: true];
|
||||
let opts: *mut AnyObject = msg_send![dict_cls,
|
||||
dictionaryWithObject: yes,
|
||||
@@ -750,16 +742,16 @@ unsafe fn scan_with_manager(mgr_raw: *mut AnyObject) -> Result<(), String> {
|
||||
"Apple BLE Central: scanForPeripheralsWithServices"
|
||||
);
|
||||
let _: () = msg_send![&*mgr_raw,
|
||||
scanForPeripheralsWithServices: svc_arr,
|
||||
scanForPeripheralsWithServices: svc_arr.as_deref(),
|
||||
options: opts];
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// `{ RestoreIdentifierKey: CENTRAL_RESTORE_ID }`. Ignored on macOS.
|
||||
unsafe fn build_init_options() -> Result<*mut AnyObject, String> {
|
||||
unsafe {
|
||||
let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?;
|
||||
let dict_cls = AnyClass::get(c"NSDictionary").ok_or("NSDictionary not found")?;
|
||||
let restore_id = NSString::from_str(CENTRAL_RESTORE_ID);
|
||||
let opts: *mut AnyObject = msg_send![dict_cls,
|
||||
dictionaryWithObject: &*restore_id,
|
||||
@@ -852,18 +844,6 @@ unsafe fn nsstring_to_string(s: *mut AnyObject) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn cbuuid(uuid: &Uuid) -> *mut AnyObject {
|
||||
let s = NSString::from_str(&uuid.to_string());
|
||||
unsafe {
|
||||
let cls = AnyClass::get("CBUUID").expect("CBUUID must exist at runtime");
|
||||
let obj: *mut AnyObject = msg_send![cls, UUIDWithString: &*s];
|
||||
// UUIDWithString: returns autoreleased; retain so the pointer
|
||||
// survives the autorelease pool drain.
|
||||
let _: *mut AnyObject = msg_send![obj, retain];
|
||||
obj
|
||||
}
|
||||
}
|
||||
|
||||
/// Expand a SIG short UUID ("180D" / "0000180D") to its 128-bit form using
|
||||
/// the Bluetooth base UUID.
|
||||
fn parse_short_uuid(s: &str) -> Result<Uuid, ()> {
|
||||
|
||||
@@ -5,10 +5,11 @@
|
||||
|
||||
#![cfg(any(target_os = "ios", target_os = "macos"))]
|
||||
|
||||
use crate::apple_objc::{cbuuid, nsarray, nsdata};
|
||||
use crate::ble_tx_queue::PacketQueue;
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
|
||||
use objc2::{msg_send, sel};
|
||||
use objc2_foundation::NSString;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
@@ -135,7 +136,7 @@ pub struct ConnectedPeer {
|
||||
|
||||
impl Drop for ConnectedPeer {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
// Clear the (weakly-retained) delegate first so a late callback
|
||||
// can't fire into freed memory after the release below.
|
||||
if !self.peripheral.0.is_null() {
|
||||
@@ -157,7 +158,7 @@ impl Drop for ConnectedPeer {
|
||||
let _: () = msg_send![p.0, release];
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,12 +213,12 @@ pub async fn connect_peer(
|
||||
reason = %reason,
|
||||
"Apple BLE central connect: tearing down partial connection"
|
||||
);
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![&*manager, cancelPeripheralConnection: peripheral];
|
||||
let _: () = msg_send![peripheral, setDelegate: std::ptr::null::<AnyObject>()];
|
||||
let _: () = msg_send![delegate, release];
|
||||
let _: () = msg_send![peripheral, release];
|
||||
}
|
||||
});
|
||||
if let Ok(mut g) = pending().lock() {
|
||||
for kind in [
|
||||
CallbackKind::Connect,
|
||||
@@ -239,11 +240,11 @@ pub async fn connect_peer(
|
||||
"Apple BLE central: connectPeripheral"
|
||||
);
|
||||
let rx = install_pending(&address, CallbackKind::Connect);
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![&*manager.0,
|
||||
connectPeripheral: peripheral.0,
|
||||
options: std::ptr::null::<AnyObject>()];
|
||||
}
|
||||
});
|
||||
if let Err(e) = await_step(rx, "connect", CONNECT_TIMEOUT).await {
|
||||
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e);
|
||||
return Err(e);
|
||||
@@ -263,17 +264,19 @@ pub async fn connect_peer(
|
||||
// install_pending must run BEFORE the CB call so a fast-path callback
|
||||
// (cached service data) can't race ahead of its own entry.
|
||||
let rx = install_pending(&address, CallbackKind::Services);
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![peripheral.0, setDelegate: delegate.0];
|
||||
let svc_filter = build_cbuuid_array(&[target_service_uuid]);
|
||||
let _: () = msg_send![peripheral.0, discoverServices: svc_filter];
|
||||
}
|
||||
let _: () = msg_send![peripheral.0, discoverServices: &*svc_filter];
|
||||
});
|
||||
if let Err(e) = await_step(rx, "discoverServices", DISCOVERY_TIMEOUT).await {
|
||||
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e);
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
let service = match unsafe { find_service(peripheral.0, target_service_uuid) } {
|
||||
let service = match autoreleasepool(|_| unsafe {
|
||||
find_service(peripheral.0, target_service_uuid)
|
||||
}) {
|
||||
Some(p) => SendPtr(p),
|
||||
None => {
|
||||
let msg = format!("target service {target_service_uuid} not present after discovery");
|
||||
@@ -295,39 +298,41 @@ pub async fn connect_peer(
|
||||
PeerProtocol::Columba => (COLUMBA_RX_UUID, COLUMBA_TX_UUID),
|
||||
};
|
||||
let rx = install_pending(&address, CallbackKind::Chars);
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let chars_filter = build_cbuuid_array(&[rx_uuid, tx_uuid]);
|
||||
let _: () = msg_send![peripheral.0,
|
||||
discoverCharacteristics: chars_filter,
|
||||
discoverCharacteristics: &*chars_filter,
|
||||
forService: service.0];
|
||||
}
|
||||
});
|
||||
if let Err(e) = await_step(rx, "discoverCharacteristics", DISCOVERY_TIMEOUT).await {
|
||||
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &e);
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
let rx_char = match unsafe { find_char(service.0, rx_uuid) } {
|
||||
Some(p) => SendPtr(p),
|
||||
None => {
|
||||
// The peripheral owns these; retain so they outlive any single
|
||||
// delegate callback frame.
|
||||
let found = autoreleasepool(|_| unsafe {
|
||||
let rx_char = find_char(service.0, rx_uuid);
|
||||
let tx_char = find_char(service.0, tx_uuid);
|
||||
if let (Some(rx), Some(tx)) = (rx_char, tx_char) {
|
||||
let _: *mut AnyObject = msg_send![rx, retain];
|
||||
let _: *mut AnyObject = msg_send![tx, retain];
|
||||
}
|
||||
(rx_char, tx_char)
|
||||
});
|
||||
let (rx_char, tx_char) = match found {
|
||||
(Some(rx), Some(tx)) => (SendPtr(rx), SendPtr(tx)),
|
||||
(None, _) => {
|
||||
let msg = format!("rx characteristic {rx_uuid} missing after discovery");
|
||||
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &msg);
|
||||
return Err(msg);
|
||||
}
|
||||
};
|
||||
let tx_char = match unsafe { find_char(service.0, tx_uuid) } {
|
||||
Some(p) => SendPtr(p),
|
||||
None => {
|
||||
(_, None) => {
|
||||
let msg = format!("tx characteristic {tx_uuid} missing after discovery");
|
||||
teardown_partial(&address, manager.0, peripheral.0, delegate.0, &msg);
|
||||
return Err(msg);
|
||||
}
|
||||
};
|
||||
// The peripheral owns these; retain so they outlive any single
|
||||
// delegate callback frame.
|
||||
unsafe {
|
||||
let _: *mut AnyObject = msg_send![rx_char.0, retain];
|
||||
let _: *mut AnyObject = msg_send![tx_char.0, retain];
|
||||
}
|
||||
tracing::info!(
|
||||
target: "ble_trace",
|
||||
step = "apple_connect.chars_discovered",
|
||||
@@ -339,11 +344,11 @@ pub async fn connect_peer(
|
||||
|
||||
// Step 4: setNotifyValue:YES on tx_char (CB handles CCCD internally).
|
||||
let rx = install_pending(&address, CallbackKind::Notify);
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![peripheral.0,
|
||||
setNotifyValue: true,
|
||||
forCharacteristic: tx_char.0];
|
||||
}
|
||||
});
|
||||
if let Err(e) = await_step(rx, "setNotifyValue", DISCOVERY_TIMEOUT).await {
|
||||
// Balance the rx/tx retains on failure.
|
||||
unsafe {
|
||||
@@ -437,6 +442,7 @@ fn enqueue_packet(peer: &ConnectedPeer, frames: Vec<Vec<u8>>) -> Result<bool, St
|
||||
}
|
||||
|
||||
fn drain_peer_queue(peer: &ConnectedPeer, q: &mut PacketQueue) {
|
||||
autoreleasepool(|_| {
|
||||
while q.drain_one(|data| {
|
||||
if !peer.online.load(Ordering::SeqCst) {
|
||||
return false;
|
||||
@@ -448,6 +454,7 @@ fn drain_peer_queue(peer: &ConnectedPeer, q: &mut PacketQueue) {
|
||||
unsafe { issue_write(peer, data) };
|
||||
true
|
||||
}) {}
|
||||
});
|
||||
}
|
||||
|
||||
/// Caller must have either confirmed `canSendWriteWithoutResponse` or be
|
||||
@@ -457,11 +464,11 @@ fn drain_peer_queue(peer: &ConnectedPeer, q: &mut PacketQueue) {
|
||||
/// `peer.peripheral.0` and `peer.rx_char.0` must be retained, valid CB
|
||||
/// pointers.
|
||||
unsafe fn issue_write(peer: &ConnectedPeer, data: &[u8]) {
|
||||
unsafe {
|
||||
let nsdata = nsdata_from_slice(data);
|
||||
let value = nsdata(data);
|
||||
const WRITE_WITHOUT_RESPONSE: i64 = 1;
|
||||
unsafe {
|
||||
let _: () = msg_send![peer.peripheral.0,
|
||||
writeValue: nsdata,
|
||||
writeValue: &*value,
|
||||
forCharacteristic: peer.rx_char.0,
|
||||
type: WRITE_WITHOUT_RESPONSE];
|
||||
}
|
||||
@@ -481,10 +488,10 @@ pub fn disconnect_peer(address: &str) {
|
||||
*q = PacketQueue::default();
|
||||
}
|
||||
if let Some(manager_ptr) = crate::ble_central_apple::central_manager_ptr() {
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![&*manager_ptr,
|
||||
cancelPeripheralConnection: peer.peripheral.0];
|
||||
}
|
||||
});
|
||||
}
|
||||
// online_flags entry stays — the disconnect callback flips it.
|
||||
tracing::info!(
|
||||
@@ -575,8 +582,6 @@ pub unsafe fn adopt_restored_peer(
|
||||
Some(p) => SendPtr(p),
|
||||
None => {
|
||||
unsafe {
|
||||
let _: () = msg_send![rx_char.0, retain];
|
||||
let _: () = msg_send![rx_char.0, release];
|
||||
let _: () = msg_send![peripheral, release];
|
||||
}
|
||||
return Err(format!(
|
||||
@@ -824,8 +829,8 @@ async fn await_step(
|
||||
|
||||
fn peripheral_delegate_class() -> &'static AnyClass {
|
||||
DELEGATE_CLASS.get_or_init(|| {
|
||||
let superclass = AnyClass::get("NSObject").expect("NSObject must exist");
|
||||
let mut builder = ClassBuilder::new("RatspeakBlePeripheralDelegate", superclass)
|
||||
let superclass = AnyClass::get(c"NSObject").expect("NSObject must exist");
|
||||
let mut builder = ClassBuilder::new(c"RatspeakBlePeripheralDelegate", superclass)
|
||||
.expect("ClassBuilder for peripheral delegate must succeed");
|
||||
|
||||
extern "C" fn did_discover_services(
|
||||
@@ -1015,41 +1020,11 @@ fn peripheral_delegate_class() -> &'static AnyClass {
|
||||
})
|
||||
}
|
||||
|
||||
/// Autoreleased `NSArray<CBUUID>`; CB retains internally.
|
||||
fn build_cbuuid_array(uuids: &[Uuid]) -> *mut AnyObject {
|
||||
if uuids.is_empty() {
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
let cbuuid_cls = match AnyClass::get("CBUUID") {
|
||||
Some(c) => c,
|
||||
None => return std::ptr::null_mut(),
|
||||
};
|
||||
let nsarr_cls = match AnyClass::get("NSArray") {
|
||||
Some(c) => c,
|
||||
None => return std::ptr::null_mut(),
|
||||
};
|
||||
let mut raw_ptrs: Vec<*const AnyObject> = Vec::with_capacity(uuids.len());
|
||||
for u in uuids {
|
||||
let s = NSString::from_str(&u.to_string());
|
||||
unsafe {
|
||||
let cb: *mut AnyObject = msg_send![cbuuid_cls, UUIDWithString: &*s];
|
||||
raw_ptrs.push(cb as *const AnyObject);
|
||||
}
|
||||
}
|
||||
unsafe {
|
||||
msg_send![nsarr_cls,
|
||||
arrayWithObjects: raw_ptrs.as_ptr(),
|
||||
count: raw_ptrs.len()]
|
||||
}
|
||||
}
|
||||
|
||||
/// Autoreleased `NSData` over a copy of `bytes`; valid for the synchronous
|
||||
/// CB call only.
|
||||
unsafe fn nsdata_from_slice(bytes: &[u8]) -> *mut AnyObject {
|
||||
let cls = AnyClass::get("NSData").expect("NSData class must exist");
|
||||
let ptr = bytes.as_ptr() as *const std::ffi::c_void;
|
||||
let len = bytes.len();
|
||||
unsafe { msg_send![cls, dataWithBytes: ptr, length: len] }
|
||||
/// Call inside `autoreleasepool`: the CBUUIDs autorelease.
|
||||
fn build_cbuuid_array(uuids: &[Uuid]) -> Retained<AnyObject> {
|
||||
let owned: Vec<_> = uuids.iter().map(cbuuid).collect();
|
||||
let refs: Vec<&AnyObject> = owned.iter().map(|u| &**u).collect();
|
||||
nsarray(&refs)
|
||||
}
|
||||
|
||||
unsafe fn find_service(peripheral: *mut AnyObject, uuid: Uuid) -> Option<*mut AnyObject> {
|
||||
@@ -1204,6 +1179,13 @@ unsafe fn nsstring_to_string(s: *mut AnyObject) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cbuuid_filter_holds_no_extra_retains() {
|
||||
assert!(crate::apple_objc::tests::freed_on_drop(|| {
|
||||
autoreleasepool(|_| vec![build_cbuuid_array(&[RATSPEAK_RX_UUID, RATSPEAK_TX_UUID])])
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expand_short_uuid_round_trip_16bit() {
|
||||
let u = expand_short_uuid("180D").expect("must parse");
|
||||
|
||||
@@ -1510,8 +1510,15 @@ pub(crate) fn try_push_apple_inbound(peer: String, data: Vec<u8>) -> bool {
|
||||
#[cfg(any(target_os = "ios", target_os = "macos"))]
|
||||
mod apple_peripheral {
|
||||
use super::*;
|
||||
use crate::apple_objc::{cbuuid, nsarray, nsdata};
|
||||
use objc2::rc::{Allocated, Retained, autoreleasepool};
|
||||
use objc2::runtime::{AnyClass, AnyObject, ClassBuilder, Sel};
|
||||
use objc2::{msg_send, sel};
|
||||
use objc2_core_bluetooth::{
|
||||
CBPeripheralManagerOptionRestoreIdentifierKey,
|
||||
CBPeripheralManagerRestoredStateAdvertisementDataKey,
|
||||
CBPeripheralManagerRestoredStateServicesKey,
|
||||
};
|
||||
use objc2_foundation::NSString;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
@@ -1631,15 +1638,6 @@ mod apple_peripheral {
|
||||
/// previously-backgrounded GATT subscriptions.
|
||||
const PERIPHERAL_RESTORE_ID: &str = "org.ratspeak.ios.peripheral";
|
||||
|
||||
// objc2-core-bluetooth 0.2.2 only exports the central-role keys; link
|
||||
// the peripheral-role NSString constants directly.
|
||||
#[link(name = "CoreBluetooth", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
static CBPeripheralManagerOptionRestoreIdentifierKey: &'static NSString;
|
||||
static CBPeripheralManagerRestoredStateServicesKey: &'static NSString;
|
||||
static CBPeripheralManagerRestoredStateAdvertisementDataKey: &'static NSString;
|
||||
}
|
||||
|
||||
/// Ratspeak primary + Columba compat.
|
||||
const EXPECTED_SERVICE_COUNT: usize = 2;
|
||||
|
||||
@@ -1856,8 +1854,8 @@ mod apple_peripheral {
|
||||
|
||||
fn get_delegate_class() -> &'static AnyClass {
|
||||
DELEGATE_CLASS.get_or_init(|| {
|
||||
let superclass = AnyClass::get("NSObject").unwrap();
|
||||
let mut builder = ClassBuilder::new("RatspeakBleDelegate", superclass).unwrap();
|
||||
let superclass = AnyClass::get(c"NSObject").unwrap();
|
||||
let mut builder = ClassBuilder::new(c"RatspeakBleDelegate", superclass).unwrap();
|
||||
|
||||
extern "C" fn did_update_state(
|
||||
_this: *mut AnyObject,
|
||||
@@ -2488,40 +2486,27 @@ mod apple_peripheral {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
unsafe {
|
||||
let arr_cls = match AnyClass::get("NSArray") {
|
||||
Some(c) => c,
|
||||
None => return false,
|
||||
};
|
||||
let data_cls = match AnyClass::get("NSData") {
|
||||
Some(c) => c,
|
||||
None => return false,
|
||||
};
|
||||
let payload: *mut AnyObject = msg_send![data_cls,
|
||||
dataWithBytes: data.as_ptr() as *const std::ffi::c_void,
|
||||
length: data.len()];
|
||||
let centrals: *mut AnyObject = if let Some(peer_id) = to_peer {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let payload = nsdata(data);
|
||||
let centrals = match to_peer {
|
||||
Some(peer_id) => {
|
||||
let map = subscribed_centrals_map().lock().unwrap();
|
||||
let ptr = match map.get(peer_id) {
|
||||
Some(p) => p.0,
|
||||
None => {
|
||||
let Some(central) = map.get(peer_id) else {
|
||||
tracing::warn!(peer = %peer_id, "Apple BLE notify_tx: peer not in subscribed map");
|
||||
return false;
|
||||
}
|
||||
};
|
||||
let one = [ptr as *const AnyObject];
|
||||
msg_send![arr_cls, arrayWithObjects: one.as_ptr(), count: 1usize]
|
||||
} else {
|
||||
std::ptr::null_mut()
|
||||
Some(nsarray(&[&*central.0]))
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let ok: bool = msg_send![
|
||||
mgr,
|
||||
updateValue: payload,
|
||||
updateValue: &*payload,
|
||||
forCharacteristic: char_ptr,
|
||||
onSubscribedCentrals: centrals,
|
||||
onSubscribedCentrals: centrals.as_deref(),
|
||||
];
|
||||
ok
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// We only need the TX chars from notify_tx, but the registry is keyed
|
||||
@@ -2556,17 +2541,6 @@ mod apple_peripheral {
|
||||
.map(|(uuid, _)| *uuid)
|
||||
}
|
||||
|
||||
/// Returns a raw retained pointer.
|
||||
fn cbuuid(uuid: &Uuid) -> *mut AnyObject {
|
||||
let s = NSString::from_str(&uuid.to_string());
|
||||
unsafe {
|
||||
let cls = AnyClass::get("CBUUID").unwrap();
|
||||
let obj: *mut AnyObject = msg_send![cls, UUIDWithString: &*s];
|
||||
let _: *mut AnyObject = msg_send![obj, retain];
|
||||
obj
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn start_advertising(identity_hash: &[u8]) -> Result<(), String> {
|
||||
// Drive the lifecycle BEFORE any side effects.
|
||||
apply_event(crate::ble_peer_lifecycle::LifecycleEvent::StartRequested);
|
||||
@@ -2608,7 +2582,7 @@ mod apple_peripheral {
|
||||
let delegate_raw: *mut AnyObject = msg_send![delegate_cls, alloc];
|
||||
let delegate_raw: *mut AnyObject = msg_send![delegate_raw, init];
|
||||
|
||||
let Some(mgr_cls) = AnyClass::get("CBPeripheralManager") else {
|
||||
let Some(mgr_cls) = AnyClass::get(c"CBPeripheralManager") else {
|
||||
tracing::error!("iOS BLE Peripheral: CBPeripheralManager class not found");
|
||||
return;
|
||||
};
|
||||
@@ -2617,7 +2591,7 @@ mod apple_peripheral {
|
||||
// background BLE event after the process is killed.
|
||||
let opts: *mut AnyObject = {
|
||||
let dict_cls =
|
||||
AnyClass::get("NSDictionary").expect("NSDictionary must exist at runtime");
|
||||
AnyClass::get(c"NSDictionary").expect("NSDictionary must exist at runtime");
|
||||
let id = NSString::from_str(PERIPHERAL_RESTORE_ID);
|
||||
msg_send![dict_cls,
|
||||
dictionaryWithObject: &*id,
|
||||
@@ -2682,68 +2656,21 @@ mod apple_peripheral {
|
||||
mgr_raw: *mut AnyObject,
|
||||
id_hash: &[u8],
|
||||
) -> Result<(), String> {
|
||||
unsafe {
|
||||
let char_cls = AnyClass::get("CBMutableCharacteristic")
|
||||
.ok_or("CBMutableCharacteristic not found")?;
|
||||
let svc_cls = AnyClass::get("CBMutableService").ok_or("CBMutableService not found")?;
|
||||
let arr_cls = AnyClass::get("NSArray").ok_or("NSArray not found")?;
|
||||
let dict_cls = AnyClass::get("NSDictionary").ok_or("NSDictionary not found")?;
|
||||
|
||||
// RX (write + writeNoResponse)
|
||||
let rx_raw: *mut AnyObject = msg_send![char_cls, alloc];
|
||||
let rx_raw: *mut AnyObject = msg_send![rx_raw,
|
||||
initWithType: cbuuid(&RATSPEAK_RX_UUID), properties: 0x0Cu64,
|
||||
value: std::ptr::null::<AnyObject>(), permissions: 0x02u64];
|
||||
// TX (read + notify)
|
||||
let tx_raw: *mut AnyObject = msg_send![char_cls, alloc];
|
||||
let tx_raw: *mut AnyObject = msg_send![tx_raw,
|
||||
initWithType: cbuuid(&RATSPEAK_TX_UUID), properties: 0x12u64,
|
||||
value: std::ptr::null::<AnyObject>(), permissions: 0x01u64];
|
||||
// Keep the registry pointer valid for notify_tx.
|
||||
let _: *mut AnyObject = msg_send![tx_raw, retain];
|
||||
register_characteristic(RATSPEAK_TX_UUID, tx_raw);
|
||||
// No static ID characteristic: it exposed a MAC-rotation-stable
|
||||
// identity read to any connecting scanner (a tracking vector) and
|
||||
// was never read by this stack — identity is learned from signed
|
||||
// announces instead.
|
||||
|
||||
// Ratspeak service (primary)
|
||||
let svc_raw: *mut AnyObject = msg_send![svc_cls, alloc];
|
||||
let svc_raw: *mut AnyObject = msg_send![svc_raw,
|
||||
initWithType: cbuuid(&RATSPEAK_SERVICE_UUID), primary: true];
|
||||
let char_ptrs = [rx_raw as *const AnyObject, tx_raw as *const AnyObject];
|
||||
let chars: *mut AnyObject = msg_send![arr_cls,
|
||||
arrayWithObjects: char_ptrs.as_ptr(), count: 2usize];
|
||||
let _: () = msg_send![svc_raw, setCharacteristics: chars];
|
||||
let _: () = msg_send![mgr_raw, addService: svc_raw];
|
||||
|
||||
// Columba compat (secondary, omitted from advertising payload).
|
||||
let c_rx_raw: *mut AnyObject = msg_send![char_cls, alloc];
|
||||
let c_rx_raw: *mut AnyObject = msg_send![c_rx_raw,
|
||||
initWithType: cbuuid(&COLUMBA_RX_UUID), properties: 0x0Cu64,
|
||||
value: std::ptr::null::<AnyObject>(), permissions: 0x02u64];
|
||||
let c_tx_raw: *mut AnyObject = msg_send![char_cls, alloc];
|
||||
let c_tx_raw: *mut AnyObject = msg_send![c_tx_raw,
|
||||
initWithType: cbuuid(&COLUMBA_TX_UUID), properties: 0x12u64,
|
||||
value: std::ptr::null::<AnyObject>(), permissions: 0x01u64];
|
||||
let _: *mut AnyObject = msg_send![c_tx_raw, retain];
|
||||
register_characteristic(COLUMBA_TX_UUID, c_tx_raw);
|
||||
let c_svc_raw: *mut AnyObject = msg_send![svc_cls, alloc];
|
||||
let c_svc_raw: *mut AnyObject = msg_send![c_svc_raw,
|
||||
initWithType: cbuuid(&COLUMBA_SERVICE_UUID), primary: false];
|
||||
let c_char_ptrs = [c_rx_raw as *const AnyObject, c_tx_raw as *const AnyObject];
|
||||
let c_chars: *mut AnyObject = msg_send![arr_cls,
|
||||
arrayWithObjects: c_char_ptrs.as_ptr(), count: 2usize];
|
||||
let _: () = msg_send![c_svc_raw, setCharacteristics: c_chars];
|
||||
let _: () = msg_send![mgr_raw, addService: c_svc_raw];
|
||||
autoreleasepool(|_| unsafe {
|
||||
let gatt = build_gatt_services()?;
|
||||
let dict_cls = AnyClass::get(c"NSDictionary").ok_or("NSDictionary not found")?;
|
||||
// The registry owns these +1s until it is drained.
|
||||
register_characteristic(RATSPEAK_TX_UUID, Retained::into_raw(gatt.ratspeak_tx));
|
||||
register_characteristic(COLUMBA_TX_UUID, Retained::into_raw(gatt.columba_tx));
|
||||
// The manager retains each service.
|
||||
let _: () = msg_send![mgr_raw, addService: &*gatt.ratspeak];
|
||||
let _: () = msg_send![mgr_raw, addService: &*gatt.columba];
|
||||
|
||||
// One 128-bit UUID fits in the 31-byte BLE 4.x adv PDU; two do not.
|
||||
let ad_key = NSString::from_str("kCBAdvDataServiceUUIDs");
|
||||
let uuid_ptrs = [cbuuid(&RATSPEAK_SERVICE_UUID) as *const AnyObject];
|
||||
let uuid_arr: *mut AnyObject = msg_send![arr_cls,
|
||||
arrayWithObjects: uuid_ptrs.as_ptr(), count: 1usize];
|
||||
let uuid_arr = nsarray(&[&*cbuuid(&RATSPEAK_SERVICE_UUID)]);
|
||||
let ad_dict: *mut AnyObject = msg_send![dict_cls,
|
||||
dictionaryWithObject: uuid_arr, forKey: &*ad_key];
|
||||
dictionaryWithObject: &*uuid_arr, forKey: &*ad_key];
|
||||
let _: () = msg_send![mgr_raw, startAdvertising: ad_dict];
|
||||
|
||||
tracing::info!(
|
||||
@@ -2755,7 +2682,53 @@ mod apple_peripheral {
|
||||
"Apple BLE Peripheral: advertising started"
|
||||
);
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
struct GattServices {
|
||||
ratspeak: Retained<AnyObject>,
|
||||
columba: Retained<AnyObject>,
|
||||
ratspeak_tx: Retained<AnyObject>,
|
||||
columba_tx: Retained<AnyObject>,
|
||||
}
|
||||
|
||||
/// Call inside `autoreleasepool`: the CBUUIDs autorelease. No static ID
|
||||
/// characteristic: it exposed a MAC-rotation-stable identity read to any
|
||||
/// connecting scanner (a tracking vector) and was never read by this
|
||||
/// stack — identity is learned from signed announces instead.
|
||||
unsafe fn build_gatt_services() -> Result<GattServices, String> {
|
||||
let char_cls =
|
||||
AnyClass::get(c"CBMutableCharacteristic").ok_or("CBMutableCharacteristic not found")?;
|
||||
let svc_cls = AnyClass::get(c"CBMutableService").ok_or("CBMutableService not found")?;
|
||||
// RX: write + writeNoResponse, writeable. TX: read + notify, readable.
|
||||
let characteristic = |uuid: &Uuid, properties: u64, permissions: u64| unsafe {
|
||||
let obj: Allocated<AnyObject> = msg_send![char_cls, alloc];
|
||||
let obj: Retained<AnyObject> = msg_send![obj,
|
||||
initWithType: &*cbuuid(uuid), properties: properties,
|
||||
value: std::ptr::null::<AnyObject>(), permissions: permissions];
|
||||
obj
|
||||
};
|
||||
let service = |uuid: &Uuid, primary: bool, rx: &AnyObject, tx: &AnyObject| unsafe {
|
||||
let obj: Allocated<AnyObject> = msg_send![svc_cls, alloc];
|
||||
let obj: Retained<AnyObject> =
|
||||
msg_send![obj, initWithType: &*cbuuid(uuid), primary: primary];
|
||||
let chars = nsarray(&[rx, tx]);
|
||||
let _: () = msg_send![&*obj, setCharacteristics: &*chars];
|
||||
obj
|
||||
};
|
||||
let rx = characteristic(&RATSPEAK_RX_UUID, 0x0C, 0x02);
|
||||
let ratspeak_tx = characteristic(&RATSPEAK_TX_UUID, 0x12, 0x01);
|
||||
let ratspeak = service(&RATSPEAK_SERVICE_UUID, true, &rx, &ratspeak_tx);
|
||||
// Columba compat: secondary, omitted from the advertising payload.
|
||||
let c_rx = characteristic(&COLUMBA_RX_UUID, 0x0C, 0x02);
|
||||
let columba_tx = characteristic(&COLUMBA_TX_UUID, 0x12, 0x01);
|
||||
let columba = service(&COLUMBA_SERVICE_UUID, false, &c_rx, &columba_tx);
|
||||
Ok(GattServices {
|
||||
ratspeak,
|
||||
columba,
|
||||
ratspeak_tx,
|
||||
columba_tx,
|
||||
})
|
||||
}
|
||||
|
||||
/// Walks the lifecycle state machine in lockstep with the platform
|
||||
@@ -2829,9 +2802,9 @@ mod apple_peripheral {
|
||||
let mgr_send = SendPtr(mgr_ptr);
|
||||
|
||||
if needs_stop_ad {
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![mgr_send.0, stopAdvertising];
|
||||
}
|
||||
});
|
||||
// CB has no peripheralManagerDidStopAdvertising delegate — poll
|
||||
// `isAdvertising`. Radio flips within ~20ms; 1s budget covers
|
||||
// contended radios and bounce loops.
|
||||
@@ -2855,13 +2828,13 @@ mod apple_peripheral {
|
||||
apply_event(crate::ble_peer_lifecycle::LifecycleEvent::AdvertiseStopped);
|
||||
}
|
||||
|
||||
unsafe {
|
||||
autoreleasepool(|_| unsafe {
|
||||
let _: () = msg_send![mgr_send.0, removeAllServices];
|
||||
}
|
||||
});
|
||||
apply_event(crate::ble_peer_lifecycle::LifecycleEvent::ServicesRemoved);
|
||||
|
||||
// Without this, every toggle cycle leaks two CBMutableCharacteristic
|
||||
// pointers and notify_tx can race onto dead characteristics post-teardown.
|
||||
// Releases the registry's TX characteristics, so notify_tx can't race
|
||||
// onto dead characteristics post-teardown.
|
||||
{
|
||||
let mut map = characteristic_registry().lock().unwrap();
|
||||
for (_, ptr) in map.drain() {
|
||||
@@ -2930,6 +2903,15 @@ mod apple_peripheral {
|
||||
mod notify_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn gatt_services_hold_no_extra_retains() {
|
||||
assert!(crate::apple_objc::tests::freed_on_drop(|| {
|
||||
autoreleasepool(|_| {
|
||||
let g = unsafe { build_gatt_services() }.unwrap();
|
||||
vec![g.ratspeak, g.columba, g.ratspeak_tx, g.columba_tx]
|
||||
})
|
||||
}));
|
||||
}
|
||||
#[test]
|
||||
fn readiness_keeps_partial_packet_first_across_characteristics() {
|
||||
let mut state = NotifyState {
|
||||
accepting: true,
|
||||
|
||||
@@ -9,6 +9,8 @@ pub mod android_usb;
|
||||
mod android_usb_lifecycle;
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
mod android_usb_setup;
|
||||
#[cfg(all(feature = "ble", any(target_os = "ios", target_os = "macos")))]
|
||||
mod apple_objc;
|
||||
pub mod auto;
|
||||
pub mod ax25kiss;
|
||||
pub mod backbone;
|
||||
|
||||
Reference in new issue
Block a user